blob: 7cc828eba0b3044386c4dfe668481d485d99ccd9 [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();
2040 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002041 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2042 dex_file_location.c_str(),
2043 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002044 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002045 return false;
2046 }
2047
2048 if (app_image) {
2049 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2050 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002051 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002052 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002053 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002054 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002055 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002056 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002057 }
2058 }
2059 } else {
2060 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002061 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2062 this,
2063 dex_cache->GetResolvedMethods(),
2064 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002065 }
2066 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002067 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002068 }
2069 out_dex_files->push_back(std::move(dex_file));
2070 }
2071
2072 if (app_image) {
2073 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002074 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002075 // Check that the class loader resolves the same way as the ones in the image.
2076 // Image class loader [A][B][C][image dex files]
2077 // Class loader = [???][dex_elements][image dex files]
2078 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002079 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002080 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2081 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2082 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002083 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2084 *error_msg = "Unexpected BootClassLoader in app image";
2085 return false;
2086 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002087 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2088 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2089 // special case the comparison of dex files of the two class loaders, but then do full
2090 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002091 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002092 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002093 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2094 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2095 if (element != nullptr) {
2096 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002097 ObjPtr<mirror::String> name;
2098 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2099 loader_dex_file_names.push_back(name);
2100 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002101 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002102 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002103 std::string temp_error_msg;
2104 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2105 bool success = GetDexFileNames(
2106 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2107 if (success) {
2108 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2109 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2110 static_cast<size_t>(dex_caches->GetLength()));
2111 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2112 image_dex_file_names.resize(image_count);
2113 success = success && CompareDexFiles(image_dex_file_names,
2114 loader_dex_file_names,
2115 &temp_error_msg);
2116 success = success && CompareClassLoaders(soa,
2117 image_class_loader.Get(),
2118 class_loader.Get(),
2119 /*check_dex_file_names=*/ false,
2120 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002121 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002122 if (!success) {
2123 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2124 temp_error_msg.c_str());
2125 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002126 }
2127 }
2128
2129 if (kSanityCheckObjects) {
2130 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002131 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002132 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2133 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2134 if (field != nullptr) {
2135 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2136 }
2137 }
2138 }
2139 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002140 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002141 }
2142 }
2143
2144 // Set entry point to interpreter if in InterpretOnly mode.
2145 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002146 // Set image methods' entry point to interpreter.
2147 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2148 if (!method.IsRuntimeMethod()) {
2149 DCHECK(method.GetDeclaringClass() != nullptr);
2150 if (!method.IsNative() && !method.IsResolutionMethod()) {
2151 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2152 image_pointer_size_);
2153 }
2154 }
2155 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002156 }
2157
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002158 ClassTable* class_table = nullptr;
2159 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002160 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002161 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002162 }
2163 // If we have a class table section, read it and use it for verification in
2164 // UpdateAppImageClassLoadersAndDexCaches.
2165 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002166 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002167 const bool added_class_table = class_table_section.Size() > 0u;
2168 if (added_class_table) {
2169 const uint64_t start_time2 = NanoTime();
2170 size_t read_count = 0;
2171 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2172 /*make copy*/false,
2173 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002174 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002175 }
2176 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002177 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002178
2179 {
2180 ScopedTrace trace("AppImage:UpdateClassLoaders");
2181 // Update class loader and resolved strings. If added_class_table is false, the resolved
2182 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002183 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002184 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002185 // Note: We probably don't need the read barrier unless we copy the app image objects into
2186 // the region space.
2187 ObjPtr<mirror::Class> klass(root.Read());
2188 // Do not update class loader for boot image classes where the app image
2189 // class loader is only the initiating loader but not the defining loader.
2190 // Avoid read barrier since we are comparing against null.
2191 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2192 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2193 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002194 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002195 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002196
Vladimir Marko305c38b2018-02-14 11:50:07 +00002197 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002198 // Every class in the app image has initially SubtypeCheckInfo in the
2199 // Uninitialized state.
2200 //
2201 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2202 // after class initialization is complete. The app image ClassStatus as-is
2203 // are almost all ClassStatus::Initialized, and being in the
2204 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2205 //
2206 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2207 //
2208 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002209 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002210 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2211 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002212 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002213 }
2214 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002215 }
2216 if (!oat_file->GetBssGcRoots().empty()) {
2217 // Insert oat file to class table for visiting .bss GC roots.
2218 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002219 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002220
Mathieu Chartier69731002016-03-02 16:08:31 -08002221 if (added_class_table) {
2222 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2223 class_table->AddClassSet(std::move(temp_set));
2224 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002225
Mathieu Chartier69731002016-03-02 16:08:31 -08002226 if (kIsDebugBuild && app_image) {
2227 // This verification needs to happen after the classes have been added to the class loader.
2228 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002229 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002230 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002231 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002232
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002233 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002234 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002235}
2236
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002237bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002238 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2239 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002240}
2241
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002242void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002243 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2244 // enabling tracing requires the mutator lock, there are no race conditions here.
2245 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002246 Thread* const self = Thread::Current();
2247 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002248 if (kUseReadBarrier) {
2249 // We do not track new roots for CC.
2250 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2251 kVisitRootFlagClearRootLog |
2252 kVisitRootFlagStartLoggingNewRoots |
2253 kVisitRootFlagStopLoggingNewRoots));
2254 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002255 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002256 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2257 // There is 3 GC cases to handle:
2258 // Non moving concurrent:
2259 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002260 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002261 //
2262 // Moving non-concurrent:
2263 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2264 // To prevent missing roots, this case needs to ensure that there is no
2265 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2266 // class which is in the class table.
2267 //
2268 // Moving concurrent:
2269 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2270 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002271 //
2272 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2273 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2274 // these objects.
2275 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002276 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002277 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002278 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002279 for (const ClassLoaderData& data : class_loaders_) {
2280 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2281 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2282 }
2283 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002284 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002285 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002286 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002287 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002288 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002289 // Concurrent moving GC marked new roots through the to-space invariant.
2290 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002291 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002292 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2293 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2294 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2295 if (old_ref != nullptr) {
2296 DCHECK(old_ref->IsClass());
2297 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2298 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2299 // Concurrent moving GC marked new roots through the to-space invariant.
2300 CHECK_EQ(new_ref, old_ref);
2301 }
2302 }
2303 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002304 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002305 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002306 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002307 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002308 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002309 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002310 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002311 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002312 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002313 }
2314 // We deliberately ignore the class roots in the image since we
2315 // handle image roots by using the MS/CMS rescanning of dirty cards.
2316}
2317
Brian Carlstroma663ea52011-08-19 23:33:41 -07002318// Keep in sync with InitCallback. Anything we visit, we need to
2319// reinit references to when reinitializing a ClassLinker from a
2320// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002321void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002322 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002323 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002324 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2325 // unloading if we are marking roots.
2326 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002327}
2328
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002329class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2330 public:
2331 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2332 : visitor_(visitor),
2333 done_(false) {}
2334
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002335 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002336 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002337 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002338 if (!done_ && class_table != nullptr) {
2339 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2340 if (!class_table->Visit(visitor)) {
2341 // If the visitor ClassTable returns false it means that we don't need to continue.
2342 done_ = true;
2343 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002344 }
2345 }
2346
2347 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002348 // Class visitor that limits the class visits from a ClassTable to the classes with
2349 // the provided defining class loader. This filter is used to avoid multiple visits
2350 // of the same class which can be recorded for multiple initiating class loaders.
2351 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2352 public:
2353 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2354 ClassVisitor* visitor)
2355 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2356
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002357 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002358 if (klass->GetClassLoader() != defining_class_loader_) {
2359 return true;
2360 }
2361 return (*visitor_)(klass);
2362 }
2363
Vladimir Marko0984e482019-03-27 16:41:41 +00002364 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002365 ClassVisitor* const visitor_;
2366 };
2367
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002368 ClassVisitor* const visitor_;
2369 // If done is true then we don't need to do any more visiting.
2370 bool done_;
2371};
2372
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002373void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002374 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002375 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2376 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002377 }
2378}
2379
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002380void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002381 Thread* const self = Thread::Current();
2382 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2383 // Not safe to have thread suspension when we are holding a lock.
2384 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002385 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002386 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002387 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002388 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002389 }
2390}
2391
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002392class GetClassesInToVector : public ClassVisitor {
2393 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002394 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002395 classes_.push_back(klass);
2396 return true;
2397 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002398 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002399};
2400
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002401class GetClassInToObjectArray : public ClassVisitor {
2402 public:
2403 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2404 : arr_(arr), index_(0) {}
2405
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002406 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002407 ++index_;
2408 if (index_ <= arr_->GetLength()) {
2409 arr_->Set(index_ - 1, klass);
2410 return true;
2411 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002412 return false;
2413 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002414
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002415 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002416 return index_ <= arr_->GetLength();
2417 }
2418
2419 private:
2420 mirror::ObjectArray<mirror::Class>* const arr_;
2421 int32_t index_;
2422};
2423
2424void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002425 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2426 // is avoiding duplicates.
2427 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002428 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002429 GetClassesInToVector accumulator;
2430 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002431 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002432 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002433 return;
2434 }
2435 }
2436 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002437 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002438 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002439 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002440 // We size the array assuming classes won't be added to the class table during the visit.
2441 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002442 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002443 size_t class_table_size;
2444 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002445 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002446 // Add 100 in case new classes get loaded when we are filling in the object array.
2447 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002448 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002449 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002450 classes.Assign(
2451 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002452 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002453 GetClassInToObjectArray accumulator(classes.Get());
2454 VisitClasses(&accumulator);
2455 if (accumulator.Succeeded()) {
2456 break;
2457 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002458 }
2459 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2460 // If the class table shrank during creation of the clases array we expect null elements. If
2461 // the class table grew then the loop repeats. If classes are created after the loop has
2462 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002463 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002464 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002465 return;
2466 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002467 }
2468 }
2469}
2470
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002471ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002472 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002473 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002474 // CHA unloading analysis is not needed. No negative consequences are expected because
2475 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002476 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002477 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002478 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002479}
2480
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002481void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002482 Runtime* const runtime = Runtime::Current();
2483 JavaVMExt* const vm = runtime->GetJavaVM();
2484 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002485 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002486 if (runtime->GetJit() != nullptr) {
2487 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2488 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002489 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002490 code_cache->RemoveMethodsIn(self, *data.allocator);
2491 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002492 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002493 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002494 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002495 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002496 // Cleanup references to single implementation ArtMethods that will be deleted.
2497 if (cleanup_cha) {
2498 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2499 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2500 }
2501
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002502 delete data.allocator;
2503 delete data.class_table;
2504}
2505
Vladimir Markobcf17522018-06-01 13:14:32 +01002506ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2507 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002508 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002509 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2510 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002511}
2512
Vladimir Markobcf17522018-06-01 13:14:32 +01002513ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2514 Thread* self,
2515 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002516 StackHandleScope<1> hs(self);
2517 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002518 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002519 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002520 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002521 self->AssertPendingOOMException();
2522 return nullptr;
2523 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002524 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002525 if (location == nullptr) {
2526 self->AssertPendingOOMException();
2527 return nullptr;
2528 }
2529 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002530 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002531}
2532
Vladimir Markobcf17522018-06-01 13:14:32 +01002533ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2534 const DexFile& dex_file,
2535 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002536 ObjPtr<mirror::String> location = nullptr;
2537 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002538 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002539 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002540 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002541 mirror::DexCache::InitializeDexCache(self,
2542 dex_cache,
2543 location,
2544 &dex_file,
2545 linear_alloc,
2546 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002547 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002548 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002549}
2550
Roland Levillain0e840272018-08-23 19:55:30 +01002551template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002552ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2553 ObjPtr<mirror::Class> java_lang_Class,
2554 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002555 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002556 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002557 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002558 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002559 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2560 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002561 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002562 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002563 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002564 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002565 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002566}
2567
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002568ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002569 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002570}
2571
Roland Levillain0e840272018-08-23 19:55:30 +01002572ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2573 ObjPtr<mirror::Class> java_lang_Class) {
2574 // We make this class non-movable for the unlikely case where it were to be
2575 // moved by a sticky-bit (minor) collection when using the Generational
2576 // Concurrent Copying (CC) collector, potentially creating a stale reference
2577 // in the `klass_` field of one of its instances allocated in the Large-Object
2578 // Space (LOS) -- see the comment about the dirty card scanning logic in
2579 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002580 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002581 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2582}
2583
Vladimir Markobcf17522018-06-01 13:14:32 +01002584ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002585 Thread* self,
2586 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002587 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002588 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002589}
2590
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002591ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2592 const char* descriptor,
2593 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002594 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002595 if (kIsDebugBuild) {
2596 StackHandleScope<1> hs(self);
2597 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2598 Thread::PoisonObjectPointersIfDebug();
2599 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002600
2601 // For temporary classes we must wait for them to be retired.
2602 if (init_done_ && klass->IsTemp()) {
2603 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002604 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002605 ThrowEarlierClassFailure(klass);
2606 return nullptr;
2607 }
2608 StackHandleScope<1> hs(self);
2609 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2610 ObjectLock<mirror::Class> lock(self, h_class);
2611 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002612 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002613 lock.WaitIgnoringInterrupts();
2614 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002615 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002616 ThrowEarlierClassFailure(h_class.Get());
2617 return nullptr;
2618 }
2619 CHECK(h_class->IsRetired());
2620 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002621 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002622 }
2623
Brian Carlstromaded5f72011-10-07 17:15:04 -07002624 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002625 size_t index = 0;
2626 // Maximum number of yield iterations until we start sleeping.
2627 static const size_t kNumYieldIterations = 1000;
2628 // How long each sleep is in us.
2629 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002630 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002631 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002632 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002633 {
2634 ObjectTryLock<mirror::Class> lock(self, h_class);
2635 // Can not use a monitor wait here since it may block when returning and deadlock if another
2636 // thread has locked klass.
2637 if (lock.Acquired()) {
2638 // Check for circular dependencies between classes, the lock is required for SetStatus.
2639 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2640 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002641 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002642 return nullptr;
2643 }
2644 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002646 {
2647 // Handle wrapper deals with klass moving.
2648 ScopedThreadSuspension sts(self, kSuspended);
2649 if (index < kNumYieldIterations) {
2650 sched_yield();
2651 } else {
2652 usleep(kSleepDurationUS);
2653 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002654 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002655 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002656 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002657
Vladimir Marko72ab6842017-01-20 19:32:50 +00002658 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002659 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002660 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002661 }
2662 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002663 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002664 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002665 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002666}
2667
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002668using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002669
2670// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002671ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002672 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002673 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002674 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002675 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002676 return ClassPathEntry(dex_file, dex_class_def);
2677 }
2678 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002679 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002680}
2681
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002682bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2683 Thread* self,
2684 const char* descriptor,
2685 size_t hash,
2686 Handle<mirror::ClassLoader> class_loader,
2687 /*out*/ ObjPtr<mirror::Class>* result) {
2688 ArtField* field =
2689 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2690 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2691 if (raw_shared_libraries == nullptr) {
2692 return true;
2693 }
2694
2695 StackHandleScope<2> hs(self);
2696 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2697 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2698 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2699 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2700 temp_loader.Assign(shared_libraries->Get(i));
2701 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2702 return false; // One of the shared libraries is not supported.
2703 }
2704 if (*result != nullptr) {
2705 return true; // Found the class up the chain.
2706 }
2707 }
2708 return true;
2709}
2710
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002711bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2712 Thread* self,
2713 const char* descriptor,
2714 size_t hash,
2715 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002716 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002717 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002718 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002719 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002720 return true;
2721 }
2722
David Brazdil05909d82018-12-06 16:25:16 +00002723 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002724 // For regular path or dex class loader the search order is:
2725 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002726 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002727 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002728
Calin Juravlecdd49122017-07-05 20:09:53 -07002729 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2730 StackHandleScope<1> hs(self);
2731 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2732 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2733 return false; // One of the parents is not supported.
2734 }
2735 if (*result != nullptr) {
2736 return true; // Found the class up the chain.
2737 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002738
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002739 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2740 return false; // One of the shared library loader is not supported.
2741 }
2742 if (*result != nullptr) {
2743 return true; // Found the class in a shared library.
2744 }
2745
Calin Juravlecdd49122017-07-05 20:09:53 -07002746 // Search the current class loader classpath.
2747 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002748 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002749 }
2750
Calin Juravlecdd49122017-07-05 20:09:53 -07002751 if (IsDelegateLastClassLoader(soa, class_loader)) {
2752 // For delegate last, the search order is:
2753 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002754 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002755 // - class loader dex files
2756 // - parent
2757 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2758 if (*result != nullptr) {
2759 return true; // The class is part of the boot class path.
2760 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002761 if (self->IsExceptionPending()) {
2762 // Pending exception means there was an error other than ClassNotFound that must be returned
2763 // to the caller.
2764 return false;
2765 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002766
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002767 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2768 return false; // One of the shared library loader is not supported.
2769 }
2770 if (*result != nullptr) {
2771 return true; // Found the class in a shared library.
2772 }
2773
Calin Juravlecdd49122017-07-05 20:09:53 -07002774 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2775 if (*result != nullptr) {
2776 return true; // Found the class in the current class loader
2777 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002778 if (self->IsExceptionPending()) {
2779 // Pending exception means there was an error other than ClassNotFound that must be returned
2780 // to the caller.
2781 return false;
2782 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002783
2784 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2785 StackHandleScope<1> hs(self);
2786 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2787 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2788 }
2789
2790 // Unsupported class loader.
2791 *result = nullptr;
2792 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002793}
2794
Andreas Gampe501c3b02019-04-17 21:54:27 +00002795namespace {
2796
2797// Matches exceptions caught in DexFile.defineClass.
2798ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2799 ClassLinker* class_linker)
2800 REQUIRES_SHARED(Locks::mutator_lock_) {
2801 return
2802 // ClassNotFoundException.
2803 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2804 class_linker))
2805 ||
2806 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2807 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2808}
2809
2810// Clear exceptions caught in DexFile.defineClass.
2811ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2812 REQUIRES_SHARED(Locks::mutator_lock_) {
2813 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2814 self->ClearException();
2815 }
2816}
2817
2818} // namespace
2819
Calin Juravle415dc3d2017-06-28 11:03:12 -07002820// Finds the class in the boot class loader.
2821// If the class is found the method returns the resolved class. Otherwise it returns null.
2822ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2823 const char* descriptor,
2824 size_t hash) {
2825 ObjPtr<mirror::Class> result = nullptr;
2826 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2827 if (pair.second != nullptr) {
2828 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2829 if (klass != nullptr) {
2830 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002831 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002832 result = DefineClass(self,
2833 descriptor,
2834 hash,
2835 ScopedNullHandle<mirror::ClassLoader>(),
2836 *pair.first,
2837 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002838 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002839 if (result == nullptr) {
2840 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002841 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002842 }
2843 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002844 return result;
2845}
Andreas Gampef865ea92015-04-13 22:14:19 -07002846
Calin Juravle415dc3d2017-06-28 11:03:12 -07002847ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2848 ScopedObjectAccessAlreadyRunnable& soa,
2849 const char* descriptor,
2850 size_t hash,
2851 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002852 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2853 IsInMemoryDexClassLoader(soa, class_loader) ||
2854 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002855 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002856
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002857 ObjPtr<mirror::Class> ret;
2858 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002859 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002860 if (dex_class_def != nullptr) {
2861 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2862 descriptor,
2863 hash,
2864 class_loader,
2865 *cp_dex_file,
2866 *dex_class_def);
2867 if (klass == nullptr) {
2868 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002869 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002870 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00002871 } else {
2872 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002873 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002874 ret = klass;
2875 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002876 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002877 return true; // Continue with the next DexFile.
2878 };
2879
2880 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2881 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002882}
2883
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002884ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2885 const char* descriptor,
2886 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002887 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002888 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002889 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002890 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002891 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002892 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2893 // for primitive classes that aren't backed by dex files.
2894 return FindPrimitiveClass(descriptor[0]);
2895 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002896 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002897 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002898 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002899 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002900 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002901 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002902 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002903 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002904 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002905 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002906 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002907 return DefineClass(self,
2908 descriptor,
2909 hash,
2910 ScopedNullHandle<mirror::ClassLoader>(),
2911 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002912 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002913 } else {
2914 // The boot class loader is searched ahead of the application class loader, failures are
2915 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2916 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002917 ObjPtr<mirror::Throwable> pre_allocated =
2918 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002919 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002920 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002921 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002922 }
2923 ObjPtr<mirror::Class> result_ptr;
2924 bool descriptor_equals;
2925 if (descriptor[0] == '[') {
2926 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2927 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2928 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2929 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002930 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002931 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002932 bool known_hierarchy =
2933 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2934 if (result_ptr != nullptr) {
2935 // The chain was understood and we found the class. We still need to add the class to
2936 // the class table to protect from racy programs that can try and redefine the path list
2937 // which would change the Class<?> returned for subsequent evaluation of const-class.
2938 DCHECK(known_hierarchy);
2939 DCHECK(result_ptr->DescriptorEquals(descriptor));
2940 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002941 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002942 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002943 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2944 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002945 //
2946 // If the chain was understood but we did not find the class, let the Java-side
2947 // rediscover all this and throw the exception with the right stack trace. Note that
2948 // the Java-side could still succeed for racy programs if another thread is actively
2949 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002950
Alex Light185a4612018-10-04 15:54:25 -07002951 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002952 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002953 // Oops, we can't call into java so we can't run actual class-loader code.
2954 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002955 ObjPtr<mirror::Throwable> pre_allocated =
2956 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2957 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002958 return nullptr;
2959 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002960
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002961 // Inlined DescriptorToDot(descriptor) with extra validation.
2962 //
2963 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2964 // the DescriptorEquals() check below and give a confusing error message. For example,
2965 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2966 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2967 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2968 size_t descriptor_length = strlen(descriptor);
2969 if (UNLIKELY(descriptor[0] != 'L') ||
2970 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2971 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2972 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2973 return nullptr;
2974 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002975
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002976 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2977 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Mathieu Chartierd399f572019-04-17 12:34:19 -07002978 ScopedLocalRef<jobject> class_loader_object(
2979 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2980 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2981 {
2982 ScopedThreadStateChange tsc(self, kNative);
2983 ScopedLocalRef<jobject> class_name_object(
2984 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2985 if (class_name_object.get() == nullptr) {
2986 DCHECK(self->IsExceptionPending()); // OOME.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002987 return nullptr;
2988 }
Mathieu Chartierd399f572019-04-17 12:34:19 -07002989 CHECK(class_loader_object.get() != nullptr);
2990 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2991 WellKnownClasses::java_lang_ClassLoader_loadClass,
2992 class_name_object.get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002993 }
Mathieu Chartierd399f572019-04-17 12:34:19 -07002994 if (result.get() == nullptr && !self->IsExceptionPending()) {
2995 // broken loader - throw NPE to be compatible with Dalvik
2996 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2997 class_name_string.c_str()).c_str());
2998 return nullptr;
2999 }
3000 result_ptr = soa.Decode<mirror::Class>(result.get());
3001 // Check the name of the returned class.
3002 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Andreas Gampe501c3b02019-04-17 21:54:27 +00003003 } else {
3004 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003005 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003006 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003007
3008 if (self->IsExceptionPending()) {
3009 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3010 // However, to comply with the RI behavior, first check if another thread succeeded.
3011 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3012 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3013 self->ClearException();
3014 return EnsureResolved(self, descriptor, result_ptr);
3015 }
3016 return nullptr;
3017 }
3018
3019 // Try to insert the class to the class table, checking for mismatch.
3020 ObjPtr<mirror::Class> old;
3021 {
3022 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3023 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3024 old = class_table->Lookup(descriptor, hash);
3025 if (old == nullptr) {
3026 old = result_ptr; // For the comparison below, after releasing the lock.
3027 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003028 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003029 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003030 } // else throw below, after releasing the lock.
3031 }
3032 }
3033 if (UNLIKELY(old != result_ptr)) {
3034 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3035 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003036 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003037 const char* loader_class_name =
3038 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3039 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3040 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3041 << DescriptorToDot(descriptor) << "\").";
3042 return EnsureResolved(self, descriptor, old);
3043 }
3044 if (UNLIKELY(!descriptor_equals)) {
3045 std::string result_storage;
3046 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3047 std::string loader_storage;
3048 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3049 ThrowNoClassDefFoundError(
3050 "Initiating class loader of type %s returned class %s instead of %s.",
3051 DescriptorToDot(loader_class_name).c_str(),
3052 DescriptorToDot(result_name).c_str(),
3053 DescriptorToDot(descriptor).c_str());
3054 return nullptr;
3055 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003056 // Success.
3057 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003058}
3059
Vladimir Markob9c29f62019-03-20 14:22:51 +00003060static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3061 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003062 return
3063 // Reserved conscrypt packages (includes sub-packages under these paths).
3064 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3065 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3066 // Reserved updatable-media package (includes sub-packages under this path).
3067 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003068}
3069
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003070ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3071 const char* descriptor,
3072 size_t hash,
3073 Handle<mirror::ClassLoader> class_loader,
3074 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003075 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003076 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003077 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003078
Brian Carlstromaded5f72011-10-07 17:15:04 -07003079 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003080 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003081 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003082 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003083 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003084 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003085 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003086 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003087 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003088 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003089 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003090 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003091 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003092 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003093 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003094 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003095 }
3096
Vladimir Markob9c29f62019-03-20 14:22:51 +00003097 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3098 // some runtime modules. Prevent definition of classes in app class loader that could clash
3099 // with these modules as these classes could be resolved differently during execution.
3100 if (class_loader != nullptr &&
3101 Runtime::Current()->IsAotCompiler() &&
3102 IsReservedBootClassPathDescriptor(descriptor)) {
3103 ObjPtr<mirror::Throwable> pre_allocated =
3104 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3105 self->SetException(pre_allocated);
3106 return nullptr;
3107 }
3108
Alex Lighte9f61032018-09-24 16:04:51 -07003109 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3110 // code to be executed. We put it up here so we can avoid all the allocations associated with
3111 // creating the class. This can happen with (eg) jit threads.
3112 if (!self->CanLoadClasses()) {
3113 // Make sure we don't try to load anything, potentially causing an infinite loop.
3114 ObjPtr<mirror::Throwable> pre_allocated =
3115 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3116 self->SetException(pre_allocated);
3117 return nullptr;
3118 }
3119
Andreas Gampefa4333d2017-02-14 11:10:34 -08003120 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003121 // Allocate a class with the status of not ready.
3122 // Interface object should get the right size here. Regular class will
3123 // figure out the right size later and be replaced with one of the right
3124 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003125 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003126 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003127 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003128 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003129 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003130 }
Alex Lightb0f11922017-01-23 14:25:17 -08003131 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3132 // nothing.
3133 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003134 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003135 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3136 // will only be called once.
3137 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3138 klass,
3139 class_loader,
3140 dex_file,
3141 dex_class_def,
3142 &new_dex_file,
3143 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003144 // Check to see if an exception happened during runtime callbacks. Return if so.
3145 if (self->IsExceptionPending()) {
3146 return nullptr;
3147 }
Alex Lightb0f11922017-01-23 14:25:17 -08003148 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003149 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003150 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003151 return nullptr;
3152 }
3153 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003154 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003155
Jeff Hao848f70a2014-01-15 13:49:50 -08003156 // Mark the string class by setting its access flag.
3157 if (UNLIKELY(!init_done_)) {
3158 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3159 klass->SetStringClass();
3160 }
3161 }
3162
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003163 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003164 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003165 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003166 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003167
Mathieu Chartier590fee92013-09-13 13:46:47 -07003168 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003169 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003170 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003171 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3172 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003173 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003174 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003175
Mathieu Chartierc7853442015-03-27 14:35:38 -07003176 // Load the fields and other things after we are inserted in the table. This is so that we don't
3177 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3178 // other reason is that the field roots are only visited from the class table. So we need to be
3179 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003180 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003181 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003182 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003183 // An exception occured during load, set status to erroneous while holding klass' lock in case
3184 // notification is necessary.
3185 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003186 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003187 }
3188 return nullptr;
3189 }
3190
Brian Carlstromaded5f72011-10-07 17:15:04 -07003191 // Finish loading (if necessary) by finding parents
3192 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003193 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003194 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003195 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003196 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003197 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003198 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003199 }
3200 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003201
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003202 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003203 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003204 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003205
Brian Carlstromaded5f72011-10-07 17:15:04 -07003206 // Link the class (if necessary)
3207 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003208 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003209 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003210
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003211 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003212 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003213 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003214 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003215 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003216 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003217 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003218 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003219 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003220 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003221 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003222
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003223 // Instrumentation may have updated entrypoints for all methods of all
3224 // classes. However it could not update methods of this class while we
3225 // were loading it. Now the class is resolved, we can update entrypoints
3226 // as required by instrumentation.
3227 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3228 // We must be in the kRunnable state to prevent instrumentation from
3229 // suspending all threads to update entrypoints while we are doing it
3230 // for this class.
3231 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003232 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003233 }
3234
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003235 /*
3236 * We send CLASS_PREPARE events to the debugger from here. The
3237 * definition of "preparation" is creating the static fields for a
3238 * class and initializing them to the standard default values, but not
3239 * executing any code (that comes later, during "initialization").
3240 *
3241 * We did the static preparation in LinkClass.
3242 *
3243 * The class has been prepared and resolved but possibly not yet verified
3244 * at this point.
3245 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003246 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003247
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003248 // Notify native debugger of the new class and its layout.
3249 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3250
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003251 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003252}
3253
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003254uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003255 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003256 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003257 size_t num_8 = 0;
3258 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003259 size_t num_32 = 0;
3260 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003261 ClassAccessor accessor(dex_file, dex_class_def);
3262 // We allow duplicate definitions of the same field in a class_data_item
3263 // but ignore the repeated indexes here, b/21868015.
3264 uint32_t last_field_idx = dex::kDexNoIndex;
3265 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3266 uint32_t field_idx = field.GetIndex();
3267 // Ordering enforced by DexFileVerifier.
3268 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3269 if (UNLIKELY(field_idx == last_field_idx)) {
3270 continue;
3271 }
3272 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003273 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003274 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3275 char c = descriptor[0];
3276 switch (c) {
3277 case 'L':
3278 case '[':
3279 num_ref++;
3280 break;
3281 case 'J':
3282 case 'D':
3283 num_64++;
3284 break;
3285 case 'I':
3286 case 'F':
3287 num_32++;
3288 break;
3289 case 'S':
3290 case 'C':
3291 num_16++;
3292 break;
3293 case 'B':
3294 case 'Z':
3295 num_8++;
3296 break;
3297 default:
3298 LOG(FATAL) << "Unknown descriptor: " << c;
3299 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003300 }
3301 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003302 return mirror::Class::ComputeClassSize(false,
3303 0,
3304 num_8,
3305 num_16,
3306 num_32,
3307 num_64,
3308 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003309 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003310}
3311
Alex Lightfc49fec2018-01-16 22:28:36 +00003312// Special case to get oat code without overwriting a trampoline.
3313const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003314 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003315 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003316 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003317 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003318 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3319 if (code != nullptr) {
3320 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003321 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003322 if (method->IsNative()) {
3323 // No code and native? Use generic trampoline.
3324 return GetQuickGenericJniStub();
3325 }
3326 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003327}
3328
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003329bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003330 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003331 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3332 return false;
3333 }
3334
Elliott Hughes956af0f2014-12-11 14:34:28 -08003335 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003336 return true;
3337 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003338
3339 Runtime* runtime = Runtime::Current();
3340 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3341 if (instr->InterpretOnly()) {
3342 return true;
3343 }
3344
3345 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3346 // Doing this check avoids doing compiled/interpreter transitions.
3347 return true;
3348 }
3349
Alex Light3dacdd62019-03-12 15:45:47 +00003350 if (Thread::Current()->IsForceInterpreter() ||
3351 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003352 // Force the use of interpreter when it is required by the debugger.
3353 return true;
3354 }
3355
Alex Light8f34aba2017-10-09 13:46:32 -07003356 if (Thread::Current()->IsAsyncExceptionPending()) {
3357 // Force use of interpreter to handle async-exceptions
3358 return true;
3359 }
3360
Alex Light2d441b12018-06-08 15:33:21 -07003361 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3362 const void* instr_target = instr->GetCodeForInvoke(method);
3363 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3364 return ShouldUseInterpreterEntrypoint(method, instr_target);
3365 }
3366
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003367 if (runtime->IsJavaDebuggable()) {
3368 // For simplicity, we ignore precompiled code and go to the interpreter
3369 // assuming we don't already have jitted code.
3370 // We could look at the oat file where `quick_code` is being defined,
3371 // and check whether it's been compiled debuggable, but we decided to
3372 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003373 jit::Jit* jit = Runtime::Current()->GetJit();
3374 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3375 }
3376
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003377 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003378 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003379 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003380 // since we want to JIT it (at first use) with extra stackmaps for native
3381 // debugging. We keep however all AOT code from the boot image,
3382 // since the JIT-at-first-use is blocking and would result in non-negligible
3383 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003384 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003385 }
3386
3387 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003388}
3389
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003390void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003391 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003392 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003393 if (klass->NumDirectMethods() == 0) {
3394 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003395 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003396 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003397 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003398 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003399 return; // OAT file unavailable.
3400 }
Ian Rogers19846512012-02-24 11:42:47 -08003401 }
Alex Light64ad14d2014-08-19 14:23:13 -07003402
Mathieu Chartierf8322842014-05-16 10:59:25 -07003403 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003404 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3405 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3406 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003407 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003408 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003409 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003410 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3411 klass->GetDexClassDefIndex(),
3412 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003413 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003414 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003415 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003416 if (!method->IsStatic()) {
3417 // Only update static methods.
3418 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003419 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003420 const void* quick_code = nullptr;
3421 if (has_oat_class) {
3422 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003423 quick_code = oat_method.GetQuickCode();
3424 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003425 // Check if we have JIT compiled code for it.
3426 if (quick_code == nullptr && Runtime::Current()->GetJit() != nullptr) {
3427 quick_code = Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteSavedEntryPoint(method);
3428 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003429 // Check whether the method is native, in which case it's generic JNI.
3430 if (quick_code == nullptr && method->IsNative()) {
3431 quick_code = GetQuickGenericJniStub();
3432 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003433 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003434 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003435 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003436 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003437 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003438 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003439}
3440
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003441// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3442// method. Should only be called on non-invokable methods.
3443inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003444 DCHECK(method != nullptr);
3445 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003446 method->SetEntryPointFromQuickCompiledCodePtrSize(
3447 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3448 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003449}
3450
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003451static void LinkCode(ClassLinker* class_linker,
3452 ArtMethod* method,
3453 const OatFile::OatClass* oat_class,
3454 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003455 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003456 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003457 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003458 // The following code only applies to a non-compiler runtime.
3459 return;
3460 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003461 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003462 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003463 if (oat_class != nullptr) {
3464 // Every kind of method should at least get an invoke stub from the oat_method.
3465 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003466 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003467 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003468 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003469
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003470 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003471 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003472 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003473
Alex Light9139e002015-10-09 15:59:48 -07003474 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003475 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003476 return;
3477 }
Ian Rogers19846512012-02-24 11:42:47 -08003478
3479 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003480 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003481 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3482 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003483 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003484 } else if (quick_code == nullptr && method->IsNative()) {
3485 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003486 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003487 // Set entry point from compiled code if there's no code or in interpreter only mode.
3488 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003489 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003490
Ian Rogers62d6c772013-02-27 08:32:07 -08003491 if (method->IsNative()) {
3492 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003493 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003494
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003495 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003496 // We have a native method here without code. Then it should have either the generic JNI
3497 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3498 // TODO: this doesn't handle all the cases where trampolines may be installed.
3499 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003500 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3501 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003502 }
Nicolas Geoffray5a0622a2019-04-12 16:35:17 +01003503
3504 // For the jitzygote configuration we want JNI stubs to be compiled, just like boot classpath
3505 // AOT where we compile all native entries.
3506 if (!Runtime::Current()->IsUsingDefaultBootImageLocation() &&
3507 method->GetDeclaringClass()->GetClassLoader() == nullptr &&
David Srbeckyd94c87d2019-04-16 18:40:03 +01003508 method->GetDeclaringClass()->IsResolved() &&
Nicolas Geoffray5a0622a2019-04-12 16:35:17 +01003509 Runtime::Current()->GetJit() != nullptr) {
3510 Runtime::Current()->GetJit()->CompileMethod(
3511 method, Thread::Current(), /* baseline= */ false, /* osr= */ false);
3512 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003513 }
3514}
3515
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003516void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003517 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003518 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003519 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003520 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003521 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003522 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003523 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003524 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003525
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003526 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003527 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003528 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003529 klass->SetAccessFlags(access_flags);
3530 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003531 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003532 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003533
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003534 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003535 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003536}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003537
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003538LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3539 LinearAlloc* allocator,
3540 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003541 if (length == 0) {
3542 return nullptr;
3543 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003544 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3545 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3546 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003547 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003548 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003549 CHECK(ret != nullptr);
3550 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3551 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003552}
3553
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003554LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3555 LinearAlloc* allocator,
3556 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003557 if (length == 0) {
3558 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003559 }
Vladimir Marko14632852015-08-17 12:07:23 +01003560 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3561 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003562 const size_t storage_size =
3563 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003564 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003565 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003566 CHECK(ret != nullptr);
3567 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003568 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003569 }
3570 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003571}
3572
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003573LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003574 if (class_loader == nullptr) {
3575 return Runtime::Current()->GetLinearAlloc();
3576 }
3577 LinearAlloc* allocator = class_loader->GetAllocator();
3578 DCHECK(allocator != nullptr);
3579 return allocator;
3580}
3581
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003582LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003583 if (class_loader == nullptr) {
3584 return Runtime::Current()->GetLinearAlloc();
3585 }
3586 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3587 LinearAlloc* allocator = class_loader->GetAllocator();
3588 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003589 RegisterClassLoader(class_loader);
3590 allocator = class_loader->GetAllocator();
3591 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003592 }
3593 return allocator;
3594}
3595
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003596void ClassLinker::LoadClass(Thread* self,
3597 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003598 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003599 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003600 ClassAccessor accessor(dex_file,
3601 dex_class_def,
3602 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003603 if (!accessor.HasClassData()) {
3604 return;
3605 }
3606 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003607 {
3608 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3609 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003610 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003611 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003612 // We allow duplicate definitions of the same field in a class_data_item
3613 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003614 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003615 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3616 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003617 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003618 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3619 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003620 accessor.NumInstanceFields());
3621 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003622 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003623 uint32_t last_static_field_idx = 0u;
3624 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003625
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003626 // Methods
3627 bool has_oat_class = false;
3628 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3629 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3630 : OatFile::OatClass::Invalid();
3631 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3632 klass->SetMethodsPtr(
3633 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3634 accessor.NumDirectMethods(),
3635 accessor.NumVirtualMethods());
3636 size_t class_def_method_index = 0;
3637 uint32_t last_dex_method_index = dex::kDexNoIndex;
3638 size_t last_class_def_method_index = 0;
3639
3640 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3641 // methods needs to decode all of the fields.
3642 accessor.VisitFieldsAndMethods([&](
3643 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3644 uint32_t field_idx = field.GetIndex();
3645 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3646 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3647 LoadField(field, klass, &sfields->At(num_sfields));
3648 ++num_sfields;
3649 last_static_field_idx = field_idx;
3650 }
3651 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3652 uint32_t field_idx = field.GetIndex();
3653 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3654 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3655 LoadField(field, klass, &ifields->At(num_ifields));
3656 ++num_ifields;
3657 last_instance_field_idx = field_idx;
3658 }
3659 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3660 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3661 image_pointer_size_);
3662 LoadMethod(dex_file, method, klass, art_method);
3663 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3664 uint32_t it_method_index = method.GetIndex();
3665 if (last_dex_method_index == it_method_index) {
3666 // duplicate case
3667 art_method->SetMethodIndex(last_class_def_method_index);
3668 } else {
3669 art_method->SetMethodIndex(class_def_method_index);
3670 last_dex_method_index = it_method_index;
3671 last_class_def_method_index = class_def_method_index;
3672 }
3673 ++class_def_method_index;
3674 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3675 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3676 class_def_method_index - accessor.NumDirectMethods(),
3677 image_pointer_size_);
3678 LoadMethod(dex_file, method, klass, art_method);
3679 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3680 ++class_def_method_index;
3681 });
3682
3683 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003684 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003685 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3686 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3687 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003688 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3689 if (sfields != nullptr) {
3690 sfields->SetSize(num_sfields);
3691 }
3692 if (ifields != nullptr) {
3693 ifields->SetSize(num_ifields);
3694 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003695 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003696 // Set the field arrays.
3697 klass->SetSFieldsPtr(sfields);
3698 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003699 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003700 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003701 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003702 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003703 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003704 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003705}
3706
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003707void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003708 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003709 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003710 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003711 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003712 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003713
David Brazdil85865692018-10-30 17:26:20 +00003714 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3715 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003716}
3717
Mathieu Chartier268764d2016-09-13 12:09:38 -07003718void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003719 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003720 Handle<mirror::Class> klass,
3721 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003722 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003723 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003724 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003725
Mathieu Chartier268764d2016-09-13 12:09:38 -07003726 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003727 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003728 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003729 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003730
David Brazdil85865692018-10-30 17:26:20 +00003731 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3732 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003733
Ian Rogersdfb325e2013-10-30 01:00:44 -07003734 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003735 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003736 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3737 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003738 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003739 klass->SetFinalizable();
3740 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003741 std::string temp;
3742 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003743 // The Enum class declares a "final" finalize() method to prevent subclasses from
3744 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3745 // subclasses, so we exclude it here.
3746 // We also want to avoid setting the flag on Object, where we know that finalize() is
3747 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003748 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3749 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003750 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003751 }
3752 }
3753 }
3754 } else if (method_name[0] == '<') {
3755 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003756 bool is_init = (strcmp("<init>", method_name) == 0);
3757 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003758 if (UNLIKELY(!is_init && !is_clinit)) {
3759 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3760 } else {
3761 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3762 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003763 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003764 access_flags |= kAccConstructor;
3765 }
3766 }
3767 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003768 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3769 // Check if the native method is annotated with @FastNative or @CriticalNative.
3770 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3771 dex_file, dst->GetClassDef(), dex_method_idx);
3772 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003773 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003774 // Must be done after SetAccessFlags since IsAbstract depends on it.
3775 if (klass->IsInterface() && dst->IsAbstract()) {
3776 dst->CalculateAndSetImtIndex();
3777 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003778}
3779
Ian Rogers7b078e82014-09-10 14:44:24 -07003780void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003781 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003782 self,
3783 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003784 Runtime::Current()->GetLinearAlloc());
3785 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003786 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003787}
3788
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003789void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003790 ObjPtr<mirror::DexCache> dex_cache) {
3791 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003792 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003793 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003794 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003795}
3796
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003797void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003798 ObjPtr<mirror::DexCache> dex_cache,
3799 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003800 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003801 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003802 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003803 // For app images, the dex cache location may be a suffix of the dex file location since the
3804 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003805 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3806 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003807 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3808 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003809 // The following paths checks don't work on preopt when using boot dex files, where the dex
3810 // cache location is the one on device, and the dex_file's location is the one on host.
3811 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3812 CHECK_GE(dex_file_location.length(), dex_cache_length)
3813 << dex_cache_location << " " << dex_file.GetLocation();
3814 const std::string dex_file_suffix = dex_file_location.substr(
3815 dex_file_location.length() - dex_cache_length,
3816 dex_cache_length);
3817 // Example dex_cache location is SettingsProvider.apk and
3818 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3819 CHECK_EQ(dex_cache_location, dex_file_suffix);
3820 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003821 const OatFile* oat_file =
3822 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003823 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3824 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3825 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3826 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003827 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003828 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3829 DexCacheData data = *it;
3830 if (self->IsJWeakCleared(data.weak_root)) {
3831 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003832 it = dex_caches_.erase(it);
3833 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003834 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003835 it->dex_file->GetOatDexFile() != nullptr &&
3836 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003837 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003838 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003839 ++it;
3840 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003841 }
Vladimir Markob066d432018-01-03 13:14:37 +00003842 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003843 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003844 }
David Brazdila5c3a802019-03-08 14:59:41 +00003845 // Let hiddenapi assign a domain to the newly registered dex file.
3846 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3847
Vladimir Markocd556b02017-02-03 11:47:34 +00003848 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003849 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003850 DexCacheData data;
3851 data.weak_root = dex_cache_jweak;
3852 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003853 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003854 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003855 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003856 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3857 // path dex caches without an image.
3858 data.class_table->InsertStrongRoot(dex_cache);
3859 if (class_loader != nullptr) {
3860 // Since we added a strong root to the class table, do the write barrier as required for
3861 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003862 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003863 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003864 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003865}
3866
Vladimir Markocd556b02017-02-03 11:47:34 +00003867ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3868 return data.IsValid()
3869 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3870 : nullptr;
3871}
3872
3873ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3874 Thread* self,
3875 ObjPtr<mirror::DexCache> dex_cache,
3876 const DexCacheData& data,
3877 ObjPtr<mirror::ClassLoader> class_loader) {
3878 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3879 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3880 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3881 "Attempt to register dex file %s with multiple class loaders",
3882 data.dex_file->GetLocation().c_str());
3883 return nullptr;
3884 }
3885 return dex_cache;
3886}
3887
Alex Light07f06212017-06-01 14:01:43 -07003888void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3889 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003890 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003891 Thread* self = Thread::Current();
3892 StackHandleScope<2> hs(self);
3893 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3894 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3895 const DexFile* dex_file = dex_cache->GetDexFile();
3896 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3897 if (kIsDebugBuild) {
3898 DexCacheData old_data;
3899 {
3900 ReaderMutexLock mu(self, *Locks::dex_lock_);
3901 old_data = FindDexCacheDataLocked(*dex_file);
3902 }
3903 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3904 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3905 << "been registered on dex file " << dex_file->GetLocation();
3906 }
3907 ClassTable* table;
3908 {
3909 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3910 table = InsertClassTableForClassLoader(h_class_loader.Get());
3911 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003912 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3913 // a thread holding the dex lock and blocking on a condition variable regarding
3914 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003915 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003916 WriterMutexLock mu(self, *Locks::dex_lock_);
3917 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3918 table->InsertStrongRoot(h_dex_cache.Get());
3919 if (h_class_loader.Get() != nullptr) {
3920 // Since we added a strong root to the class table, do the write barrier as required for
3921 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003922 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003923 }
3924}
3925
Vladimir Markocd556b02017-02-03 11:47:34 +00003926ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3927 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003928 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003929 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003930 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003931 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003932 old_data = FindDexCacheDataLocked(dex_file);
3933 }
3934 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3935 if (old_dex_cache != nullptr) {
3936 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003937 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003938 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003939 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3940 DCHECK(linear_alloc != nullptr);
3941 ClassTable* table;
3942 {
3943 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3944 table = InsertClassTableForClassLoader(class_loader);
3945 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003946 // Don't alloc while holding the lock, since allocation may need to
3947 // suspend all threads and another thread may need the dex_lock_ to
3948 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003949 StackHandleScope<3> hs(self);
3950 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003951 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003952 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3953 self,
3954 dex_file)));
3955 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003956 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003957 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3958 // a thread holding the dex lock and blocking on a condition variable regarding
3959 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003960 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003961 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003962 old_data = FindDexCacheDataLocked(dex_file);
3963 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003964 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003965 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3966 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3967 // that the arrays are null.
3968 mirror::DexCache::InitializeDexCache(self,
3969 h_dex_cache.Get(),
3970 h_location.Get(),
3971 &dex_file,
3972 linear_alloc,
3973 image_pointer_size_);
3974 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003975 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003976 }
3977 if (old_dex_cache != nullptr) {
3978 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3979 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003980 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003981 self->ClearException();
3982 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3983 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3984 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003985 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003986 self->AssertPendingOOMException();
3987 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003988 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003989 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003990 if (h_class_loader.Get() != nullptr) {
3991 // Since we added a strong root to the class table, do the write barrier as required for
3992 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003993 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003994 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003995 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003996}
3997
Vladimir Markocd556b02017-02-03 11:47:34 +00003998bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003999 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004000 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004001}
4002
Vladimir Markocd556b02017-02-03 11:47:34 +00004003ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4004 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004005 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
4006 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004007 if (dex_cache != nullptr) {
4008 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004009 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004010 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004011 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004012 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004013 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004014 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004015 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004016 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
4017 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004018 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004019}
4020
Vladimir Markocd556b02017-02-03 11:47:34 +00004021ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4022 const DexFile* dex_file = dex_cache->GetDexFile();
4023 DCHECK(dex_file != nullptr);
4024 ReaderMutexLock mu(self, *Locks::dex_lock_);
4025 // Search assuming unique-ness of dex file.
4026 for (const DexCacheData& data : dex_caches_) {
4027 // Avoid decoding (and read barriers) other unrelated dex caches.
4028 if (data.dex_file == dex_file) {
4029 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
4030 if (registered_dex_cache != nullptr) {
4031 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4032 return data.class_table;
4033 }
4034 }
4035 }
4036 return nullptr;
4037}
4038
4039ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
4040 // Search assuming unique-ness of dex file.
4041 for (const DexCacheData& data : dex_caches_) {
4042 // Avoid decoding (and read barriers) other unrelated dex caches.
4043 if (data.dex_file == &dex_file) {
4044 return data;
4045 }
4046 }
4047 return DexCacheData();
4048}
4049
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004050ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004051 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004052 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01004053 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004054 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004055 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004056 }
Ian Rogers1f539342012-10-03 21:09:42 -07004057 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004058 StackHandleScope<1> hs(self);
4059 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004060 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004061 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
4062 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004063 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07004064 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004065 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004066 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004067 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4068 h_class.Get(),
4069 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004070 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004071 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004072}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004073
Vladimir Marko02610552018-06-04 14:38:00 +01004074inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4075 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4076}
4077
Brian Carlstrombe977852011-07-19 14:54:54 -07004078// Create an array class (i.e. the class object for the array, not the
4079// array itself). "descriptor" looks like "[C" or "[[[[B" or
4080// "[Ljava/lang/String;".
4081//
4082// If "descriptor" refers to an array of primitives, look up the
4083// primitive type's internally-generated class object.
4084//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004085// "class_loader" is the class loader of the class that's referring to
4086// us. It's used to ensure that we're looking for the element type in
4087// the right context. It does NOT become the class loader for the
4088// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004089//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004090// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004091ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4092 const char* descriptor,
4093 size_t hash,
4094 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004095 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004096 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004097 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004098
4099 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4100 // code to be executed. We put it up here so we can avoid all the allocations associated with
4101 // creating the class. This can happen with (eg) jit threads.
4102 if (!self->CanLoadClasses()) {
4103 // Make sure we don't try to load anything, potentially causing an infinite loop.
4104 ObjPtr<mirror::Throwable> pre_allocated =
4105 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4106 self->SetException(pre_allocated);
4107 return nullptr;
4108 }
4109
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004110 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4111 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004112 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004113 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004114 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004115 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4116 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004117 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004118 DCHECK(self->IsExceptionPending());
4119 return nullptr;
4120 } else {
4121 self->ClearException();
4122 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004123 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004124 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4125 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4126 return nullptr;
4127 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004128 // See if the component type is already loaded. Array classes are
4129 // always associated with the class loader of their underlying
4130 // element type -- an array of Strings goes with the loader for
4131 // java/lang/String -- so we need to look for it there. (The
4132 // caller should have checked for the existence of the class
4133 // before calling here, but they did so with *their* class loader,
4134 // not the component type's loader.)
4135 //
4136 // If we find it, the caller adds "loader" to the class' initiating
4137 // loader list, which should prevent us from going through this again.
4138 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004139 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004140 // are the same, because our caller (FindClass) just did the
4141 // lookup. (Even if we get this wrong we still have correct behavior,
4142 // because we effectively do this lookup again when we add the new
4143 // class to the hash table --- necessary because of possible races with
4144 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004145 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004146 ObjPtr<mirror::Class> new_class =
4147 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004148 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004149 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004150 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004151 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004152
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004153 // Fill out the fields in the Class.
4154 //
4155 // It is possible to execute some methods against arrays, because
4156 // all arrays are subclasses of java_lang_Object_, so we need to set
4157 // up a vtable. We can just point at the one in java_lang_Object_.
4158 //
4159 // Array classes are simple enough that we don't need to do a full
4160 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004161 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004162 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004163 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004164 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004165 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004166 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004167 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4168 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4169 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004170 } else if (strcmp(descriptor, "[Z") == 0) {
4171 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4172 } else if (strcmp(descriptor, "[B") == 0) {
4173 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4174 } else if (strcmp(descriptor, "[C") == 0) {
4175 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4176 } else if (strcmp(descriptor, "[S") == 0) {
4177 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004178 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004179 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004180 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004181 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004182 } else if (strcmp(descriptor, "[F") == 0) {
4183 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4184 } else if (strcmp(descriptor, "[D") == 0) {
4185 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004186 }
4187 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004188 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004189 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004190 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004191 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004192 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004193 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004194 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004195 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004196 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004197 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004198 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004199 new_class->SetSuperClass(java_lang_Object);
4200 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004201 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004202 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004203 if (component_type->IsPrimitive()) {
4204 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4205 } else {
4206 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4207 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004208 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004209 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4210 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4211 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004212 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004213 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004214 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004215 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004216
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004217 // All arrays have java/lang/Cloneable and java/io/Serializable as
4218 // interfaces. We need to set that up here, so that stuff like
4219 // "instanceof" works right.
4220 //
4221 // Note: The GC could run during the call to FindSystemClass,
4222 // so we need to make sure the class object is GC-valid while we're in
4223 // there. Do this by clearing the interface list so the GC will just
4224 // think that the entries are null.
4225
4226
4227 // Use the single, global copies of "interfaces" and "iftable"
4228 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004229 {
Vladimir Marko02610552018-06-04 14:38:00 +01004230 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004231 CHECK(array_iftable != nullptr);
4232 new_class->SetIfTable(array_iftable);
4233 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004234
Elliott Hughes00626c22013-06-14 15:04:14 -07004235 // Inherit access flags from the component type.
4236 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4237 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4238 access_flags &= kAccJavaFlagsMask;
4239 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004240 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004241 access_flags |= kAccAbstract | kAccFinal;
4242 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004243 // Arrays are access-checks-clean and preverified.
4244 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004245
4246 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004247
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004248 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004249 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004250 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4251 // duplicate events in case of races. Array classes don't really follow dedicated
4252 // load and prepare, anyways.
4253 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4254 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4255
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004256 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004257 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004258 }
4259 // Another thread must have loaded the class after we
4260 // started but before we finished. Abandon what we've
4261 // done.
4262 //
4263 // (Yes, this happens.)
4264
Vladimir Markobcf17522018-06-01 13:14:32 +01004265 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004266}
4267
Vladimir Marko9186b182018-11-06 14:55:54 +00004268ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4269 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004270 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004271 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4272 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4273 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4274 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4275 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4276 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4277 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4278 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4279 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004280 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004281 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004282 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004283 return GetClassRoot(class_root, this);
4284}
4285
4286ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4287 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4288 if (UNLIKELY(result == nullptr)) {
4289 std::string printable_type(PrintableChar(type));
4290 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4291 }
4292 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004293}
4294
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004295ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4296 ObjPtr<mirror::Class> klass,
4297 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004298 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004299 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004300 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004301 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004302 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004303 source += " from ";
4304 source += dex_cache->GetLocation()->ToModifiedUtf8();
4305 }
4306 LOG(INFO) << "Loaded class " << descriptor << source;
4307 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004308 {
4309 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004310 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004311 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004312 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004313 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004314 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004315 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004316 VerifyObject(klass);
4317 class_table->InsertWithHash(klass, hash);
4318 if (class_loader != nullptr) {
4319 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004320 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004321 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004322 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004323 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004324 }
4325 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004326 if (kIsDebugBuild) {
4327 // Test that copied methods correctly can find their holder.
4328 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4329 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4330 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004331 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004332 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004333}
4334
Vladimir Marko1998cd02017-01-13 13:02:58 +00004335void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004336 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4337 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4338 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4339 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004340 }
4341}
4342
Alex Lighte64300b2015-12-15 15:02:47 -08004343// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004344void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004345 LengthPrefixedArray<ArtMethod>* new_methods) {
4346 klass->SetMethodsPtrUnchecked(new_methods,
4347 klass->NumDirectMethods(),
4348 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004349 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004350 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004351}
4352
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004353ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4354 const char* descriptor,
4355 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004356 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4357}
4358
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004359ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4360 const char* descriptor,
4361 size_t hash,
4362 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004363 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4364 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4365 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004366 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004367 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004368 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004369 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004370 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004371 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004372}
4373
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004374class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4375 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004376 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004377
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004378 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004379 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004380 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004381 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004382 if (class_table != nullptr) {
4383 class_table->FreezeSnapshot();
4384 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004385 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004386};
4387
4388void ClassLinker::MoveClassTableToPreZygote() {
4389 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004390 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004391 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004392 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004393}
4394
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004395// Look up classes by hash and descriptor and put all matching ones in the result array.
4396class LookupClassesVisitor : public ClassLoaderVisitor {
4397 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004398 LookupClassesVisitor(const char* descriptor,
4399 size_t hash,
4400 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004401 : descriptor_(descriptor),
4402 hash_(hash),
4403 result_(result) {}
4404
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004405 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004406 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004407 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004408 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004409 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4410 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004411 result_->push_back(klass);
4412 }
4413 }
4414
4415 private:
4416 const char* const descriptor_;
4417 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004418 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004419};
4420
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004421void ClassLinker::LookupClasses(const char* descriptor,
4422 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004423 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004424 Thread* const self = Thread::Current();
4425 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004426 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004427 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004428 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004429 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004430 result.push_back(klass);
4431 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004432 LookupClassesVisitor visitor(descriptor, hash, &result);
4433 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004434}
4435
Alex Lightf1f10492015-10-07 16:08:36 -07004436bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4437 Handle<mirror::Class> klass,
4438 Handle<mirror::Class> supertype) {
4439 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004440 DCHECK(klass != nullptr);
4441 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004442
Alex Lightf1f10492015-10-07 16:08:36 -07004443 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4444 VerifyClass(self, supertype);
4445 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004446
4447 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4448 // The supertype is either verified, or we soft failed at AOT time.
4449 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004450 return true;
4451 }
4452 // If we got this far then we have a hard failure.
4453 std::string error_msg =
4454 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004455 klass->PrettyDescriptor().c_str(),
4456 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004457 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004458 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004459 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004460 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004461 // Set during VerifyClass call (if at all).
4462 self->ClearException();
4463 }
4464 // Change into a verify error.
4465 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004466 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004467 self->GetException()->SetCause(cause.Get());
4468 }
4469 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4470 if (Runtime::Current()->IsAotCompiler()) {
4471 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4472 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004473 // Need to grab the lock to change status.
4474 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004475 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004476 return false;
4477}
4478
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004479verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004480 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004481 {
4482 // TODO: assert that the monitor on the Class is held
4483 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004484
Andreas Gampe884f3b82016-03-30 19:52:58 -07004485 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004486 ClassStatus old_status = klass->GetStatus();
4487 while (old_status == ClassStatus::kVerifying ||
4488 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004489 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004490 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4491 // case we may see the same status again. b/62912904. This is why the check is
4492 // greater or equal.
4493 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004494 << "Class '" << klass->PrettyClass()
4495 << "' performed an illegal verification state transition from " << old_status
4496 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004497 old_status = klass->GetStatus();
4498 }
jeffhao98eacac2011-09-14 16:11:53 -07004499
Andreas Gampe884f3b82016-03-30 19:52:58 -07004500 // The class might already be erroneous, for example at compile time if we attempted to verify
4501 // this class as a parent to another.
4502 if (klass->IsErroneous()) {
4503 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004504 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004505 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004506
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004507 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004508 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004509 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004510 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004511 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004512
4513 // For AOT, don't attempt to re-verify if we have already found we should
4514 // verify at runtime.
4515 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004516 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004517 }
jeffhao98eacac2011-09-14 16:11:53 -07004518
Vladimir Marko2c64a832018-01-04 11:31:56 +00004519 if (klass->GetStatus() == ClassStatus::kResolved) {
4520 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004521 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004522 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004523 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004524 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004525 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004526 }
4527
4528 // Skip verification if disabled.
4529 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004530 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004531 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004532 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004533 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004534 }
4535
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004536 VLOG(class_linker) << "Beginning verification for class: "
4537 << klass->PrettyDescriptor()
4538 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4539
Ian Rogers9ffb0392012-09-10 11:56:50 -07004540 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004541 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004542 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4543 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004544 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004545 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004546 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004547 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004548
Alex Lightf1f10492015-10-07 16:08:36 -07004549 // Verify all default super-interfaces.
4550 //
4551 // (1) Don't bother if the superclass has already had a soft verification failure.
4552 //
4553 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4554 // recursive initialization by themselves. This is because when an interface is initialized
4555 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4556 // but choose not to for an optimization. If the interfaces is being verified due to a class
4557 // initialization (which would need all the default interfaces to be verified) the class code
4558 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004559 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004560 && !klass->IsInterface()) { // See (2)
4561 int32_t iftable_count = klass->GetIfTableCount();
4562 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4563 // Loop through all interfaces this class has defined. It doesn't matter the order.
4564 for (int32_t i = 0; i < iftable_count; i++) {
4565 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004566 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004567 // We only care if we have default interfaces and can skip if we are already verified...
4568 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4569 continue;
4570 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4571 // We had a hard failure while verifying this interface. Just return immediately.
4572 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004573 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004574 } else if (UNLIKELY(!iface->IsVerified())) {
4575 // We softly failed to verify the iface. Stop checking and clean up.
4576 // Put the iface into the supertype handle so we know what caused us to fail.
4577 supertype.Assign(iface.Get());
4578 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004579 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004580 }
4581 }
4582
Alex Lightf1f10492015-10-07 16:08:36 -07004583 // At this point if verification failed, then supertype is the "first" supertype that failed
4584 // verification (without a specific order). If verification succeeded, then supertype is either
4585 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004586 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004587 supertype.Get() == klass->GetSuperClass() ||
4588 !supertype->IsVerified());
4589
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004590 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004591 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004592 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004593 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004594
4595 VLOG(class_linker) << "Class preverified status for class "
4596 << klass->PrettyDescriptor()
4597 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4598 << ": "
4599 << preverified;
4600
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004601 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4602 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004603 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4604 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004605
Ian Rogers62d6c772013-02-27 08:32:07 -08004606 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004607 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004608 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004609 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004610 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004611
4612 // Verification is done, grab the lock again.
4613 ObjectLock<mirror::Class> lock(self, klass);
4614
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004615 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4616 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004617 VLOG(class_linker) << "Soft verification failure in class "
4618 << klass->PrettyDescriptor()
4619 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4620 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004621 }
Ian Rogers1f539342012-10-03 21:09:42 -07004622 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004623 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004624 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004625 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004626 // Even though there were no verifier failures we need to respect whether the super-class and
4627 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004628 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004629 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004630 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004631 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4632 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004633 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004634 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004635 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004636 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004637 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004638 // Soft failures at compile time should be retried at runtime. Soft
4639 // failures at runtime will be handled by slow paths in the generated
4640 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004641 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004642 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004643 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004644 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004645 // As this is a fake verified status, make sure the methods are _not_ marked
4646 // kAccSkipAccessChecks later.
4647 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004648 }
4649 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004650 } else {
David Sehr709b0702016-10-13 09:12:37 -07004651 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004652 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4653 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004654 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004655 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004656 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004657 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004658 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004659 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004660 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004661 // method.
4662 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004663 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004664 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004665
4666 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4667 // Never skip access checks if the verification soft fail is forced.
4668 // Mark the class as having a verification attempt to avoid re-running the verifier.
4669 klass->SetVerificationAttempted();
4670 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004671 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004672 }
Andreas Gampe48498592014-09-10 19:48:05 -07004673 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004674 // Done verifying. Notify the compiler about the verification status, in case the class
4675 // was verified implicitly (eg super class of a compiled class).
4676 if (Runtime::Current()->IsAotCompiler()) {
4677 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4678 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4679 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004680 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004681}
4682
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004683verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4684 Handle<mirror::Class> klass,
4685 verifier::HardFailLogMode log_level,
4686 std::string* error_msg) {
4687 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004688 return verifier::ClassVerifier::VerifyClass(self,
4689 klass.Get(),
4690 runtime->GetCompilerCallbacks(),
4691 runtime->IsAotCompiler(),
4692 log_level,
4693 Runtime::Current()->GetTargetSdkVersion(),
4694 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004695}
4696
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004697bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004698 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004699 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004700 // If we're compiling, we can only verify the class using the oat file if
4701 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004702 // the compilation unit (app - dependencies). We will let the compiler callback
4703 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004704 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004705 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004706 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004707 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004708 return false;
4709 }
4710 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004711 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004712 return false;
4713 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004714 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004715
Andreas Gampeb40d3612018-06-26 15:49:42 -07004716 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004717 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004718 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004719 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4720 // For boot classpath classes in the case we're not using a default boot image:
4721 // we don't have the infrastructure yet to query verification data on individual
4722 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4723 // verified. This should be taken into account when measuring boot time and app
4724 // startup compare to the (current) production system where both:
4725 // 1) updatable boot classpath classes, and
4726 // 2) classes in /system referencing updatable classes
4727 // will be verified at runtime.
4728 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4729 oat_file_class_status = ClassStatus::kVerified;
4730 return true;
4731 }
4732 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004733 return false;
4734 }
4735
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004736 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004737 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004738 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004739 return true;
4740 }
4741 // If we only verified a subset of the classes at compile time, we can end up with classes that
4742 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004743 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004744 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004745 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004746 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004747 // Compile time verification failed with a soft error. Compile time verification can fail
4748 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004749 // class ... {
4750 // Foo x;
4751 // .... () {
4752 // if (...) {
4753 // v1 gets assigned a type of resolved class Foo
4754 // } else {
4755 // v1 gets assigned a type of unresolved class Bar
4756 // }
4757 // iput x = v1
4758 // } }
4759 // when we merge v1 following the if-the-else it results in Conflict
4760 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4761 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4762 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4763 // at compile time).
4764 return false;
4765 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004766 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004767 // Compile time verification failed with a hard error. This is caused by invalid instructions
4768 // in the class. These errors are unrecoverable.
4769 return false;
4770 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004771 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004772 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4773 // not loading the class.
4774 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4775 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004776 return false;
4777 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004778 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004779 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004780 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004781 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004782 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004783}
4784
Alex Light5a559862016-01-29 12:24:48 -08004785void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004786 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004787 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004788 }
4789}
4790
Alex Light5a559862016-01-29 12:24:48 -08004791void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004792 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004793 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004794 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004795 return; // native or abstract method
4796 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004797 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004798 return; // nothing to process
4799 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004800 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004801 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004802 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4803 CatchHandlerIterator iterator(handlers_ptr);
4804 for (; iterator.HasNext(); iterator.Next()) {
4805 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4806 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004807 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004808 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004809 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004810 DCHECK(Thread::Current()->IsExceptionPending());
4811 Thread::Current()->ClearException();
4812 }
4813 }
4814 }
4815 handlers_ptr = iterator.EndDataPointer();
4816 }
4817}
4818
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004819ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4820 jstring name,
4821 jobjectArray interfaces,
4822 jobject loader,
4823 jobjectArray methods,
4824 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004825 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004826
4827 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4828 // code to be executed. We put it up here so we can avoid all the allocations associated with
4829 // creating the class. This can happen with (eg) jit-threads.
4830 if (!self->CanLoadClasses()) {
4831 // Make sure we don't try to load anything, potentially causing an infinite loop.
4832 ObjPtr<mirror::Throwable> pre_allocated =
4833 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4834 self->SetException(pre_allocated);
4835 return nullptr;
4836 }
4837
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004838 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004839 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004840 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004841 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004842 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004843 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004844 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004845 DCHECK(temp_klass->GetClass() != nullptr);
4846 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004847 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4848 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004849 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4850 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4851 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4852 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004853 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004854 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004855 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004856 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004857 std::string storage;
4858 const char* descriptor = temp_klass->GetDescriptor(&storage);
4859 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004860
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004861 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004862 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004863
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004864 // Insert the class before loading the fields as the field roots
4865 // (ArtField::declaring_class_) are only visited from the class
4866 // table. There can't be any suspend points between inserting the
4867 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004868 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004869 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004870
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004871 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004872 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004873 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004874 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004875
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004876 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4877 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004878 ArtField& interfaces_sfield = sfields->At(0);
4879 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004880 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004881 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004882
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004883 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004884 ArtField& throws_sfield = sfields->At(1);
4885 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004886 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004887 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004888
Ian Rogers466bb252011-10-14 03:29:56 -07004889 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004890 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004891
Alex Lighte64300b2015-12-15 15:02:47 -08004892 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004893 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004894 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004895 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004896 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004897
4898 // Create the methods array.
4899 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4900 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004901 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4902 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004903 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004904 self->AssertPendingOOMException();
4905 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004906 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004907 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004908
4909 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004910 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004911
4912 // Create virtual method using specified prototypes.
4913 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004914 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004915 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004916 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004917 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004918 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4919 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004920 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004921
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004922 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004923 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004924 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004925 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004926 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004927
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004928 // At this point the class is loaded. Publish a ClassLoad event.
4929 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4930 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4931
4932 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004933 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004934 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004935 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004936 // Link the fields and virtual methods, creating vtable and iftables.
4937 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004938 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004939 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004940 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004941 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004942 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004943 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004944 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004945 CHECK(temp_klass->IsRetired());
4946 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004947
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004948 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004949 interfaces_sfield.SetObject<false>(
4950 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004951 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004952 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4953 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004954 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004955 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004956
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004957 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4958
Vladimir Marko305c38b2018-02-14 11:50:07 +00004959 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4960 // See also ClassLinker::EnsureInitialized().
4961 if (kBitstringSubtypeCheckEnabled) {
4962 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4963 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4964 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4965 }
4966
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004967 {
4968 // Lock on klass is released. Lock new class object.
4969 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004970 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004971 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004972 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004973
4974 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004975 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004976 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004977 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4978
Ian Rogersc2b44472011-12-14 21:17:17 -08004979 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004980 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4981 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004982 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004983 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004984
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004985 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004986 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004987 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004988 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004989 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004990
4991 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004992 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004993 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004994
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004995 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004996 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004997 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004998 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004999 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005000 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005001}
5002
Mathieu Chartiere401d142015-04-22 13:56:20 -07005003void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5004 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005005 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5006 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005007
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005008 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5009 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005010 ArtMethod* proxy_constructor =
5011 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005012 DCHECK(proxy_constructor != nullptr)
5013 << "Could not find <init> method in java.lang.reflect.Proxy";
5014
Jeff Haodb8a6642014-08-14 17:18:52 -07005015 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5016 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005017 DCHECK(out != nullptr);
5018 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005019 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005020 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005021 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005022 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5023 kAccPublic |
5024 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005026
5027 // Set the original constructor method.
5028 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005029}
5030
Mathieu Chartiere401d142015-04-22 13:56:20 -07005031void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005032 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005033 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5034 CHECK_STREQ(np->GetName(), "<init>");
5035 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005036 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005037}
5038
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005039void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005040 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005041 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005042 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005043 DCHECK(out != nullptr);
5044 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005045
Alex Lighte9dd04f2016-03-16 16:09:45 -07005046 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005047 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005048 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5049 // preference to the invocation handler.
5050 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5051 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005052 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5053 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005054 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5055
5056 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5057 // method they copy might (if it's a default method).
5058 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005059
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005060 // Set the original interface method.
5061 out->SetDataPtrSize(prototype, image_pointer_size_);
5062
Ian Rogers466bb252011-10-14 03:29:56 -07005063 // At runtime the method looks like a reference and argument saving method, clone the code
5064 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005065 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005066}
Jesse Wilson95caa792011-10-12 18:14:17 -04005067
Mathieu Chartiere401d142015-04-22 13:56:20 -07005068void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005069 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005070 CHECK(!prototype->IsFinal());
5071 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005072 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005073
5074 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5075 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005076 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005077 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005078}
5079
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005080bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005081 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005082 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005083 return true;
5084 }
5085 if (!can_init_statics) {
5086 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005087 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005088 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005089 return false;
5090 }
5091 // Check if there are encoded static values needing initialization.
5092 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005093 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005094 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005095 if (dex_class_def->static_values_off_ != 0) {
5096 return false;
5097 }
5098 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005099 // If we are a class we need to initialize all interfaces with default methods when we are
5100 // initialized. Check all of them.
5101 if (!klass->IsInterface()) {
5102 size_t num_interfaces = klass->GetIfTableCount();
5103 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005104 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005105 if (iface->HasDefaultMethods() &&
5106 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5107 return false;
5108 }
5109 }
5110 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005111 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005112 if (klass->IsInterface() || !klass->HasSuperClass()) {
5113 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005114 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005115 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005116 if (!can_init_parents && !super_class->IsInitialized()) {
5117 return false;
5118 }
5119 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005120}
5121
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005122bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5123 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005124 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5125
5126 // Are we already initialized and therefore done?
5127 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5128 // an initialized class will never change its state.
5129 if (klass->IsInitialized()) {
5130 return true;
5131 }
5132
5133 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005134 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005135 return false;
5136 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005137
Ian Rogers7b078e82014-09-10 14:44:24 -07005138 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005139 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005140 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005141 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005142
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005143 // Re-check under the lock in case another thread initialized ahead of us.
5144 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005145 return true;
5146 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005147
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005148 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005149 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005150 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005151 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005152 return false;
5153 }
5154
Vladimir Marko72ab6842017-01-20 19:32:50 +00005155 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5156 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005157
5158 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005159 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005160 if (!klass->IsVerified()) {
5161 // We failed to verify, expect either the klass to be erroneous or verification failed at
5162 // compile time.
5163 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005164 // The class is erroneous. This may be a verifier error, or another thread attempted
5165 // verification and/or initialization and failed. We can distinguish those cases by
5166 // whether an exception is already pending.
5167 if (self->IsExceptionPending()) {
5168 // Check that it's a VerifyError.
5169 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005170 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005171 } else {
5172 // Check that another thread attempted initialization.
5173 DCHECK_NE(0, klass->GetClinitThreadId());
5174 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5175 // Need to rethrow the previous failure now.
5176 ThrowEarlierClassFailure(klass.Get(), true);
5177 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005178 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005179 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005180 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005181 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005182 self->AssertNoPendingException();
5183 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005184 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005185 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005186 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005187 } else {
5188 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005189 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005190
5191 // A separate thread could have moved us all the way to initialized. A "simple" example
5192 // involves a subclass of the current class being initialized at the same time (which
5193 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005194 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005195 if (klass->IsInitialized()) {
5196 return true;
5197 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005198 }
5199
Vladimir Marko2c64a832018-01-04 11:31:56 +00005200 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005201 // initializing higher up the stack or another thread has beat us
5202 // to initializing and we need to wait. Either way, this
5203 // invocation of InitializeClass will not be responsible for
5204 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005205 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005206 // Could have got an exception during verification.
5207 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005208 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005209 return false;
5210 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005211 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005212 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005213 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005214 return true;
5215 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005216 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005217 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005218 }
5219
Jeff Haoe2e40342017-07-19 10:45:18 -07005220 // Try to get the oat class's status for this class if the oat file is present. The compiler
5221 // tries to validate superclass descriptors, and writes the result into the oat file.
5222 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5223 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5224 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005225 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005226 const Runtime* runtime = Runtime::Current();
5227 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5228 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5229 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005230 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005231 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005232 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005233 return false;
5234 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005235 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005236
Vladimir Marko2c64a832018-01-04 11:31:56 +00005237 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005238 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005239
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005240 // From here out other threads may observe that we're initializing and so changes of state
5241 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005242 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005243 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005244
5245 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005246 }
5247
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005248 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005249 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005250 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005251 if (!super_class->IsInitialized()) {
5252 CHECK(!super_class->IsInterface());
5253 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005254 StackHandleScope<1> hs(self);
5255 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005256 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005257 if (!super_initialized) {
5258 // The super class was verified ahead of entering initializing, we should only be here if
5259 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005260 // For the case of aot compiler, the super class might also be initializing but we don't
5261 // want to process circular dependencies in pre-compile.
5262 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005263 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005264 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005265 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005266 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005267 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005268 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005269 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005270 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005271 return false;
5272 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005273 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005274 }
5275
Alex Lighteb7c1442015-08-31 13:17:42 -07005276 if (!klass->IsInterface()) {
5277 // Initialize interfaces with default methods for the JLS.
5278 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005279 // Only setup the (expensive) handle scope if we actually need to.
5280 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005281 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005282 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5283 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005284 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005285 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005286 CHECK(handle_scope_iface->IsInterface());
5287 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5288 // We have already done this for this interface. Skip it.
5289 continue;
5290 }
5291 // We cannot just call initialize class directly because we need to ensure that ALL
5292 // interfaces with default methods are initialized. Non-default interface initialization
5293 // will not affect other non-default super-interfaces.
5294 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5295 handle_scope_iface,
5296 can_init_statics,
5297 can_init_parents);
5298 if (!iface_initialized) {
5299 ObjectLock<mirror::Class> lock(self, klass);
5300 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005301 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005302 return false;
5303 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005304 }
5305 }
5306 }
5307
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005308 const size_t num_static_fields = klass->NumStaticFields();
5309 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005310 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005311 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005312 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005313 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005314 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005315
5316 // Eagerly fill in static fields so that the we don't have to do as many expensive
5317 // Class::FindStaticField in ResolveField.
5318 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005319 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005320 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005321 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005322 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005323 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005324 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5325 field,
5326 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5327 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005328 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005329 } else {
5330 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005331 }
5332 }
5333
Vladimir Markoe11dd502017-12-08 14:09:45 +00005334 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5335 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005336 this,
5337 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005338 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005339
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005340 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005341 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005342 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005343 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5344 if (!value_it.HasNext()) {
5345 break;
5346 }
5347 ArtField* art_field = ResolveField(field.GetIndex(),
5348 dex_cache,
5349 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005350 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005351 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005352 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005353 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005354 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005355 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005356 if (self->IsExceptionPending()) {
5357 break;
5358 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005359 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005360 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005361 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005362 }
5363 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005364
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005365
Mathieu Chartierda595be2016-08-10 13:57:39 -07005366 if (!self->IsExceptionPending()) {
5367 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5368 if (clinit != nullptr) {
5369 CHECK(can_init_statics);
5370 JValue result;
5371 clinit->Invoke(self, nullptr, 0, &result, "V");
5372 }
5373 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005374 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005375 uint64_t t1 = NanoTime();
5376
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005377 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005378 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005379 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005380
5381 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005382 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005383 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005384 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005385 } else if (Runtime::Current()->IsTransactionAborted()) {
5386 // The exception thrown when the transaction aborted has been caught and cleared
5387 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005388 VLOG(compiler) << "Return from class initializer of "
5389 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005390 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005391 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005392 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005393 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005394 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005395 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5396 RuntimeStats* thread_stats = self->GetStats();
5397 ++global_stats->class_init_count;
5398 ++thread_stats->class_init_count;
5399 global_stats->class_init_time_ns += (t1 - t0);
5400 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005401 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005402 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005403 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005404 std::string temp;
5405 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005406 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005407 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005408 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005409 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005410 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005411 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005412 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005413}
5414
Alex Lighteb7c1442015-08-31 13:17:42 -07005415// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5416// and perform the initialization only on those interfaces that contain default methods.
5417bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5418 Handle<mirror::Class> iface,
5419 bool can_init_statics,
5420 bool can_init_parents) {
5421 CHECK(iface->IsInterface());
5422 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005423 // Only create the (expensive) handle scope if we need it.
5424 if (UNLIKELY(num_direct_ifaces > 0)) {
5425 StackHandleScope<1> hs(self);
5426 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5427 // First we initialize all of iface's super-interfaces recursively.
5428 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005429 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005430 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005431 if (!super_iface->HasBeenRecursivelyInitialized()) {
5432 // Recursive step
5433 handle_super_iface.Assign(super_iface);
5434 if (!InitializeDefaultInterfaceRecursive(self,
5435 handle_super_iface,
5436 can_init_statics,
5437 can_init_parents)) {
5438 return false;
5439 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005440 }
5441 }
5442 }
5443
5444 bool result = true;
5445 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5446 // initialize if we don't have default methods.
5447 if (iface->HasDefaultMethods()) {
5448 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5449 }
5450
5451 // Mark that this interface has undergone recursive default interface initialization so we know we
5452 // can skip it on any later class initializations. We do this even if we are not a default
5453 // interface since we can still avoid the traversal. This is purely a performance optimization.
5454 if (result) {
5455 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005456 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5457 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5458 // initialization is a performance optimization (to avoid another idempotent visit
5459 // for other implementing classes/interfaces), and can be revisited later.
5460 ObjectTryLock<mirror::Class> lock(self, iface);
5461 if (lock.Acquired()) {
5462 iface->SetRecursivelyInitialized();
5463 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005464 }
5465 return result;
5466}
5467
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005468bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5469 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005470 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005471 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005472 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005473 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005474 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005475 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005476
5477 // When we wake up, repeat the test for init-in-progress. If
5478 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005479 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005480 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005481 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005482 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005483 return false;
5484 }
5485 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005486 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005487 continue;
5488 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005489 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005490 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005491 // Compile time initialization failed.
5492 return false;
5493 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005494 if (klass->IsErroneous()) {
5495 // The caller wants an exception, but it was thrown in a
5496 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005497 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005498 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005499 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005500 return false;
5501 }
5502 if (klass->IsInitialized()) {
5503 return true;
5504 }
David Sehr709b0702016-10-13 09:12:37 -07005505 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005506 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005507 }
Ian Rogers07140832014-09-30 15:43:59 -07005508 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005509}
5510
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005511static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5512 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005513 ArtMethod* method,
5514 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005515 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005516 DCHECK(Thread::Current()->IsExceptionPending());
5517 DCHECK(!m->IsProxyMethod());
5518 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005519 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5520 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005521 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005522 std::string return_type = dex_file->PrettyType(return_type_idx);
5523 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005524 ThrowWrappedLinkageError(klass.Get(),
5525 "While checking class %s method %s signature against %s %s: "
5526 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005527 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5528 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005529 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005530 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005531 return_type.c_str(), class_loader.c_str());
5532}
5533
5534static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5535 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005536 ArtMethod* method,
5537 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005538 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005539 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005540 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005541 DCHECK(Thread::Current()->IsExceptionPending());
5542 DCHECK(!m->IsProxyMethod());
5543 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005544 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5545 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005546 ThrowWrappedLinkageError(klass.Get(),
5547 "While checking class %s method %s signature against %s %s: "
5548 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005549 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5550 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005551 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005552 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005553 index, arg_type.c_str(), class_loader.c_str());
5554}
5555
5556static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5557 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005558 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005559 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005560 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 ThrowLinkageError(klass.Get(),
5562 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005563 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5564 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005565 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005566 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005567 error_msg.c_str());
5568}
5569
Ian Rogersb5fb2072014-12-02 17:22:02 -08005570static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005571 Handle<mirror::Class> klass,
5572 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005573 ArtMethod* method1,
5574 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005575 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005576 {
5577 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005578 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005579 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005580 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005581 return false;
5582 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005583 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005584 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005585 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005586 return false;
5587 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005588 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005589 ThrowSignatureMismatch(klass, super_klass, method1,
5590 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005591 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005592 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005593 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005594 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005595 return false;
5596 }
5597 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005598 const dex::TypeList* types1 = method1->GetParameterTypeList();
5599 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005600 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005601 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005602 ThrowSignatureMismatch(klass, super_klass, method1,
5603 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005604 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005605 return false;
5606 }
5607 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005608 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005609 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005610 ThrowSignatureMismatch(klass, super_klass, method1,
5611 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005612 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005613 return false;
5614 }
5615 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005616 }
5617 uint32_t num_types = types1->Size();
5618 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005619 ThrowSignatureMismatch(klass, super_klass, method1,
5620 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005621 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005622 return false;
5623 }
5624 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005625 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005626 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005627 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005628 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005629 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005630 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005631 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005632 return false;
5633 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005634 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005635 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005636 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005637 if (UNLIKELY(other_param_type == nullptr)) {
5638 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005639 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005640 return false;
5641 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005642 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005643 ThrowSignatureMismatch(klass, super_klass, method1,
5644 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5645 i,
David Sehr709b0702016-10-13 09:12:37 -07005646 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005647 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005648 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005649 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005650 return false;
5651 }
5652 }
5653 return true;
5654}
5655
5656
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005657bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005658 if (klass->IsInterface()) {
5659 return true;
5660 }
Ian Rogers151f2212014-05-06 11:27:27 -07005661 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005662 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005663 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005664 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005665 if (klass->HasSuperClass() &&
5666 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005667 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005668 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005669 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5670 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5671 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005672 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5673 klass,
5674 super_klass,
5675 m,
5676 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005677 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005678 return false;
5679 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005680 }
5681 }
5682 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005683 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005684 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5685 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5686 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005687 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005688 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5689 j, image_pointer_size_);
5690 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5691 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005692 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5693 klass,
5694 super_klass,
5695 m,
5696 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005697 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005698 return false;
5699 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005700 }
5701 }
5702 }
5703 }
5704 return true;
5705}
5706
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005707bool ClassLinker::EnsureInitialized(Thread* self,
5708 Handle<mirror::Class> c,
5709 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005710 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005711 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005712
Mathieu Chartier524507a2014-08-27 15:28:28 -07005713 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005714 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005715 return true;
5716 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005717 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5718 //
5719 // Ensure the bitstring is initialized before any of the class initialization
5720 // logic occurs. Once a class initializer starts running, objects can
5721 // escape into the heap and use the subtype checking code.
5722 //
5723 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5724 // can be used as a source for the IsSubClass check, and that all ancestors
5725 // of the class are Assigned (can be used as a target for IsSubClass check)
5726 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005727 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005728 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005729 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005730 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5731 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005732 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005733 if (!success) {
5734 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005735 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005736 }
5737 } else {
5738 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005739 }
5740 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005741}
5742
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005743void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5744 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005745 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005746 for (ArtField& field : new_class->GetIFields()) {
5747 if (field.GetDeclaringClass() == temp_class) {
5748 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005749 }
5750 }
5751
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005752 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005753 for (ArtField& field : new_class->GetSFields()) {
5754 if (field.GetDeclaringClass() == temp_class) {
5755 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005756 }
5757 }
5758
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005759 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005760 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005761 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005762 if (method.GetDeclaringClass() == temp_class) {
5763 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005764 }
5765 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005766
5767 // Make sure the remembered set and mod-union tables know that we updated some of the native
5768 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005769 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005770}
5771
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005772void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005773 CHECK(class_loader->GetAllocator() == nullptr);
5774 CHECK(class_loader->GetClassTable() == nullptr);
5775 Thread* const self = Thread::Current();
5776 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005777 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005778 // Create and set the class table.
5779 data.class_table = new ClassTable;
5780 class_loader->SetClassTable(data.class_table);
5781 // Create and set the linear allocator.
5782 data.allocator = Runtime::Current()->CreateLinearAlloc();
5783 class_loader->SetAllocator(data.allocator);
5784 // Add to the list so that we know to free the data later.
5785 class_loaders_.push_back(data);
5786}
5787
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005788ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005789 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005790 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005791 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005792 ClassTable* class_table = class_loader->GetClassTable();
5793 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005794 RegisterClassLoader(class_loader);
5795 class_table = class_loader->GetClassTable();
5796 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005797 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005798 return class_table;
5799}
5800
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005801ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005802 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005803}
5804
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005805static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005806 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005807 while (klass->HasSuperClass()) {
5808 klass = klass->GetSuperClass();
5809 if (klass->ShouldHaveImt()) {
5810 return klass->GetImt(pointer_size);
5811 }
5812 }
5813 return nullptr;
5814}
5815
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005816bool ClassLinker::LinkClass(Thread* self,
5817 const char* descriptor,
5818 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005819 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005820 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005821 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005822
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005823 if (!LinkSuperClass(klass)) {
5824 return false;
5825 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005826 ArtMethod* imt_data[ImTable::kSize];
5827 // If there are any new conflicts compared to super class.
5828 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005829 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005830 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005831 return false;
5832 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005833 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005834 return false;
5835 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005836 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005837 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005838 return false;
5839 }
5840 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005841 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005842
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005843 ImTable* imt = nullptr;
5844 if (klass->ShouldHaveImt()) {
5845 // If there are any new conflicts compared to the super class we can not make a copy. There
5846 // can be cases where both will have a conflict method at the same slot without having the same
5847 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5848 // will possibly create a table that is incorrect for either of the classes.
5849 // Same IMT with new_conflict does not happen very often.
5850 if (!new_conflict) {
5851 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5852 if (super_imt != nullptr) {
5853 bool imt_equals = true;
5854 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5855 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5856 }
5857 if (imt_equals) {
5858 imt = super_imt;
5859 }
5860 }
5861 }
5862 if (imt == nullptr) {
5863 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5864 imt = reinterpret_cast<ImTable*>(
5865 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5866 if (imt == nullptr) {
5867 return false;
5868 }
5869 imt->Populate(imt_data, image_pointer_size_);
5870 }
5871 }
5872
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005873 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5874 // We don't need to retire this class as it has no embedded tables or it was created the
5875 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005876 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005877
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005878 if (klass->ShouldHaveEmbeddedVTable()) {
5879 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005880 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005881 if (klass->ShouldHaveImt()) {
5882 klass->SetImt(imt, image_pointer_size_);
5883 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005884
5885 // Update CHA info based on whether we override methods.
5886 // Have to do this before setting the class as resolved which allows
5887 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005888 if (cha_ != nullptr) {
5889 cha_->UpdateAfterLoadingOf(klass);
5890 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005891
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005892 // This will notify waiters on klass that saw the not yet resolved
5893 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005894 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005895 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005896 } else {
5897 CHECK(!klass->IsResolved());
5898 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005899 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005900 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005901 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5902 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5903 // may not see any references to the target space and clean the card for a class if another
5904 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005905 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005906 klass->SetSFieldsPtrUnchecked(nullptr);
5907 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005908 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005909 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005910 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005911 return false;
5912 }
5913
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005914 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5915 ObjectLock<mirror::Class> lock(self, h_new_class);
5916 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005917
5918 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005919 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005920 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005921 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005922 const ObjPtr<mirror::Class> existing =
5923 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005924 if (class_loader != nullptr) {
5925 // We updated the class in the class table, perform the write barrier so that the GC knows
5926 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005927 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005928 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005929 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005930 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005931 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5932 }
5933 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005934
Mingyao Yang063fc772016-08-02 11:02:54 -07005935 // Update CHA info based on whether we override methods.
5936 // Have to do this before setting the class as resolved which allows
5937 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005938 if (cha_ != nullptr) {
5939 cha_->UpdateAfterLoadingOf(h_new_class);
5940 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005941
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005942 // This will notify waiters on temp class that saw the not yet resolved class in the
5943 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005944 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005945
Vladimir Marko2c64a832018-01-04 11:31:56 +00005946 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005947 // This will notify waiters on new_class that saw the not yet resolved
5948 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005949 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005950 // Return the new class.
5951 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005952 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005953 return true;
5954}
5955
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005956bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005957 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005958 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005959 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5960 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005961 // Check that a class does not inherit from itself directly.
5962 //
5963 // TODO: This is a cheap check to detect the straightforward case
5964 // of a class extending itself (b/28685551), but we should do a
5965 // proper cycle detection on loaded classes, to detect all cases
5966 // of class circularity errors (b/28830038).
5967 if (super_class_idx == class_def.class_idx_) {
5968 ThrowClassCircularityError(klass.Get(),
5969 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005970 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005971 return false;
5972 }
5973
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005974 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005975 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005976 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005977 return false;
5978 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005979 // Verify
5980 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005981 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005982 super_class->PrettyDescriptor().c_str(),
5983 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005984 return false;
5985 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005986 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005987 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005988 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005989 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005990 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005991 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005992 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005993 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005994 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005995 DCHECK(Thread::Current()->IsExceptionPending());
5996 return false;
5997 }
5998 // Verify
5999 if (!klass->CanAccess(interface)) {
6000 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006001 ThrowIllegalAccessError(klass.Get(),
6002 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006003 interface->PrettyDescriptor().c_str(),
6004 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006005 return false;
6006 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006007 }
6008 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006009 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006010 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006011 return true;
6012}
6013
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006014bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006015 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006016 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006017 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6018 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006019 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006020 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006021 return false;
6022 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006023 return true;
6024 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006025 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006026 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006027 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006028 return false;
6029 }
6030 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006031 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006032 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6033 return false;
6034 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006035 if (super->IsFinal()) {
6036 ThrowVerifyError(klass.Get(),
6037 "Superclass %s of %s is declared final",
6038 super->PrettyDescriptor().c_str(),
6039 klass->PrettyDescriptor().c_str());
6040 return false;
6041 }
6042 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006043 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006044 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006045 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006046 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006047 return false;
6048 }
6049 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006050 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006051 super->PrettyDescriptor().c_str(),
6052 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006053 return false;
6054 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006055
Brian Carlstromf3632832014-05-20 15:36:53 -07006056 // Inherit kAccClassIsFinalizable from the superclass in case this
6057 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006058 if (super->IsFinalizable()) {
6059 klass->SetFinalizable();
6060 }
6061
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006062 // Inherit class loader flag form super class.
6063 if (super->IsClassLoaderClass()) {
6064 klass->SetClassLoaderClass();
6065 }
6066
Elliott Hughes2da50362011-10-10 16:57:08 -07006067 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006068 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006069 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006070 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006071 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006072 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006073 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006074 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006075 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006076 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006077 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006078 return false;
6079 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006080
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006081 if (kIsDebugBuild) {
6082 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006083 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006084 CHECK(super->IsResolved());
6085 super = super->GetSuperClass();
6086 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006087 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006088 return true;
6089}
6090
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006091// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006092bool ClassLinker::LinkMethods(Thread* self,
6093 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006094 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006095 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006096 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006097 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006098 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6099 // need to have default methods be in the virtuals array of each class but we don't set that up
6100 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006101 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006102 // Link virtual methods then interface methods.
6103 // We set up the interface lookup table first because we need it to determine if we need to update
6104 // any vtable entries with new default method implementations.
6105 return SetupInterfaceLookupTable(self, klass, interfaces)
6106 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006107 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006108}
6109
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006110// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6111// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6112// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006113class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006114 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006115 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006116 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006117 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6118 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006119 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006120 }
6121
6122 const char* GetName() {
6123 if (name_ == nullptr) {
6124 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6125 }
6126 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006127 }
6128
Mathieu Chartiere401d142015-04-22 13:56:20 -07006129 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006130 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006131 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006132 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006133 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006134 if (dex_file_ == other_dex_file) {
6135 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6136 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006137 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006138 uint32_t other_name_len;
6139 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6140 &other_name_len);
6141 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6142 return false;
6143 }
6144 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6145 }
6146
6147 private:
6148 // Dex file for the method to compare against.
6149 const DexFile* const dex_file_;
6150 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006151 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006152 // Lazily computed name from the dex file's strings.
6153 const char* name_;
6154 // Lazily computed name length.
6155 uint32_t name_len_;
6156};
6157
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006158class LinkVirtualHashTable {
6159 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006160 LinkVirtualHashTable(Handle<mirror::Class> klass,
6161 size_t hash_size,
6162 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006163 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006164 : klass_(klass),
6165 hash_size_(hash_size),
6166 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006167 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006168 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6169 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006170
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006171 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006172 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6173 virtual_method_index, image_pointer_size_);
6174 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006175 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006176 uint32_t index = hash % hash_size_;
6177 // Linear probe until we have an empty slot.
6178 while (hash_table_[index] != invalid_index_) {
6179 if (++index == hash_size_) {
6180 index = 0;
6181 }
6182 }
6183 hash_table_[index] = virtual_method_index;
6184 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006185
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006186 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006187 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006188 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006189 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006190 size_t index = hash % hash_size_;
6191 while (true) {
6192 const uint32_t value = hash_table_[index];
6193 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6194 // the block and can safely assume not found.
6195 if (value == invalid_index_) {
6196 break;
6197 }
6198 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006199 ArtMethod* virtual_method =
6200 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6201 if (comparator->HasSameNameAndSignature(
6202 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006203 hash_table_[index] = removed_index_;
6204 return value;
6205 }
6206 }
6207 if (++index == hash_size_) {
6208 index = 0;
6209 }
6210 }
6211 return GetNotFoundIndex();
6212 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006213
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006214 static uint32_t GetNotFoundIndex() {
6215 return invalid_index_;
6216 }
6217
6218 private:
6219 static const uint32_t invalid_index_;
6220 static const uint32_t removed_index_;
6221
6222 Handle<mirror::Class> klass_;
6223 const size_t hash_size_;
6224 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006225 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006226};
6227
6228const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6229const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6230
Stephen Hines1ddd9132017-02-08 01:51:18 -08006231bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006232 Thread* self,
6233 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006234 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006235 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006236 if (klass->IsInterface()) {
6237 // No vtable.
6238 if (!IsUint<16>(num_virtual_methods)) {
6239 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6240 return false;
6241 }
6242 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006243 // Assign each method an IMT index and set the default flag.
6244 for (size_t i = 0; i < num_virtual_methods; ++i) {
6245 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6246 m->SetMethodIndex(i);
6247 if (!m->IsAbstract()) {
6248 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6249 has_defaults = true;
6250 }
6251 }
6252 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6253 // during initialization. This is a performance optimization. We could simply traverse the
6254 // virtual_methods_ array again during initialization.
6255 if (has_defaults) {
6256 klass->SetHasDefaultMethods();
6257 }
6258 return true;
6259 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006260 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6261 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006262 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006263 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006264 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006265 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006266 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006267 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006268 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006269 return false;
6270 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006271 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006272 vtable->SetElementPtrSize(
6273 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006274 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006275 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6276 // might give us new default methods). If no new interfaces then we can skip the rest since
6277 // the class cannot override any of the super-class's methods. This is required for
6278 // correctness since without it we might not update overridden default method vtable entries
6279 // correctly.
6280 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006281 klass->SetVTable(vtable.Get());
6282 return true;
6283 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006284 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006285 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Markoc524e9e2019-03-26 10:54:50 +00006286 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006287 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006288 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6289 // might give us new default methods). See comment above.
6290 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006291 klass->SetVTable(super_vtable);
6292 return true;
6293 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006294 vtable = hs.NewHandle(
6295 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006296 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006297 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006298 return false;
6299 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006300 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006301 // How the algorithm works:
6302 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6303 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6304 // method which has not been matched to a vtable method, and j if the virtual method at the
6305 // index overrode the super virtual method at index j.
6306 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6307 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6308 // the need for the initial vtable which we later shrink back down).
6309 // 3. Add non overridden methods to the end of the vtable.
6310 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006311 // + 1 so that even if we only have new default methods we will still be able to use this hash
6312 // table (i.e. it will never have 0 size).
6313 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006314 uint32_t* hash_table_ptr;
6315 std::unique_ptr<uint32_t[]> hash_heap_storage;
6316 if (hash_table_size <= kMaxStackHash) {
6317 hash_table_ptr = reinterpret_cast<uint32_t*>(
6318 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6319 } else {
6320 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6321 hash_table_ptr = hash_heap_storage.get();
6322 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006323 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006324 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006325 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006326 DCHECK(klass->GetVirtualMethodDuringLinking(
6327 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006328 hash_table.Add(i);
6329 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006330 // 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 -07006331 // the hash table.
6332 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006333 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006334 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006335 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6336 super_method->GetAccessFlags())) {
6337 // Continue on to the next method since this one is package private and canot be overridden.
6338 // Before Android 4.1, the package-private method super_method might have been incorrectly
6339 // overridden.
6340 continue;
6341 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006342 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006343 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006344 // We remove the method so that subsequent lookups will be faster by making the hash-map
6345 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006346 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6347 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006348 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6349 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006350 if (super_method->IsFinal()) {
6351 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6352 virtual_method->PrettyMethod().c_str(),
6353 super_method->GetDeclaringClassDescriptor());
6354 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006355 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006356 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6357 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006358 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006359 // We didn't directly override this method but we might through default methods...
6360 // Check for default method update.
6361 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006362 switch (FindDefaultMethodImplementation(self,
6363 super_method,
6364 klass,
6365 /*out*/&default_method)) {
6366 case DefaultMethodSearchResult::kDefaultConflict: {
6367 // A conflict was found looking for default methods. Note this (assuming it wasn't
6368 // pre-existing) in the translations map.
6369 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6370 // Don't generate another conflict method to reduce memory use as an optimization.
6371 default_translations->insert(
6372 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6373 }
6374 break;
6375 }
6376 case DefaultMethodSearchResult::kAbstractFound: {
6377 // No conflict but method is abstract.
6378 // We note that this vtable entry must be made abstract.
6379 if (UNLIKELY(!super_method->IsAbstract())) {
6380 default_translations->insert(
6381 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6382 }
6383 break;
6384 }
6385 case DefaultMethodSearchResult::kDefaultFound: {
6386 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6387 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6388 // Found a default method implementation that is new.
6389 // TODO Refactor this add default methods to virtuals here and not in
6390 // LinkInterfaceMethods maybe.
6391 // The problem is default methods might override previously present
6392 // default-method or miranda-method vtable entries from the superclass.
6393 // Unfortunately we need these to be entries in this class's virtuals. We do not
6394 // give these entries there until LinkInterfaceMethods so we pass this map around
6395 // to let it know which vtable entries need to be updated.
6396 // Make a note that vtable entry j must be updated, store what it needs to be updated
6397 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6398 // then.
6399 default_translations->insert(
6400 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006401 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6402 << " overridden by default "
6403 << default_method->PrettyMethod()
6404 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006405 }
6406 break;
6407 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006408 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006409 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006410 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006411 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006412 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006413 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006414 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006415 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6416 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006417 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006418 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006419 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006420 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006421 local_method->SetMethodIndex(actual_count);
6422 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006423 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006424 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006425 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006426 return false;
6427 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006428 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006429 CHECK_LE(actual_count, max_count);
6430 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006431 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006432 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006433 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006434 return false;
6435 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006436 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006437 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006438 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006439 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006440 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006441 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6442 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006443 return false;
6444 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006445 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006446 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006447 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006448 return false;
6449 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006450 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006451 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6452 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006453 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006454 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006455 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006456 }
6457 return true;
6458}
6459
Alex Light9139e002015-10-09 15:59:48 -07006460// Determine if the given iface has any subinterface in the given list that declares the method
6461// specified by 'target'.
6462//
6463// Arguments
6464// - self: The thread we are running on
6465// - target: A comparator that will match any method that overrides the method we are checking for
6466// - iftable: The iftable we are searching for an overriding method on.
6467// - ifstart: The index of the interface we are checking to see if anything overrides
6468// - iface: The interface we are checking to see if anything overrides.
6469// - image_pointer_size:
6470// The image pointer size.
6471//
6472// Returns
6473// - True: There is some method that matches the target comparator defined in an interface that
6474// is a subtype of iface.
6475// - False: There is no method that matches the target comparator in any interface that is a subtype
6476// of iface.
6477static bool ContainsOverridingMethodOf(Thread* self,
6478 MethodNameAndSignatureComparator& target,
6479 Handle<mirror::IfTable> iftable,
6480 size_t ifstart,
6481 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006482 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006483 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006484 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006485 DCHECK(iface != nullptr);
6486 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006487 DCHECK_GE(ifstart, 0u);
6488 DCHECK_LT(ifstart, iftable->Count());
6489 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6490 DCHECK(iface->IsInterface());
6491
6492 size_t iftable_count = iftable->Count();
6493 StackHandleScope<1> hs(self);
6494 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6495 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6496 // Skip ifstart since our current interface obviously cannot override itself.
6497 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006498 // Iterate through every method on this interface. The order does not matter.
6499 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006500 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006501 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006502 // Check if the i'th interface is a subtype of this one.
6503 if (iface->IsAssignableFrom(current_iface.Get())) {
6504 return true;
6505 }
6506 break;
6507 }
6508 }
6509 }
6510 return false;
6511}
6512
Alex Lighteb7c1442015-08-31 13:17:42 -07006513// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006514// out_default_method and returns kDefaultFound on success. If no default method was found return
6515// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6516// default_method conflict) it will return kDefaultConflict.
6517ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6518 Thread* self,
6519 ArtMethod* target_method,
6520 Handle<mirror::Class> klass,
6521 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006522 DCHECK(self != nullptr);
6523 DCHECK(target_method != nullptr);
6524 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006525
6526 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006527
6528 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6529 // table. This lets us walk the table backwards when searching for default methods. The first one
6530 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6531 // track of it and then continue checking all other interfaces, since we need to throw an error if
6532 // we encounter conflicting default method implementations (one is not a subtype of the other).
6533 //
6534 // The order of unrelated interfaces does not matter and is not defined.
6535 size_t iftable_count = klass->GetIfTableCount();
6536 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006537 // No interfaces. We have already reset out to null so just return kAbstractFound.
6538 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006539 }
6540
Alex Light9139e002015-10-09 15:59:48 -07006541 StackHandleScope<3> hs(self);
6542 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006543 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006544 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006545 MethodNameAndSignatureComparator target_name_comparator(
6546 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6547 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006548 for (size_t k = iftable_count; k != 0; ) {
6549 --k;
6550
Alex Lighteb7c1442015-08-31 13:17:42 -07006551 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006552
6553 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006554 // Iterate through every declared method on this interface. The order does not matter.
6555 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6556 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006557 // Skip abstract methods and methods with different names.
6558 if (current_method->IsAbstract() ||
6559 !target_name_comparator.HasSameNameAndSignature(
6560 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6561 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006562 } else if (!current_method->IsPublic()) {
6563 // The verifier should have caught the non-public method for dex version 37. Just warn and
6564 // skip it since this is from before default-methods so we don't really need to care that it
6565 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006566 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6567 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006568 << "This will be a fatal error in subsequent versions of android. "
6569 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006570 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006571 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006572 // We have multiple default impls of the same method. This is a potential default conflict.
6573 // We need to check if this possibly conflicting method is either a superclass of the chosen
6574 // default implementation or is overridden by a non-default interface method. In either case
6575 // there is no conflict.
6576 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6577 !ContainsOverridingMethodOf(self,
6578 target_name_comparator,
6579 iftable,
6580 k,
6581 iface,
6582 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006583 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006584 << current_method->PrettyMethod() << " and "
6585 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6586 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006587 *out_default_method = nullptr;
6588 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006589 } else {
6590 break; // Continue checking at the next interface.
6591 }
6592 } else {
Alex Light9139e002015-10-09 15:59:48 -07006593 // chosen_iface == null
6594 if (!ContainsOverridingMethodOf(self,
6595 target_name_comparator,
6596 iftable,
6597 k,
6598 iface,
6599 image_pointer_size_)) {
6600 // Don't set this as the chosen interface if something else is overriding it (because that
6601 // other interface would be potentially chosen instead if it was default). If the other
6602 // interface was abstract then we wouldn't select this interface as chosen anyway since
6603 // the abstract method masks it.
6604 *out_default_method = current_method;
6605 chosen_iface.Assign(iface.Get());
6606 // We should now finish traversing the graph to find if we have default methods that
6607 // conflict.
6608 } else {
David Sehr709b0702016-10-13 09:12:37 -07006609 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6610 << "' was "
6611 << "skipped because it was overridden by an abstract method in a "
6612 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006613 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006614 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006615 break;
6616 }
6617 }
Alex Light9139e002015-10-09 15:59:48 -07006618 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006619 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6620 << "' selected "
6621 << "as the implementation for '" << target_method->PrettyMethod()
6622 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006623 return DefaultMethodSearchResult::kDefaultFound;
6624 } else {
6625 return DefaultMethodSearchResult::kAbstractFound;
6626 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006627}
6628
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006629ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006630 ArtMethod* conflict_method,
6631 ArtMethod* interface_method,
6632 ArtMethod* method,
6633 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006634 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006635 Runtime* const runtime = Runtime::Current();
6636 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6637 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6638
6639 // Create a new entry if the existing one is the shared conflict method.
6640 ArtMethod* new_conflict_method = new_entry
6641 ? runtime->CreateImtConflictMethod(linear_alloc)
6642 : conflict_method;
6643
6644 // Allocate a new table. Note that we will leak this table at the next conflict,
6645 // but that's a tradeoff compared to making the table fixed size.
6646 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006647 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6648 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006649 if (data == nullptr) {
6650 LOG(ERROR) << "Failed to allocate conflict table";
6651 return conflict_method;
6652 }
6653 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6654 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006655 method,
6656 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006657
6658 // Do a fence to ensure threads see the data in the table before it is assigned
6659 // to the conflict method.
6660 // Note that there is a race in the presence of multiple threads and we may leak
6661 // memory from the LinearAlloc, but that's a tradeoff compared to using
6662 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006663 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006664 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006665 return new_conflict_method;
6666}
6667
Vladimir Marko921094a2017-01-12 18:37:06 +00006668bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6669 Handle<mirror::Class> klass,
6670 Handle<mirror::IfTable> iftable) {
6671 DCHECK(!klass->IsInterface());
6672 const bool has_superclass = klass->HasSuperClass();
6673 const bool extend_super_iftable = has_superclass;
6674 const size_t ifcount = klass->GetIfTableCount();
6675 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6676 for (size_t i = 0; i < ifcount; ++i) {
6677 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6678 if (num_methods > 0) {
6679 const bool is_super = i < super_ifcount;
6680 // This is an interface implemented by a super-class. Therefore we can just copy the method
6681 // array from the superclass.
6682 const bool super_interface = is_super && extend_super_iftable;
6683 ObjPtr<mirror::PointerArray> method_array;
6684 if (super_interface) {
6685 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6686 DCHECK(if_table != nullptr);
6687 DCHECK(if_table->GetMethodArray(i) != nullptr);
6688 // If we are working on a super interface, try extending the existing method array.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00006689 method_array = ObjPtr<mirror::PointerArray>::DownCast(
6690 if_table->GetMethodArray(i)->Clone(self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006691 } else {
6692 method_array = AllocPointerArray(self, num_methods);
6693 }
6694 if (UNLIKELY(method_array == nullptr)) {
6695 self->AssertPendingOOMException();
6696 return false;
6697 }
6698 iftable->SetMethodArray(i, method_array);
6699 }
6700 }
6701 return true;
6702}
6703
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006704void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6705 ArtMethod* imt_conflict_method,
6706 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006707 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006708 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006709 // Place method in imt if entry is empty, place conflict otherwise.
6710 if (*imt_ref == unimplemented_method) {
6711 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006712 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006713 // If we are not a conflict and we have the same signature and name as the imt
6714 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006715 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6716 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006717 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006718 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006719 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006720 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006721 *imt_ref = current_method;
6722 } else {
Alex Light9139e002015-10-09 15:59:48 -07006723 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006724 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006725 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006726 } else {
6727 // Place the default conflict method. Note that there may be an existing conflict
6728 // method in the IMT, but it could be one tailored to the super class, with a
6729 // specific ImtConflictTable.
6730 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006731 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006732 }
6733}
6734
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006735void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006736 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6737 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006738 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006739 Runtime* const runtime = Runtime::Current();
6740 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6741 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006742 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006743 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006744 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006745 FillIMTFromIfTable(klass->GetIfTable(),
6746 unimplemented_method,
6747 conflict_method,
6748 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006749 /*create_conflict_tables=*/true,
6750 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006751 &new_conflict,
6752 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006753 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006754 if (!klass->ShouldHaveImt()) {
6755 return;
6756 }
6757 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6758 // we can just use the same pointer.
6759 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006760 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006761 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6762 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6763 bool same = true;
6764 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6765 ArtMethod* method = imt_data[i];
6766 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6767 if (method != super_method) {
6768 bool is_conflict_table = method->IsRuntimeMethod() &&
6769 method != unimplemented_method &&
6770 method != conflict_method;
6771 // Verify conflict contents.
6772 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6773 super_method != unimplemented_method &&
6774 super_method != conflict_method;
6775 if (!is_conflict_table || !super_conflict_table) {
6776 same = false;
6777 } else {
6778 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6779 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6780 same = same && table1->Equals(table2, image_pointer_size_);
6781 }
6782 }
6783 }
6784 if (same) {
6785 imt = super_imt;
6786 }
6787 }
6788 if (imt == nullptr) {
6789 imt = klass->GetImt(image_pointer_size_);
6790 DCHECK(imt != nullptr);
6791 imt->Populate(imt_data, image_pointer_size_);
6792 } else {
6793 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006794 }
6795}
6796
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006797ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6798 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006799 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006800 void* data = linear_alloc->Alloc(Thread::Current(),
6801 ImtConflictTable::ComputeSize(count,
6802 image_pointer_size));
6803 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6804}
6805
6806ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6807 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6808}
6809
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006810void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006811 ArtMethod* unimplemented_method,
6812 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006813 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006814 bool create_conflict_tables,
6815 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006816 /*out*/bool* new_conflict,
6817 /*out*/ArtMethod** imt) {
6818 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006819 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006820 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821 const size_t num_virtuals = interface->NumVirtualMethods();
6822 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6823 // Virtual methods can be larger than the if table methods if there are default methods.
6824 DCHECK_GE(num_virtuals, method_array_count);
6825 if (kIsDebugBuild) {
6826 if (klass->IsInterface()) {
6827 DCHECK_EQ(method_array_count, 0u);
6828 } else {
6829 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6830 }
6831 }
6832 if (method_array_count == 0) {
6833 continue;
6834 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006835 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006836 for (size_t j = 0; j < method_array_count; ++j) {
6837 ArtMethod* implementation_method =
6838 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6839 if (ignore_copied_methods && implementation_method->IsCopied()) {
6840 continue;
6841 }
6842 DCHECK(implementation_method != nullptr);
6843 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6844 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6845 // or interface methods in the IMT here they will not create extra conflicts since we compare
6846 // names and signatures in SetIMTRef.
6847 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006848 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006849
6850 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6851 // the same implementation method, keep track of this to avoid creating a conflict table in
6852 // this case.
6853
6854 // Conflict table size for each IMT slot.
6855 ++conflict_counts[imt_index];
6856
6857 SetIMTRef(unimplemented_method,
6858 imt_conflict_method,
6859 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006860 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006861 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006862 }
6863 }
6864
6865 if (create_conflict_tables) {
6866 // Create the conflict tables.
6867 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006868 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006869 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006870 if (imt[i] == imt_conflict_method) {
6871 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6872 if (new_table != nullptr) {
6873 ArtMethod* new_conflict_method =
6874 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6875 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6876 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006877 } else {
6878 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006879 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006880 }
6881 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006882 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006883 }
6884 }
6885
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006886 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006887 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006888 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6889 // Virtual methods can be larger than the if table methods if there are default methods.
6890 if (method_array_count == 0) {
6891 continue;
6892 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006893 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006894 for (size_t j = 0; j < method_array_count; ++j) {
6895 ArtMethod* implementation_method =
6896 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6897 if (ignore_copied_methods && implementation_method->IsCopied()) {
6898 continue;
6899 }
6900 DCHECK(implementation_method != nullptr);
6901 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006902 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006903 if (!imt[imt_index]->IsRuntimeMethod() ||
6904 imt[imt_index] == unimplemented_method ||
6905 imt[imt_index] == imt_conflict_method) {
6906 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006907 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006908 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6909 const size_t num_entries = table->NumEntries(image_pointer_size_);
6910 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6911 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006912 }
6913 }
6914 }
6915}
6916
Alex Lighteb7c1442015-08-31 13:17:42 -07006917// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6918// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006919static bool NotSubinterfaceOfAny(
6920 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6921 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006922 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006923 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006924 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006925 for (ObjPtr<mirror::Class> c : classes) {
6926 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006927 return false;
6928 }
6929 }
6930 return true;
6931}
6932
6933// Fills in and flattens the interface inheritance hierarchy.
6934//
6935// By the end of this function all interfaces in the transitive closure of to_process are added to
6936// the iftable and every interface precedes all of its sub-interfaces in this list.
6937//
6938// all I, J: Interface | I <: J implies J precedes I
6939//
6940// (note A <: B means that A is a subtype of B)
6941//
6942// This returns the total number of items in the iftable. The iftable might be resized down after
6943// this call.
6944//
6945// We order this backwards so that we do not need to reorder superclass interfaces when new
6946// interfaces are added in subclass's interface tables.
6947//
6948// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6949// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6950// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6951// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006952static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006953 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006954 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006955 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006956 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006957 // This is the set of all class's already in the iftable. Used to make checking if a class has
6958 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006959 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006960 // The first super_ifcount elements are from the superclass. We note that they are already added.
6961 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006962 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006963 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6964 classes_in_iftable.insert(iface);
6965 }
6966 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006967 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006968 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6969 // At this point in the loop current-iface-list has the invariant that:
6970 // for every pair of interfaces I,J within it:
6971 // if index_of(I) < index_of(J) then I is not a subtype of J
6972
6973 // If we have already seen this element then all of its super-interfaces must already be in the
6974 // current-iface-list so we can skip adding it.
6975 if (!ContainsElement(classes_in_iftable, interface)) {
6976 // We haven't seen this interface so add all of its super-interfaces onto the
6977 // current-iface-list, skipping those already on it.
6978 int32_t ifcount = interface->GetIfTableCount();
6979 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006980 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006981 if (!ContainsElement(classes_in_iftable, super_interface)) {
6982 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6983 classes_in_iftable.insert(super_interface);
6984 iftable->SetInterface(filled_ifcount, super_interface);
6985 filled_ifcount++;
6986 }
6987 }
6988 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6989 // Place this interface onto the current-iface-list after all of its super-interfaces.
6990 classes_in_iftable.insert(interface);
6991 iftable->SetInterface(filled_ifcount, interface);
6992 filled_ifcount++;
6993 } else if (kIsDebugBuild) {
6994 // Check all super-interfaces are already in the list.
6995 int32_t ifcount = interface->GetIfTableCount();
6996 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006997 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006998 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006999 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7000 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007001 }
7002 }
7003 }
7004 if (kIsDebugBuild) {
7005 // Check that the iftable is ordered correctly.
7006 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007007 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007008 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007009 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007010 // !(if_a <: if_b)
7011 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007012 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7013 << ") extends "
7014 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007015 << "interface list.";
7016 }
7017 }
7018 }
7019 return filled_ifcount;
7020}
7021
7022bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7023 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7024 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007025 const bool has_superclass = klass->HasSuperClass();
7026 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007027 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007028 const size_t num_interfaces =
7029 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007030 if (num_interfaces == 0) {
7031 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007032 if (LIKELY(has_superclass)) {
7033 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7034 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007035 // Class implements no interfaces.
7036 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007037 return true;
7038 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007039 // Class implements same interfaces as parent, are any of these not marker interfaces?
7040 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007041 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007042 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007043 if (super_iftable->GetMethodArrayCount(i) > 0) {
7044 has_non_marker_interface = true;
7045 break;
7046 }
7047 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007048 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007049 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007050 klass->SetIfTable(super_iftable);
7051 return true;
7052 }
7053 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007054 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007055 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007056 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007057 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007058 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007059 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007060 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007061 if (UNLIKELY(!interface->IsInterface())) {
7062 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007063 ThrowIncompatibleClassChangeError(klass.Get(),
7064 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007065 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007066 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7067 return false;
7068 }
7069 ifcount += interface->GetIfTableCount();
7070 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007071 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007072 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007073 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007074 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007075 return false;
7076 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007077 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007078 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007079 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007080 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007081 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007082 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007083 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007084 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007085
7086 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7087 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7088 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007089 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007090
7091 size_t new_ifcount;
7092 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007093 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007094 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007095 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007096 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007097 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007098 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007099 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007100
7101 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007102 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007103
Ian Rogers7b078e82014-09-10 14:44:24 -07007104 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007105
Ian Rogersb52b01a2012-01-12 17:01:38 -08007106 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007107 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007108 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007109 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007110 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007111 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007112 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007113 return false;
7114 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007115 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007116 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007117 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007118 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007119 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007120 return true;
7121}
7122
Alex Light1f3925d2016-09-07 12:04:20 -07007123// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7124// of methods must be unique.
7125static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7126 return nullptr;
7127}
7128
7129template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007130static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007131 const ScopedArenaVector<ArtMethod*>& list,
7132 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007133 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007134 for (ArtMethod* method : list) {
7135 if (cmp.HasSameNameAndSignature(method)) {
7136 return method;
7137 }
7138 }
Alex Light1f3925d2016-09-07 12:04:20 -07007139 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007140}
7141
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007142namespace {
7143
Alex Light1f3925d2016-09-07 12:04:20 -07007144// Check that all vtable entries are present in this class's virtuals or are the same as a
7145// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007146void CheckClassOwnsVTableEntries(Thread* self,
7147 Handle<mirror::Class> klass,
7148 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007149 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007150 StackHandleScope<2> hs(self);
7151 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007152 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007153 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007154 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007155 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7156 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7157 CHECK(m != nullptr);
7158
Alex Lighta41a30782017-03-29 11:33:19 -07007159 if (m->GetMethodIndexDuringLinking() != i) {
7160 LOG(WARNING) << m->PrettyMethod()
7161 << " has an unexpected method index for its spot in the vtable for class"
7162 << klass->PrettyClass();
7163 }
Alex Lighte64300b2015-12-15 15:02:47 -08007164 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7165 auto is_same_method = [m] (const ArtMethod& meth) {
7166 return &meth == m;
7167 };
Alex Light3f980532017-03-17 15:10:32 -07007168 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7169 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7170 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7171 << klass->PrettyClass() << " or any of its superclasses!";
7172 }
Alex Lighte64300b2015-12-15 15:02:47 -08007173 }
7174}
7175
Alex Light1f3925d2016-09-07 12:04:20 -07007176// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7177// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007178template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007179void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007180 REQUIRES_SHARED(Locks::mutator_lock_) {
7181 StackHandleScope<1> hs(self);
7182 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7183 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007184
7185 // Observations:
7186 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7187 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7188 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7189 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7190 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7191 // * The single-pass algorithm will trade memory for speed, but that is OK.
7192
7193 CHECK_GT(num_entries, 0);
7194
7195 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7196 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7197 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7198 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7199 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7200 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7201 << m2->PrettyMethod() << " (0x" << std::hex
7202 << reinterpret_cast<uintptr_t>(m2) << ")";
7203 };
7204 struct BaseHashType {
7205 static size_t HashCombine(size_t seed, size_t val) {
7206 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7207 }
7208 };
7209
7210 // Check assuming all entries come from the same dex file.
7211 {
7212 // Find the first interesting method and its dex file.
7213 int32_t start = 0;
7214 for (; start < num_entries; ++start) {
7215 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7216 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7217 // maybe).
7218 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7219 vtable_entry->GetAccessFlags())) {
7220 continue;
7221 }
7222 break;
7223 }
7224 if (start == num_entries) {
7225 return;
7226 }
7227 const DexFile* dex_file =
7228 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7229 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7230
7231 // Helper function to avoid logging if we have to run the cross-file checks.
7232 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7233 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7234 using PairType = std::pair<uint32_t, uint16_t>;
7235 struct PairHash : BaseHashType {
7236 size_t operator()(const PairType& key) const {
7237 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7238 }
7239 };
7240 std::unordered_map<PairType, int32_t, PairHash> seen;
7241 seen.reserve(2 * num_entries);
7242 bool need_slow_path = false;
7243 bool found_dup = false;
7244 for (int i = start; i < num_entries; ++i) {
7245 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7246 // wrt/ kPointerSize.
7247 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7248 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7249 vtable_entry->GetAccessFlags())) {
7250 continue;
7251 }
7252 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7253 if (dex_file != m->GetDexFile()) {
7254 need_slow_path = true;
7255 break;
7256 }
7257 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7258 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7259 auto it = seen.find(pair);
7260 if (it != seen.end()) {
7261 found_dup = true;
7262 if (log_warn) {
7263 log_fn(it->second, i);
7264 }
7265 } else {
7266 seen.emplace(pair, i);
7267 }
7268 }
7269 return std::make_pair(need_slow_path, found_dup);
7270 };
7271 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7272 if (!result.first) {
7273 if (result.second) {
7274 check_fn(/* log_warn= */ true);
7275 }
7276 return;
7277 }
7278 }
7279
7280 // Need to check across dex files.
7281 struct Entry {
7282 size_t cached_hash = 0;
7283 const char* name = nullptr;
7284 Signature signature = Signature::NoSignature();
7285 uint32_t name_len = 0;
7286
7287 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7288 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7289 signature(dex_file->GetMethodSignature(mid)) {
7290 }
7291
7292 bool operator==(const Entry& other) const {
7293 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7294 return false;
7295 }
7296 return signature == other.signature;
7297 }
7298 };
7299 struct EntryHash {
7300 size_t operator()(const Entry& key) const {
7301 return key.cached_hash;
7302 }
7303 };
7304 std::unordered_map<Entry, int32_t, EntryHash> map;
7305 for (int32_t i = 0; i < num_entries; ++i) {
7306 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7307 // wrt/ kPointerSize.
7308 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7309 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7310 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007311 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7312 vtable_entry->GetAccessFlags())) {
7313 continue;
7314 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007315 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7316 const DexFile* dex_file = m->GetDexFile();
7317 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7318
7319 Entry e(dex_file, mid);
7320
7321 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7322 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7323 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7324 sig_hash);
7325
7326 auto it = map.find(e);
7327 if (it != map.end()) {
7328 log_fn(it->second, i);
7329 } else {
7330 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007331 }
7332 }
7333}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007334
7335void CheckVTableHasNoDuplicates(Thread* self,
7336 Handle<mirror::Class> klass,
7337 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007338 REQUIRES_SHARED(Locks::mutator_lock_) {
7339 switch (pointer_size) {
7340 case PointerSize::k64:
7341 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7342 break;
7343 case PointerSize::k32:
7344 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7345 break;
7346 }
7347}
Alex Light1f3925d2016-09-07 12:04:20 -07007348
7349static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7350 REQUIRES_SHARED(Locks::mutator_lock_) {
7351 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7352 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7353}
7354
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007355} // namespace
7356
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007357void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7358 ArtMethod* unimplemented_method,
7359 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007360 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007361 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007362 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007363 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007364 if (super_class->ShouldHaveImt()) {
7365 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7366 for (size_t i = 0; i < ImTable::kSize; ++i) {
7367 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007368 }
7369 } else {
7370 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007371 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007372 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007373 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007374 FillIMTFromIfTable(if_table,
7375 unimplemented_method,
7376 imt_conflict_method,
7377 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007378 /*create_conflict_tables=*/false,
7379 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007380 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007381 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007382 }
7383 }
7384}
7385
Vladimir Marko921094a2017-01-12 18:37:06 +00007386class ClassLinker::LinkInterfaceMethodsHelper {
7387 public:
7388 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7389 Handle<mirror::Class> klass,
7390 Thread* self,
7391 Runtime* runtime)
7392 : class_linker_(class_linker),
7393 klass_(klass),
7394 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7395 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7396 self_(self),
7397 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7398 allocator_(&stack_),
7399 default_conflict_methods_(allocator_.Adapter()),
7400 overriding_default_conflict_methods_(allocator_.Adapter()),
7401 miranda_methods_(allocator_.Adapter()),
7402 default_methods_(allocator_.Adapter()),
7403 overriding_default_methods_(allocator_.Adapter()),
7404 move_table_(allocator_.Adapter()) {
7405 }
7406
7407 ArtMethod* FindMethod(ArtMethod* interface_method,
7408 MethodNameAndSignatureComparator& interface_name_comparator,
7409 ArtMethod* vtable_impl)
7410 REQUIRES_SHARED(Locks::mutator_lock_);
7411
7412 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7413 MethodNameAndSignatureComparator& interface_name_comparator)
7414 REQUIRES_SHARED(Locks::mutator_lock_);
7415
7416 bool HasNewVirtuals() const {
7417 return !(miranda_methods_.empty() &&
7418 default_methods_.empty() &&
7419 overriding_default_methods_.empty() &&
7420 overriding_default_conflict_methods_.empty() &&
7421 default_conflict_methods_.empty());
7422 }
7423
7424 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7425
7426 ObjPtr<mirror::PointerArray> UpdateVtable(
7427 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7428 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7429
7430 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7431
7432 void UpdateIMT(ArtMethod** out_imt);
7433
7434 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7435 if (kIsDebugBuild) {
7436 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7437 // Check that there are no stale methods are in the dex cache array.
7438 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7439 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007440 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7441 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007442 CHECK(move_table_.find(m) == move_table_.end() ||
7443 // The original versions of copied methods will still be present so allow those too.
7444 // Note that if the first check passes this might fail to GetDeclaringClass().
7445 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7446 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7447 [m] (ArtMethod& meth) {
7448 return &meth == m;
7449 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7450 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7451 }
7452 }
7453 }
7454
7455 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7456 LengthPrefixedArray<ArtMethod>* methods) {
7457 if (kIsDebugBuild) {
7458 CHECK(methods != nullptr);
7459 // Put some random garbage in old methods to help find stale pointers.
7460 if (methods != old_methods && old_methods != nullptr) {
7461 // Need to make sure the GC is not running since it could be scanning the methods we are
7462 // about to overwrite.
7463 ScopedThreadStateChange tsc(self_, kSuspended);
7464 gc::ScopedGCCriticalSection gcs(self_,
7465 gc::kGcCauseClassLinker,
7466 gc::kCollectorTypeClassLinker);
7467 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7468 method_size_,
7469 method_alignment_);
7470 memset(old_methods, 0xFEu, old_size);
7471 }
7472 }
7473 }
7474
7475 private:
7476 size_t NumberOfNewVirtuals() const {
7477 return miranda_methods_.size() +
7478 default_methods_.size() +
7479 overriding_default_conflict_methods_.size() +
7480 overriding_default_methods_.size() +
7481 default_conflict_methods_.size();
7482 }
7483
7484 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7485 return !klass_->IsInterface();
7486 }
7487
7488 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7489 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7490 << "Interfaces should only have default-conflict methods appended to them.";
7491 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7492 << miranda_methods_.size()
7493 << " default_methods=" << default_methods_.size()
7494 << " overriding_default_methods=" << overriding_default_methods_.size()
7495 << " default_conflict_methods=" << default_conflict_methods_.size()
7496 << " overriding_default_conflict_methods="
7497 << overriding_default_conflict_methods_.size();
7498 }
7499
7500 ClassLinker* class_linker_;
7501 Handle<mirror::Class> klass_;
7502 size_t method_alignment_;
7503 size_t method_size_;
7504 Thread* const self_;
7505
7506 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7507 // the virtual methods array.
7508 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7509 // during cross compilation.
7510 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7511 ArenaStack stack_;
7512 ScopedArenaAllocator allocator_;
7513
7514 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7515 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7516 ScopedArenaVector<ArtMethod*> miranda_methods_;
7517 ScopedArenaVector<ArtMethod*> default_methods_;
7518 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7519
7520 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7521};
7522
7523ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7524 ArtMethod* interface_method,
7525 MethodNameAndSignatureComparator& interface_name_comparator,
7526 ArtMethod* vtable_impl) {
7527 ArtMethod* current_method = nullptr;
7528 switch (class_linker_->FindDefaultMethodImplementation(self_,
7529 interface_method,
7530 klass_,
7531 /*out*/&current_method)) {
7532 case DefaultMethodSearchResult::kDefaultConflict: {
7533 // Default method conflict.
7534 DCHECK(current_method == nullptr);
7535 ArtMethod* default_conflict_method = nullptr;
7536 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7537 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7538 default_conflict_method = vtable_impl;
7539 } else {
7540 // See if we already have a conflict method for this method.
7541 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7542 interface_name_comparator,
7543 default_conflict_methods_,
7544 overriding_default_conflict_methods_);
7545 if (LIKELY(preexisting_conflict != nullptr)) {
7546 // We already have another conflict we can reuse.
7547 default_conflict_method = preexisting_conflict;
7548 } else {
7549 // Note that we do this even if we are an interface since we need to create this and
7550 // cannot reuse another classes.
7551 // Create a new conflict method for this to use.
7552 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7553 new(default_conflict_method) ArtMethod(interface_method,
7554 class_linker_->GetImagePointerSize());
7555 if (vtable_impl == nullptr) {
7556 // Save the conflict method. We need to add it to the vtable.
7557 default_conflict_methods_.push_back(default_conflict_method);
7558 } else {
7559 // Save the conflict method but it is already in the vtable.
7560 overriding_default_conflict_methods_.push_back(default_conflict_method);
7561 }
7562 }
7563 }
7564 current_method = default_conflict_method;
7565 break;
7566 } // case kDefaultConflict
7567 case DefaultMethodSearchResult::kDefaultFound: {
7568 DCHECK(current_method != nullptr);
7569 // Found a default method.
7570 if (vtable_impl != nullptr &&
7571 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7572 // We found a default method but it was the same one we already have from our
7573 // superclass. Don't bother adding it to our vtable again.
7574 current_method = vtable_impl;
7575 } else if (LIKELY(FillTables())) {
7576 // Interfaces don't need to copy default methods since they don't have vtables.
7577 // Only record this default method if it is new to save space.
7578 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7579 // would make lookup for interface super much faster. (We would only need to scan
7580 // the iftable to find if there is a NSME or AME.)
7581 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7582 default_methods_,
7583 overriding_default_methods_);
7584 if (old == nullptr) {
7585 // We found a default method implementation and there were no conflicts.
7586 if (vtable_impl == nullptr) {
7587 // Save the default method. We need to add it to the vtable.
7588 default_methods_.push_back(current_method);
7589 } else {
7590 // Save the default method but it is already in the vtable.
7591 overriding_default_methods_.push_back(current_method);
7592 }
7593 } else {
7594 CHECK(old == current_method) << "Multiple default implementations selected!";
7595 }
7596 }
7597 break;
7598 } // case kDefaultFound
7599 case DefaultMethodSearchResult::kAbstractFound: {
7600 DCHECK(current_method == nullptr);
7601 // Abstract method masks all defaults.
7602 if (vtable_impl != nullptr &&
7603 vtable_impl->IsAbstract() &&
7604 !vtable_impl->IsDefaultConflicting()) {
7605 // We need to make this an abstract method but the version in the vtable already is so
7606 // don't do anything.
7607 current_method = vtable_impl;
7608 }
7609 break;
7610 } // case kAbstractFound
7611 }
7612 return current_method;
7613}
7614
7615ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7616 ArtMethod* interface_method,
7617 MethodNameAndSignatureComparator& interface_name_comparator) {
7618 // Find out if there is already a miranda method we can use.
7619 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7620 miranda_methods_);
7621 if (miranda_method == nullptr) {
7622 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7623 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7624 CHECK(miranda_method != nullptr);
7625 // Point the interface table at a phantom slot.
7626 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7627 miranda_methods_.push_back(miranda_method);
7628 }
7629 return miranda_method;
7630}
7631
7632void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7633 LogNewVirtuals();
7634
7635 const size_t old_method_count = klass_->NumMethods();
7636 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7637 DCHECK_NE(old_method_count, new_method_count);
7638
7639 // Attempt to realloc to save RAM if possible.
7640 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7641 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7642 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7643 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7644 // CopyFrom has internal read barriers.
7645 //
7646 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7647 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7648 method_size_,
7649 method_alignment_);
7650 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7651 method_size_,
7652 method_alignment_);
7653 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7654 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007655 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007656 self_, old_methods, old_methods_ptr_size, new_size));
7657 CHECK(methods != nullptr); // Native allocation failure aborts.
7658
7659 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7660 if (methods != old_methods) {
7661 // Maps from heap allocated miranda method to linear alloc miranda method.
7662 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7663 // Copy over the old methods.
7664 for (auto& m : klass_->GetMethods(pointer_size)) {
7665 move_table_.emplace(&m, &*out);
7666 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7667 // barriers when it copies.
7668 out->CopyFrom(&m, pointer_size);
7669 ++out;
7670 }
7671 }
7672 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7673 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7674 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007675 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7676 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007677 ArtMethod& new_method = *out;
7678 new_method.CopyFrom(mir_method, pointer_size);
7679 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7680 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7681 << "Miranda method should be abstract!";
7682 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007683 // Update the entry in the method array, as the array will be used for future lookups,
7684 // where thread suspension is allowed.
7685 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7686 // would not see them.
7687 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007688 ++out;
7689 }
7690 // We need to copy the default methods into our own method table since the runtime requires that
7691 // every method on a class's vtable be in that respective class's virtual method table.
7692 // NOTE This means that two classes might have the same implementation of a method from the same
7693 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7694 // default method found on a class with one found on the declaring interface directly and must
7695 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007696 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7697 &overriding_default_methods_}) {
7698 for (size_t i = 0; i < methods_vec->size(); ++i) {
7699 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007700 ArtMethod& new_method = *out;
7701 new_method.CopyFrom(def_method, pointer_size);
7702 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7703 // verified yet it shouldn't have methods that are skipping access checks.
7704 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7705 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007706 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007707 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7708 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7709 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7710 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007711 // Update the entry in the method array, as the array will be used for future lookups,
7712 // where thread suspension is allowed.
7713 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7714 // would not see them.
7715 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007716 ++out;
7717 }
7718 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007719 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7720 &overriding_default_conflict_methods_}) {
7721 for (size_t i = 0; i < methods_vec->size(); ++i) {
7722 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007723 ArtMethod& new_method = *out;
7724 new_method.CopyFrom(conf_method, pointer_size);
7725 // This is a type of default method (there are default method impls, just a conflict) so
7726 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7727 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7728 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007729 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7730 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007731 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007732 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007733 constexpr uint32_t kMaskFlags =
7734 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007735 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7736 DCHECK(new_method.IsDefaultConflicting());
7737 // The actual method might or might not be marked abstract since we just copied it from a
7738 // (possibly default) interface method. We need to set it entry point to be the bridge so
7739 // that the compiler will not invoke the implementation of whatever method we copied from.
7740 EnsureThrowsInvocationError(class_linker_, &new_method);
7741 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007742 // Update the entry in the method array, as the array will be used for future lookups,
7743 // where thread suspension is allowed.
7744 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7745 // would not see them.
7746 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007747 ++out;
7748 }
7749 }
7750 methods->SetSize(new_method_count);
7751 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7752}
7753
7754ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7755 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7756 ObjPtr<mirror::PointerArray> old_vtable) {
7757 // Update the vtable to the new method structures. We can skip this for interfaces since they
7758 // do not have vtables.
7759 const size_t old_vtable_count = old_vtable->GetLength();
7760 const size_t new_vtable_count = old_vtable_count +
7761 miranda_methods_.size() +
7762 default_methods_.size() +
7763 default_conflict_methods_.size();
7764
7765 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007766 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007767 if (UNLIKELY(vtable == nullptr)) {
7768 self_->AssertPendingOOMException();
7769 return nullptr;
7770 }
7771
7772 size_t vtable_pos = old_vtable_count;
7773 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7774 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7775 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7776 default_conflict_methods_,
7777 miranda_methods_}) {
7778 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007779 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007780 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7781 // fields are references into the dex file the method was defined in. Since the ArtMethod
7782 // does not store that information it uses declaring_class_->dex_cache_.
7783 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7784 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7785 ++vtable_pos;
7786 }
7787 }
7788 DCHECK_EQ(vtable_pos, new_vtable_count);
7789
7790 // Update old vtable methods. We use the default_translations map to figure out what each
7791 // vtable entry should be updated to, if they need to be at all.
7792 for (size_t i = 0; i < old_vtable_count; ++i) {
7793 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7794 // Try and find what we need to change this method to.
7795 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007796 if (translation_it != default_translations.end()) {
7797 if (translation_it->second.IsInConflict()) {
7798 // Find which conflict method we are to use for this method.
7799 MethodNameAndSignatureComparator old_method_comparator(
7800 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7801 // We only need to look through overriding_default_conflict_methods since this is an
7802 // overridden method we are fixing up here.
7803 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7804 old_method_comparator, overriding_default_conflict_methods_);
7805 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7806 translated_method = new_conflict_method;
7807 } else if (translation_it->second.IsAbstract()) {
7808 // Find which miranda method we are to use for this method.
7809 MethodNameAndSignatureComparator old_method_comparator(
7810 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7811 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7812 miranda_methods_);
7813 DCHECK(miranda_method != nullptr);
7814 translated_method = miranda_method;
7815 } else {
7816 // Normal default method (changed from an older default or abstract interface method).
7817 DCHECK(translation_it->second.IsTranslation());
7818 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007819 auto it = move_table_.find(translated_method);
7820 DCHECK(it != move_table_.end());
7821 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007822 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007823 } else {
7824 auto it = move_table_.find(translated_method);
7825 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007826 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007827
7828 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007829 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007830 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007831 if (kIsDebugBuild) {
7832 auto* methods = klass_->GetMethodsPtr();
7833 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007834 reinterpret_cast<uintptr_t>(translated_method));
7835 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007836 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7837 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007838 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007839 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007840 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007841 }
7842 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007843 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007844 return vtable;
7845}
7846
7847void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7848 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7849 const size_t ifcount = klass_->GetIfTableCount();
7850 // Go fix up all the stale iftable pointers.
7851 for (size_t i = 0; i < ifcount; ++i) {
7852 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007853 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7854 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007855 DCHECK(m != nullptr) << klass_->PrettyClass();
7856 auto it = move_table_.find(m);
7857 if (it != move_table_.end()) {
7858 auto* new_m = it->second;
7859 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7860 method_array->SetElementPtrSize(j, new_m, pointer_size);
7861 }
7862 }
7863 }
7864}
7865
7866void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7867 // Fix up IMT next.
7868 for (size_t i = 0; i < ImTable::kSize; ++i) {
7869 auto it = move_table_.find(out_imt[i]);
7870 if (it != move_table_.end()) {
7871 out_imt[i] = it->second;
7872 }
7873 }
7874}
7875
Alex Light705ad492015-09-21 11:36:30 -07007876// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007877bool ClassLinker::LinkInterfaceMethods(
7878 Thread* self,
7879 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007880 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007881 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007882 ArtMethod** out_imt) {
7883 StackHandleScope<3> hs(self);
7884 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007885
7886 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007887 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007888 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007889 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007890 const size_t ifcount = klass->GetIfTableCount();
7891
Vladimir Marko921094a2017-01-12 18:37:06 +00007892 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007893
7894 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7895 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007896 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007897 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007898 const bool extend_super_iftable = has_superclass;
7899 if (has_superclass && fill_tables) {
7900 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007901 unimplemented_method,
7902 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007903 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007904 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007905 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007906 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7907 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007908 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007909 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7910 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007911 }
7912 }
7913
Vladimir Marko921094a2017-01-12 18:37:06 +00007914 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7915
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007916 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007917 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007918 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7919 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7920 // they will already be null. This has the additional benefit that the declarer of a miranda
7921 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007922 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007923 --i;
Alex Light9139e002015-10-09 15:59:48 -07007924 DCHECK_LT(i, ifcount);
7925
Alex Light705ad492015-09-21 11:36:30 -07007926 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007927 if (num_methods > 0) {
7928 StackHandleScope<2> hs2(self);
7929 const bool is_super = i < super_ifcount;
7930 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007931 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7932 // conflict methods. Just set this as nullptr in those cases.
7933 Handle<mirror::PointerArray> method_array(fill_tables
7934 ? hs2.NewHandle(iftable->GetMethodArray(i))
7935 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007936
Alex Lighte64300b2015-12-15 15:02:47 -08007937 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007938 ScopedNullHandle<mirror::PointerArray> null_handle;
7939 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007940 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007941
Alex Light9139e002015-10-09 15:59:48 -07007942 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7943 // and confusing. Default methods should always look through all the superclasses
7944 // because they are the last choice of an implementation. We get around this by looking
7945 // at the super-classes iftable methods (copied into method_array previously) when we are
7946 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007947 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007948 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007949 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007950 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007951 using_virtuals = true;
7952 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7953 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007954 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007955 // For a new interface, however, we need the whole vtable in case a new
7956 // interface method is implemented in the whole superclass.
7957 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007958 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007959 input_vtable_array = vtable;
7960 input_array_length = input_vtable_array->GetLength();
7961 }
Alex Lighte64300b2015-12-15 15:02:47 -08007962
Alex Lighteb7c1442015-08-31 13:17:42 -07007963 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007964 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007965 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007966 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007967 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007968 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007969 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007970 // For each method listed in the interface's method list, find the
7971 // matching method in our class's method list. We want to favor the
7972 // subclass over the superclass, which just requires walking
7973 // back from the end of the vtable. (This only matters if the
7974 // superclass defines a private method and this class redefines
7975 // it -- otherwise it would use the same vtable slot. In .dex files
7976 // those don't end up in the virtual method table, so it shouldn't
7977 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007978 //
7979 // To find defaults we need to do the same but also go over interfaces.
7980 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007981 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007982 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007983 ArtMethod* vtable_method = using_virtuals ?
7984 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007985 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7986 ArtMethod* vtable_method_for_name_comparison =
7987 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007988 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007989 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007990 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007991 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7992 // allocations.
7993 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007994 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007995 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007996 vtable_method->PrettyMethod().c_str(),
7997 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007998 return false;
Alex Light9139e002015-10-09 15:59:48 -07007999 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008000 // We might have a newer, better, default method for this, so we just skip it. If we
8001 // are still using this we will select it again when scanning for default methods. To
8002 // obviate the need to copy the method again we will make a note that we already found
8003 // a default here.
8004 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008005 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008006 break;
8007 } else {
8008 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008009 if (LIKELY(fill_tables)) {
8010 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8011 // Place method in imt if entry is empty, place conflict otherwise.
8012 SetIMTRef(unimplemented_method,
8013 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008014 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008015 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008016 /*out*/imt_ptr);
8017 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008018 break;
8019 }
8020 }
Alex Light9139e002015-10-09 15:59:48 -07008021 }
8022 // Continue on to the next method if we are done.
8023 if (LIKELY(found_impl)) {
8024 continue;
8025 } else if (LIKELY(super_interface)) {
8026 // Don't look for a default implementation when the super-method is implemented directly
8027 // by the class.
8028 //
8029 // See if we can use the superclasses method and skip searching everything else.
8030 // Note: !found_impl && super_interface
8031 CHECK(extend_super_iftable);
8032 // If this is a super_interface method it is possible we shouldn't override it because a
8033 // superclass could have implemented it directly. We get the method the superclass used
8034 // to implement this to know if we can override it with a default method. Doing this is
8035 // safe since we know that the super_iftable is filled in so we can simply pull it from
8036 // there. We don't bother if this is not a super-classes interface since in that case we
8037 // have scanned the entire vtable anyway and would have found it.
8038 // TODO This is rather dirty but it is faster than searching through the entire vtable
8039 // every time.
8040 ArtMethod* supers_method =
8041 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8042 DCHECK(supers_method != nullptr);
8043 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008044 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008045 // The method is not overridable by a default method (i.e. it is directly implemented
8046 // in some class). Therefore move onto the next interface method.
8047 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008048 } else {
8049 // If the super-classes method is override-able by a default method we need to keep
8050 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8051 // 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 -07008052 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8053 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8054 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008055 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008056 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8057 << " and not 'nullptr' or "
8058 << supers_method->PrettyMethod()
8059 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008060 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008061 }
8062 }
8063 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008064 ArtMethod* current_method = helper.FindMethod(interface_method,
8065 interface_name_comparator,
8066 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008067 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008068 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008069 // We could not find an implementation for this method and since it is a brand new
8070 // interface we searched the entire vtable (and all default methods) for an
8071 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008072 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8073 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008074 }
8075
8076 if (current_method != nullptr) {
8077 // We found a default method implementation. Record it in the iftable and IMT.
8078 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8079 SetIMTRef(unimplemented_method,
8080 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008081 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008082 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008083 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008084 }
8085 }
Alex Light705ad492015-09-21 11:36:30 -07008086 } // For each method in interface end.
8087 } // if (num_methods > 0)
8088 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008089 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008090 if (helper.HasNewVirtuals()) {
8091 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8092 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8093 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8094
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008095 // 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 -07008096 // suspension assert.
8097 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008098
Alex Light705ad492015-09-21 11:36:30 -07008099 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008100 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008101 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008102 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008103 return false;
8104 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008105 helper.UpdateIfTable(iftable);
8106 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008107 }
Alex Light705ad492015-09-21 11:36:30 -07008108
Vladimir Marko921094a2017-01-12 18:37:06 +00008109 helper.CheckNoStaleMethodsInDexCache();
8110 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008111 } else {
8112 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008113 }
Alex Light705ad492015-09-21 11:36:30 -07008114 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008115 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008116 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008117 return true;
8118}
8119
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008120bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008121 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008122 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008123}
8124
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008125bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008126 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008127 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008128}
8129
Brian Carlstromdbc05252011-09-09 01:59:59 -07008130struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008131 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008132 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008133 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008134 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008135 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008136 // 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 -07008137 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8138 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008139 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008140 if (type1 == Primitive::kPrimNot) {
8141 // Reference always goes first.
8142 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008143 }
Vladimir Markod5777482014-11-12 17:02:02 +00008144 if (type2 == Primitive::kPrimNot) {
8145 // Reference always goes first.
8146 return false;
8147 }
8148 size_t size1 = Primitive::ComponentSize(type1);
8149 size_t size2 = Primitive::ComponentSize(type2);
8150 if (size1 != size2) {
8151 // Larger primitive types go first.
8152 return size1 > size2;
8153 }
8154 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8155 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008156 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008157 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8158 // by name and for equal names by type id index.
8159 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8160 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008161 }
8162};
8163
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008164bool ClassLinker::LinkFields(Thread* self,
8165 Handle<mirror::Class> klass,
8166 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008167 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008168 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008169 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008170 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8171 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008172
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008173 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008174 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008175 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008176 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008177 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008178 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008179 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008180 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008181 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008182 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008183 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008184 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008185
David Sehr709b0702016-10-13 09:12:37 -07008186 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008187
Brian Carlstromdbc05252011-09-09 01:59:59 -07008188 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008189 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008190 //
8191 // The overall sort order order is:
8192 // 1) All object reference fields, sorted alphabetically.
8193 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8194 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8195 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8196 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8197 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8198 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8199 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8200 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8201 //
8202 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8203 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008204 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008205 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008206 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008207 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008208 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008209 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008210 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8211 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008212
Fred Shih381e4ca2014-08-25 17:24:27 -07008213 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008214 size_t current_field = 0;
8215 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008216 FieldGaps gaps;
8217
Brian Carlstromdbc05252011-09-09 01:59:59 -07008218 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008219 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008220 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008221 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008222 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008223 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008224 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008225 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8226 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008227 MemberOffset old_offset = field_offset;
8228 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8229 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8230 }
Roland Levillain14d90572015-07-16 10:52:26 +01008231 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008232 grouped_and_sorted_fields.pop_front();
8233 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008234 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008235 field_offset = MemberOffset(field_offset.Uint32Value() +
8236 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008237 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008238 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8239 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008240 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8241 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8242 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8243 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008244 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8245 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008246 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008247
Elliott Hughesadb460d2011-10-05 17:02:34 -07008248 // 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 -07008249 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008250 // We know there are no non-reference fields in the Reference classes, and we know
8251 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008252 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008253 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008254 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008255 --num_reference_fields;
8256 }
8257
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008258 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008259 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008260 if (is_static) {
8261 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008262 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008263 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008264 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008265 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008266 if (num_reference_fields == 0 || super_class == nullptr) {
8267 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008268 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008269 if (super_class == nullptr ||
8270 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8271 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008272 }
8273 }
8274 if (kIsDebugBuild) {
8275 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8276 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008277 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008278 while (cur_super != nullptr) {
8279 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8280 cur_super = cur_super->GetSuperClass();
8281 }
8282 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008283 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008284 } else {
8285 // Check that there is at least num_reference_fields other than Object.class.
8286 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008287 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008288 }
8289 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008290 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008291 std::string temp;
8292 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8293 size_t previous_size = klass->GetObjectSize();
8294 if (previous_size != 0) {
8295 // Make sure that we didn't originally have an incorrect size.
8296 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008297 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008298 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008299 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008300 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008301
8302 if (kIsDebugBuild) {
8303 // Make sure that the fields array is ordered by name but all reference
8304 // offsets are at the beginning as far as alignment allows.
8305 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008306 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008307 : klass->GetFirstReferenceInstanceFieldOffset();
8308 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8309 num_reference_fields *
8310 sizeof(mirror::HeapReference<mirror::Object>));
8311 MemberOffset current_ref_offset = start_ref_offset;
8312 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008313 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008314 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008315 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8316 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008317 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008318 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008319 // NOTE: The field names can be the same. This is not possible in the Java language
8320 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008321 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008322 }
8323 Primitive::Type type = field->GetTypeAsPrimitiveType();
8324 bool is_primitive = type != Primitive::kPrimNot;
8325 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8326 strcmp("referent", field->GetName()) == 0) {
8327 is_primitive = true; // We lied above, so we have to expect a lie here.
8328 }
8329 MemberOffset offset = field->GetOffsetDuringLinking();
8330 if (is_primitive) {
8331 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8332 // Shuffled before references.
8333 size_t type_size = Primitive::ComponentSize(type);
8334 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8335 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8336 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8337 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8338 }
8339 } else {
8340 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8341 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8342 sizeof(mirror::HeapReference<mirror::Object>));
8343 }
8344 }
8345 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8346 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008347 return true;
8348}
8349
Vladimir Marko76649e82014-11-10 18:32:59 +00008350// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008351void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008352 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008353 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008354 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008355 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008356 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008357 // Compute reference offsets unless our superclass overflowed.
8358 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8359 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008360 if (num_reference_fields != 0u) {
8361 // All of the fields that contain object references are guaranteed be grouped in memory
8362 // starting at an appropriately aligned address after super class object data.
8363 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8364 sizeof(mirror::HeapReference<mirror::Object>));
8365 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008366 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008367 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008368 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008369 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008370 reference_offsets |= (0xffffffffu << start_bit) &
8371 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008372 }
8373 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008374 }
8375 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008376 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008377}
8378
Vladimir Marko18090d12018-06-01 16:53:12 +01008379ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8380 ObjPtr<mirror::DexCache> dex_cache) {
8381 StackHandleScope<1> hs(Thread::Current());
8382 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8383 return DoResolveString(string_idx, h_dex_cache);
8384}
8385
8386ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8387 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008388 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008389 uint32_t utf16_length;
8390 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008391 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008392 if (string != nullptr) {
8393 dex_cache->SetResolvedString(string_idx, string);
8394 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008395 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008396}
8397
Vladimir Marko18090d12018-06-01 16:53:12 +01008398ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8399 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008400 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008401 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008402 uint32_t utf16_length;
8403 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008404 ObjPtr<mirror::String> string =
8405 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008406 if (string != nullptr) {
8407 dex_cache->SetResolvedString(string_idx, string);
8408 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008409 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008410}
8411
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008412ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008413 ObjPtr<mirror::Class> referrer) {
8414 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8415}
8416
8417ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008418 ObjPtr<mirror::DexCache> dex_cache,
8419 ObjPtr<mirror::ClassLoader> class_loader) {
8420 const DexFile& dex_file = *dex_cache->GetDexFile();
8421 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8422 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8423 ObjPtr<mirror::Class> type = nullptr;
8424 if (descriptor[1] == '\0') {
8425 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8426 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008427 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008428 } else {
8429 Thread* const self = Thread::Current();
8430 DCHECK(self != nullptr);
8431 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8432 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008433 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008434 }
8435 if (type != nullptr) {
8436 if (type->IsResolved()) {
8437 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008438 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008439 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008440 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008441 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008442 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008443}
8444
Andreas Gampe4835d212018-11-21 14:55:10 -08008445template <typename T>
8446ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008447 StackHandleScope<2> hs(Thread::Current());
8448 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8449 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8450 return DoResolveType(type_idx, dex_cache, class_loader);
8451}
8452
Andreas Gampe4835d212018-11-21 14:55:10 -08008453// Instantiate the above.
8454template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8455 ArtField* referrer);
8456template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8457 ArtMethod* referrer);
8458template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8459 ObjPtr<mirror::Class> referrer);
8460
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008461ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008462 Handle<mirror::DexCache> dex_cache,
8463 Handle<mirror::ClassLoader> class_loader) {
8464 Thread* self = Thread::Current();
8465 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8466 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8467 if (resolved != nullptr) {
8468 // TODO: we used to throw here if resolved's class loader was not the
8469 // boot class loader. This was to permit different classes with the
8470 // same name to be loaded simultaneously by different loaders
8471 dex_cache->SetResolvedType(type_idx, resolved);
8472 } else {
8473 CHECK(self->IsExceptionPending())
8474 << "Expected pending exception for failed resolution of: " << descriptor;
8475 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8476 StackHandleScope<1> hs(self);
8477 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008478 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008479 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8480 self->ClearException();
8481 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8482 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008483 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008484 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008485 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008486 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008487 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008488}
8489
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008490ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8491 ObjPtr<mirror::DexCache> dex_cache,
8492 ObjPtr<mirror::ClassLoader> class_loader,
8493 uint32_t method_idx) {
8494 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8495 // functions can optimize the search if the dex_cache is the same as the DexCache
8496 // of the class, with fall-back to name and signature search otherwise.
8497 ArtMethod* resolved = nullptr;
8498 if (klass->IsInterface()) {
8499 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8500 } else {
8501 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8502 }
8503 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008504 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008505 hiddenapi::ShouldDenyAccessToMember(resolved,
8506 hiddenapi::AccessContext(class_loader, dex_cache),
8507 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008508 resolved = nullptr;
8509 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008510 if (resolved != nullptr) {
8511 // In case of jmvti, the dex file gets verified before being registered, so first
8512 // check if it's registered before checking class tables.
8513 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008514 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8515 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008516 << "DexFile referrer: " << dex_file.GetLocation()
8517 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8518 // Be a good citizen and update the dex cache to speed subsequent calls.
8519 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008520 // Disable the following invariant check as the verifier breaks it. b/73760543
8521 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8522 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8523 // << "Method: " << resolved->PrettyMethod() << ", "
8524 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8525 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008526 }
8527 return resolved;
8528}
8529
David Brazdil4525e0b2018-04-05 16:57:32 +01008530// Returns true if `method` is either null or hidden.
8531// Does not print any warnings if it is hidden.
8532static bool CheckNoSuchMethod(ArtMethod* method,
8533 ObjPtr<mirror::DexCache> dex_cache,
8534 ObjPtr<mirror::ClassLoader> class_loader)
8535 REQUIRES_SHARED(Locks::mutator_lock_) {
8536 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008537 hiddenapi::ShouldDenyAccessToMember(method,
8538 hiddenapi::AccessContext(class_loader, dex_cache),
8539 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008540}
8541
8542ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8543 ObjPtr<mirror::DexCache> dex_cache,
8544 ObjPtr<mirror::ClassLoader> class_loader,
8545 uint32_t method_idx) {
8546 if (klass->IsInterface()) {
8547 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8548 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8549 } else {
8550 // If there was an interface method with the same signature, we would have
8551 // found it in the "copied" methods. Only DCHECK that the interface method
8552 // really does not exist.
8553 if (kIsDebugBuild) {
8554 ArtMethod* method =
8555 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8556 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8557 }
8558 return nullptr;
8559 }
8560}
8561
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008562template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008563ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008564 Handle<mirror::DexCache> dex_cache,
8565 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008566 ArtMethod* referrer,
8567 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008568 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008569 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008570 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008571 PointerSize pointer_size = image_pointer_size_;
8572 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008573 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008574 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8575 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008576 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8577 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008578 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008579 return resolved;
8580 }
Vladimir Marko89011192017-12-11 13:45:05 +00008581 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008582 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008583 ObjPtr<mirror::Class> klass = nullptr;
8584 if (valid_dex_cache_method) {
8585 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8586 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008587 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008588 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008589 // We normaly should not end up here. However the verifier currently doesn't guarantee
8590 // the invariant of having the klass in the class table. b/73760543
8591 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008592 }
Vladimir Markoba118822017-06-12 15:41:56 +01008593 } else {
8594 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008595 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008596 if (klass == nullptr) {
8597 DCHECK(Thread::Current()->IsExceptionPending());
8598 return nullptr;
8599 }
8600 }
8601
8602 // Check if the invoke type matches the class type.
8603 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008604 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008605 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008606 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008607 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008608 }
Vladimir Markoba118822017-06-12 15:41:56 +01008609
8610 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008611 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008612 }
Vladimir Markoba118822017-06-12 15:41:56 +01008613
8614 // Note: We can check for IllegalAccessError only if we have a referrer.
8615 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8616 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8617 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8618 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8619 resolved,
8620 dex_cache.Get(),
8621 method_idx,
8622 type)) {
8623 DCHECK(Thread::Current()->IsExceptionPending());
8624 return nullptr;
8625 }
8626 }
8627
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008628 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008629 if (LIKELY(resolved != nullptr) &&
8630 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8631 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008632 return resolved;
8633 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008634 // If we had a method, or if we can find one with another lookup type,
8635 // it's an incompatible-class-change error.
8636 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008637 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008638 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008639 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008640 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008641 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008642 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008643 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8644 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008645 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008646 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008647 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008648 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008649 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008650}
8651
Vladimir Marko89011192017-12-11 13:45:05 +00008652ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008653 Handle<mirror::DexCache> dex_cache,
8654 Handle<mirror::ClassLoader> class_loader) {
8655 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008656 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008657 if (resolved != nullptr) {
8658 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008659 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8660 return resolved;
8661 }
8662 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008663 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008664 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008665 if (klass == nullptr) {
8666 Thread::Current()->AssertPendingException();
8667 return nullptr;
8668 }
8669 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008670 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8671 } else {
8672 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008673 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008674 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008675 hiddenapi::ShouldDenyAccessToMember(
8676 resolved,
8677 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8678 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008679 resolved = nullptr;
8680 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008681 return resolved;
8682}
8683
Vladimir Markof44d36c2017-03-14 14:18:46 +00008684ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8685 ObjPtr<mirror::DexCache> dex_cache,
8686 ObjPtr<mirror::ClassLoader> class_loader,
8687 bool is_static) {
8688 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008689 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008690 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8691 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008692 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008693 }
8694 if (klass == nullptr) {
8695 // The class has not been resolved yet, so the field is also unresolved.
8696 return nullptr;
8697 }
8698 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008699
David Brazdil1ab0fa82018-05-04 11:28:03 +01008700 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008701}
8702
Vladimir Markoe11dd502017-12-08 14:09:45 +00008703ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008704 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008705 Handle<mirror::ClassLoader> class_loader,
8706 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008707 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008708 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008709 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008710 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008711 return resolved;
8712 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008713 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008714 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008715 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008716 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008717 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008718 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008719 }
8720
David Brazdil1ab0fa82018-05-04 11:28:03 +01008721 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008722 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008723 const char* name = dex_file.GetFieldName(field_id);
8724 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008725 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008726 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008727 return resolved;
8728}
8729
Vladimir Markoe11dd502017-12-08 14:09:45 +00008730ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008731 Handle<mirror::DexCache> dex_cache,
8732 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008733 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008734 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008735 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008736 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008737 return resolved;
8738 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008739 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008740 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008741 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008742 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008743 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008744 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008745 }
8746
David Brazdil1ab0fa82018-05-04 11:28:03 +01008747 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8748 if (resolved == nullptr) {
8749 const char* name = dex_file.GetFieldName(field_id);
8750 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008751 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008752 }
8753 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008754}
8755
David Brazdil1ab0fa82018-05-04 11:28:03 +01008756ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8757 ObjPtr<mirror::DexCache> dex_cache,
8758 ObjPtr<mirror::ClassLoader> class_loader,
8759 uint32_t field_idx,
8760 bool is_static) {
8761 ArtField* resolved = nullptr;
8762 Thread* self = is_static ? Thread::Current() : nullptr;
8763 const DexFile& dex_file = *dex_cache->GetDexFile();
8764
8765 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8766 : klass->FindInstanceField(dex_cache, field_idx);
8767
8768 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008769 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008770 const char* name = dex_file.GetFieldName(field_id);
8771 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8772 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8773 : klass->FindInstanceField(name, type);
8774 }
8775
8776 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008777 hiddenapi::ShouldDenyAccessToMember(resolved,
8778 hiddenapi::AccessContext(class_loader, dex_cache),
8779 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008780 resolved = nullptr;
8781 }
8782
8783 if (resolved != nullptr) {
8784 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8785 }
8786
8787 return resolved;
8788}
8789
8790ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8791 ObjPtr<mirror::DexCache> dex_cache,
8792 ObjPtr<mirror::ClassLoader> class_loader,
8793 uint32_t field_idx) {
8794 ArtField* resolved = nullptr;
8795 Thread* self = Thread::Current();
8796 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008797 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008798
8799 const char* name = dex_file.GetFieldName(field_id);
8800 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8801 resolved = mirror::Class::FindField(self, klass, name, type);
8802
8803 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008804 hiddenapi::ShouldDenyAccessToMember(resolved,
8805 hiddenapi::AccessContext(class_loader, dex_cache),
8806 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008807 resolved = nullptr;
8808 }
8809
8810 if (resolved != nullptr) {
8811 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8812 }
8813
8814 return resolved;
8815}
8816
Vladimir Markoaf940202017-12-08 15:01:18 +00008817ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8818 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008819 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008820 Handle<mirror::DexCache> dex_cache,
8821 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008822 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008823 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008824
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008825 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008826 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008827 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008828 }
8829
Narayan Kamath25352fc2016-08-03 12:46:58 +01008830 StackHandleScope<4> hs(self);
8831
8832 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008833 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008834 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008835 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008836 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008837 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008838 DCHECK(self->IsExceptionPending());
8839 return nullptr;
8840 }
8841
8842 // Then resolve the argument types.
8843 //
8844 // TODO: Is there a better way to figure out the number of method arguments
8845 // other than by looking at the shorty ?
8846 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8847
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008848 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008849 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8850 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008851 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008852 DCHECK(self->IsExceptionPending());
8853 return nullptr;
8854 }
8855
8856 DexFileParameterIterator it(dex_file, proto_id);
8857 int32_t i = 0;
8858 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8859 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008860 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008861 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008862 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008863 DCHECK(self->IsExceptionPending());
8864 return nullptr;
8865 }
8866
8867 method_params->Set(i++, param_class.Get());
8868 }
8869
8870 DCHECK(!it.HasNext());
8871
8872 Handle<mirror::MethodType> type = hs.NewHandle(
8873 mirror::MethodType::Create(self, return_type, method_params));
8874 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8875
8876 return type.Get();
8877}
8878
Vladimir Markoaf940202017-12-08 15:01:18 +00008879ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008880 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008881 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008882 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008883 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8884 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008885 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008886}
8887
Vladimir Marko5aead702019-03-27 11:00:36 +00008888ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008889 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008890 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008891 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008892 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008893 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8894 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008895 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008896 bool is_static;
8897 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008898 switch (handle_type) {
8899 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008900 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008901 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008902 is_static = true;
8903 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008904 break;
8905 }
8906 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008907 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008908 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008909 is_static = true;
8910 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008911 break;
8912 }
8913 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008914 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008915 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008916 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008917 num_params = 2;
8918 break;
8919 }
8920 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008921 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008922 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008923 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008924 num_params = 1;
8925 break;
8926 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008927 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008928 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008929 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008930 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008931 case DexFile::MethodHandleType::kInvokeInterface:
8932 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008933 }
8934
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008935 ArtField* target_field =
8936 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8937 if (LIKELY(target_field != nullptr)) {
8938 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8939 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8940 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8941 ThrowIllegalAccessErrorField(referring_class, target_field);
8942 return nullptr;
8943 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008944 if (UNLIKELY(is_put && target_field->IsFinal())) {
8945 ThrowIllegalAccessErrorField(referring_class, target_field);
8946 return nullptr;
8947 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008948 } else {
8949 DCHECK(Thread::Current()->IsExceptionPending());
8950 return nullptr;
8951 }
8952
8953 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008954 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008955 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8956 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008957 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008958 DCHECK(self->IsExceptionPending());
8959 return nullptr;
8960 }
8961
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008962 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008963 Handle<mirror::Class> return_type;
8964 switch (handle_type) {
8965 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008966 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008967 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008968 break;
8969 }
8970 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008971 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008972 break;
8973 }
8974 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008975 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008976 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008977 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008978 break;
8979 }
8980 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008981 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008982 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008983 break;
8984 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008985 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008986 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008987 case DexFile::MethodHandleType::kInvokeConstructor:
8988 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008989 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008990 UNREACHABLE();
8991 }
8992
8993 for (int32_t i = 0; i < num_params; ++i) {
8994 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8995 DCHECK(self->IsExceptionPending());
8996 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008997 }
8998 }
8999
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009000 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009001 DCHECK(self->IsExceptionPending());
9002 return nullptr;
9003 }
9004
9005 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009006 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9007 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009008 DCHECK(self->IsExceptionPending());
9009 return nullptr;
9010 }
Orion Hodson631827d2017-04-10 14:53:47 +01009011
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009012 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9013 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9014}
9015
Vladimir Marko5aead702019-03-27 11:00:36 +00009016ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009017 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009018 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009019 ArtMethod* referrer) {
9020 DexFile::MethodHandleType handle_type =
9021 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9022 mirror::MethodHandle::Kind kind;
9023 uint32_t receiver_count = 0;
9024 ArtMethod* target_method = nullptr;
9025 switch (handle_type) {
9026 case DexFile::MethodHandleType::kStaticPut:
9027 case DexFile::MethodHandleType::kStaticGet:
9028 case DexFile::MethodHandleType::kInstancePut:
9029 case DexFile::MethodHandleType::kInstanceGet:
9030 UNREACHABLE();
9031 case DexFile::MethodHandleType::kInvokeStatic: {
9032 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9033 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009034 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9035 method_handle.field_or_method_idx_,
9036 referrer,
9037 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009038 break;
9039 }
9040 case DexFile::MethodHandleType::kInvokeInstance: {
9041 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9042 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009043 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9044 method_handle.field_or_method_idx_,
9045 referrer,
9046 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009047 break;
9048 }
9049 case DexFile::MethodHandleType::kInvokeConstructor: {
9050 // Constructors are currently implemented as a transform. They
9051 // are special cased later in this method.
9052 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9053 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009054 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9055 method_handle.field_or_method_idx_,
9056 referrer,
9057 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009058 break;
9059 }
9060 case DexFile::MethodHandleType::kInvokeDirect: {
9061 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9062 receiver_count = 1;
9063 StackHandleScope<2> hs(self);
9064 // A constant method handle with type kInvokeDirect can refer to
9065 // a method that is private or to a method in a super class. To
9066 // disambiguate the two options, we resolve the method ignoring
9067 // the invocation type to determine if the method is private. We
9068 // then resolve again specifying the intended invocation type to
9069 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009070 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009071 hs.NewHandle(referrer->GetDexCache()),
9072 hs.NewHandle(referrer->GetClassLoader()));
9073 if (UNLIKELY(target_method == nullptr)) {
9074 break;
9075 }
9076
9077 if (target_method->IsPrivate()) {
9078 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009079 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9080 method_handle.field_or_method_idx_,
9081 referrer,
9082 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009083 } else {
9084 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009085 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9086 method_handle.field_or_method_idx_,
9087 referrer,
9088 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009089 if (UNLIKELY(target_method == nullptr)) {
9090 break;
9091 }
9092 // Find the method specified in the parent in referring class
9093 // so invoke-super invokes the method in the parent of the
9094 // referrer.
9095 target_method =
9096 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9097 kRuntimePointerSize);
9098 }
9099 break;
9100 }
9101 case DexFile::MethodHandleType::kInvokeInterface: {
9102 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9103 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009104 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9105 method_handle.field_or_method_idx_,
9106 referrer,
9107 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009108 break;
9109 }
Orion Hodson631827d2017-04-10 14:53:47 +01009110 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009111
9112 if (UNLIKELY(target_method == nullptr)) {
9113 DCHECK(Thread::Current()->IsExceptionPending());
9114 return nullptr;
9115 }
9116
9117 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9118 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9119 uint32_t access_flags = target_method->GetAccessFlags();
9120 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9121 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9122 return nullptr;
9123 }
9124
9125 // Calculate the number of parameters from the method shorty. We add the
9126 // receiver count (0 or 1) and deduct one for the return value.
9127 uint32_t shorty_length;
9128 target_method->GetShorty(&shorty_length);
9129 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9130
Orion Hodsonecd58562018-09-24 11:27:33 +01009131 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009132 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009133 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9134 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9135 if (method_params.Get() == nullptr) {
9136 DCHECK(self->IsExceptionPending());
9137 return nullptr;
9138 }
9139
Orion Hodsonecd58562018-09-24 11:27:33 +01009140 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009141 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009142 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009143 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009144 // Insert receiver. Use the class identified in the method handle rather than the declaring
9145 // class of the resolved method which may be super class or default interface method
9146 // (b/115964401).
9147 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9148 // receiver_class should have been resolved when resolving the target method.
9149 DCHECK(receiver_class != nullptr);
9150 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009151 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009152
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009153 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009154 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009155 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009156 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009157 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009158 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009159 if (nullptr == klass) {
9160 DCHECK(self->IsExceptionPending());
9161 return nullptr;
9162 }
9163 method_params->Set(index++, klass);
9164 it.Next();
9165 }
9166
Orion Hodsonecd58562018-09-24 11:27:33 +01009167 Handle<mirror::Class> return_type =
9168 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009169 if (UNLIKELY(return_type.IsNull())) {
9170 DCHECK(self->IsExceptionPending());
9171 return nullptr;
9172 }
9173
9174 Handle<mirror::MethodType>
9175 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9176 if (UNLIKELY(method_type.IsNull())) {
9177 DCHECK(self->IsExceptionPending());
9178 return nullptr;
9179 }
9180
9181 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9182 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9183 Handle<mirror::MethodHandlesLookup> lookup =
9184 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9185 return lookup->FindConstructor(self, constructor_class, method_type);
9186 }
9187
9188 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9189 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9190}
9191
Vladimir Markoaf940202017-12-08 15:01:18 +00009192ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9193 uint32_t method_handle_idx,
9194 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009195 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009196 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009197 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009198 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9199 case DexFile::MethodHandleType::kStaticPut:
9200 case DexFile::MethodHandleType::kStaticGet:
9201 case DexFile::MethodHandleType::kInstancePut:
9202 case DexFile::MethodHandleType::kInstanceGet:
9203 return ResolveMethodHandleForField(self, method_handle, referrer);
9204 case DexFile::MethodHandleType::kInvokeStatic:
9205 case DexFile::MethodHandleType::kInvokeInstance:
9206 case DexFile::MethodHandleType::kInvokeConstructor:
9207 case DexFile::MethodHandleType::kInvokeDirect:
9208 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009209 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009210 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009211}
9212
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009213bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9214 return (entry_point == GetQuickResolutionStub()) ||
9215 (quick_resolution_trampoline_ == entry_point);
9216}
9217
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009218bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9219 return (entry_point == GetQuickToInterpreterBridge()) ||
9220 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9221}
9222
9223bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9224 return (entry_point == GetQuickGenericJniStub()) ||
9225 (quick_generic_jni_trampoline_ == entry_point);
9226}
9227
David Sehra49e0532017-08-25 08:05:29 -07009228bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9229 return entry_point == GetJniDlsymLookupStub();
9230}
9231
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009232const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9233 return GetQuickGenericJniStub();
9234}
9235
Mathieu Chartiere401d142015-04-22 13:56:20 -07009236void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009237 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009238 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9239 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009240 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009241 }
9242}
9243
Alex Lightdb01a092017-04-03 15:39:55 -07009244void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9245 DCHECK(method->IsObsolete());
9246 // We cannot mess with the entrypoints of native methods because they are used to determine how
9247 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9248 if (!method->IsNative()) {
9249 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9250 }
9251}
9252
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009253void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009254 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009255 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009256 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9257 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009258 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9259 os << "Dumping registered class loaders\n";
9260 size_t class_loader_index = 0;
9261 for (const ClassLoaderData& class_loader : class_loaders_) {
9262 ObjPtr<mirror::ClassLoader> loader =
9263 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9264 if (loader != nullptr) {
9265 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9266 bool saw_one_dex_file = false;
9267 for (const DexCacheData& dex_cache : dex_caches_) {
9268 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9269 if (saw_one_dex_file) {
9270 os << ":";
9271 }
9272 saw_one_dex_file = true;
9273 os << dex_cache.dex_file->GetLocation();
9274 }
9275 }
9276 os << "]";
9277 bool found_parent = false;
9278 if (loader->GetParent() != nullptr) {
9279 size_t parent_index = 0;
9280 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9281 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9282 soa.Self()->DecodeJObject(class_loader2.weak_root));
9283 if (loader2 == loader->GetParent()) {
9284 os << ", parent #" << parent_index;
9285 found_parent = true;
9286 break;
9287 }
9288 parent_index++;
9289 }
9290 if (!found_parent) {
9291 os << ", unregistered parent of type "
9292 << loader->GetParent()->GetClass()->PrettyDescriptor();
9293 }
9294 } else {
9295 os << ", no parent";
9296 }
9297 os << "\n";
9298 }
9299 }
9300 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009301}
9302
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009303class CountClassesVisitor : public ClassLoaderVisitor {
9304 public:
9305 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9306
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009307 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009308 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009309 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009310 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009311 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9312 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009313 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009314 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009315
9316 size_t num_zygote_classes;
9317 size_t num_non_zygote_classes;
9318};
9319
9320size_t ClassLinker::NumZygoteClasses() const {
9321 CountClassesVisitor visitor;
9322 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009323 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009324}
9325
9326size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009327 CountClassesVisitor visitor;
9328 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009329 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009330}
9331
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009332size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009333 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009334 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009335 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009336}
9337
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009338pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009339 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009340}
9341
9342pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009343 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009344}
9345
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009346void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009347 DCHECK(!init_done_);
9348
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009349 DCHECK(klass != nullptr);
9350 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009351
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009352 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009353 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009354 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9355 int32_t index = static_cast<int32_t>(class_root);
9356 DCHECK(class_roots->Get(index) == nullptr);
9357 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009358}
9359
Roland Levillain0e840272018-08-23 19:55:30 +01009360void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9361 ObjPtr<mirror::Class> java_lang_Class,
9362 ClassRoot primitive_array_class_root,
9363 ClassRoot primitive_class_root,
9364 const char* descriptor) {
9365 StackHandleScope<1> hs(self);
9366 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9367 AllocPrimitiveArrayClass(self, java_lang_Class)));
9368 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9369 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9370 CheckSystemClass(self, primitive_array_class, descriptor);
9371}
9372
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009373ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9374 Thread* self,
9375 const std::vector<const DexFile*>& dex_files,
9376 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009377 Handle<mirror::ClassLoader> parent_loader,
9378 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009379
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009380 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009381
Mathieu Chartierc7853442015-03-27 14:35:38 -07009382 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009383 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009384
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009385 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009386 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009387 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009388 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009389 mirror::ObjectArray<mirror::Object>::Alloc(self,
9390 dex_elements_class.Get(),
9391 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009392 Handle<mirror::Class> h_dex_element_class =
9393 hs.NewHandle(dex_elements_class->GetComponentType());
9394
Mathieu Chartierc7853442015-03-27 14:35:38 -07009395 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009396 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009397 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009398
Andreas Gampe08883de2016-11-08 13:20:52 -08009399 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009400 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009401
Andreas Gampe08883de2016-11-08 13:20:52 -08009402 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009403 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009404
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009405 // Fill the elements array.
9406 int32_t index = 0;
9407 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009408 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009409
Calin Juravle7865ac72017-06-28 11:03:12 -07009410 // CreateWellKnownClassLoader is only used by gtests and compiler.
9411 // 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 -07009412 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9413 self,
9414 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009415 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009416 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009417
Mathieu Chartier3738e982017-05-12 16:07:28 -07009418 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9419 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009420 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009421 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009422 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009423 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009424
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009425 Handle<mirror::String> h_file_name = hs2.NewHandle(
9426 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009427 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009428 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9429
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009430 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009431 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009432 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009433
9434 h_dex_elements->Set(index, h_element.Get());
9435 index++;
9436 }
9437 DCHECK_EQ(index, h_dex_elements->GetLength());
9438
9439 // Create DexPathList.
9440 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009441 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009442 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009443 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009444 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009445 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9446 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9447 // elements.
9448 {
9449 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9450 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9451 DCHECK(native_lib_dirs != nullptr);
9452 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9453 DCHECK(list_class != nullptr);
9454 {
9455 StackHandleScope<1> h_list_scope(self);
9456 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9457 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9458 DCHECK(list_init);
9459 list_class = h_list_class.Get();
9460 }
9461 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9462 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9463 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9464 // normally never null), as long as one does not try to add elements, this will still
9465 // work.
9466 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9467 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009468
Calin Juravle7865ac72017-06-28 11:03:12 -07009469 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009470 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9471 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009472 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009473 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009474 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009475 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009476 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009477 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009478
9479 // Make a pretend boot-classpath.
9480 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009481 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009482 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009483 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009484 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009485 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009486 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009487 if (parent_loader.Get() == nullptr) {
9488 ScopedObjectAccessUnchecked soa(self);
9489 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9490 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9491 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9492 } else {
9493 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9494 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009495
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009496 ArtField* shared_libraries_field =
9497 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9498 DCHECK(shared_libraries_field != nullptr);
9499 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9500
9501 return h_class_loader.Get();
9502}
9503
9504jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9505 const std::vector<const DexFile*>& dex_files,
9506 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009507 jobject parent_loader,
9508 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009509 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9510 WellKnownClasses::dalvik_system_PathClassLoader) ||
9511 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009512 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9513 self->GetJniEnv()->IsSameObject(loader_class,
9514 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009515
9516 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9517 // We could move the jobject to the callers, but all call-sites do this...
9518 ScopedObjectAccessUnchecked soa(self);
9519
9520 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009521 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009522
9523 Handle<mirror::Class> h_loader_class =
9524 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009525 Handle<mirror::ClassLoader> h_parent =
9526 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9527 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9528 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009529
9530 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9531 self,
9532 dex_files,
9533 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009534 h_parent,
9535 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009536
9537 // Make it a global ref and return.
9538 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009539 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009540 return soa.Env()->NewGlobalRef(local_ref.get());
9541}
9542
Calin Juravle7865ac72017-06-28 11:03:12 -07009543jobject ClassLinker::CreatePathClassLoader(Thread* self,
9544 const std::vector<const DexFile*>& dex_files) {
9545 return CreateWellKnownClassLoader(self,
9546 dex_files,
9547 WellKnownClasses::dalvik_system_PathClassLoader,
9548 nullptr);
9549}
9550
Andreas Gampe8ac75952015-06-02 21:01:45 -07009551void ClassLinker::DropFindArrayClassCache() {
9552 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9553 find_array_class_cache_next_victim_ = 0;
9554}
9555
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009556void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009557 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009558 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009559 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009560 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9561 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009562 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009563 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009564 }
9565 }
9566}
9567
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009568void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9569 for (const ClassLoaderData& data : class_loaders_) {
9570 LinearAlloc* alloc = data.allocator;
9571 if (alloc != nullptr && !visitor->Visit(alloc)) {
9572 break;
9573 }
9574 }
9575}
9576
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009577void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9578 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009579 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009580 Thread* const self = Thread::Current();
9581 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009582 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009583 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009584 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009585 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9586 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009587 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009588 }
9589}
9590
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009591void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009592 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009593 std::vector<ClassLoaderData> to_delete;
9594 // Do the delete outside the lock to avoid lock violation in jit code cache.
9595 {
9596 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9597 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9598 const ClassLoaderData& data = *it;
9599 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009600 ObjPtr<mirror::ClassLoader> class_loader =
9601 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009602 if (class_loader != nullptr) {
9603 ++it;
9604 } else {
9605 VLOG(class_linker) << "Freeing class loader";
9606 to_delete.push_back(data);
9607 it = class_loaders_.erase(it);
9608 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009609 }
9610 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009611 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009612 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009613 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009614 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009615}
9616
Vladimir Marko21300532017-01-24 18:06:55 +00009617class GetResolvedClassesVisitor : public ClassVisitor {
9618 public:
9619 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9620 : result_(result),
9621 ignore_boot_classes_(ignore_boot_classes),
9622 last_resolved_classes_(result->end()),
9623 last_dex_file_(nullptr),
9624 vlog_is_on_(VLOG_IS_ON(class_linker)),
9625 extra_stats_(),
9626 last_extra_stats_(extra_stats_.end()) { }
9627
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009628 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009629 if (!klass->IsProxyClass() &&
9630 !klass->IsArrayClass() &&
9631 klass->IsResolved() &&
9632 !klass->IsErroneousResolved() &&
9633 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9634 const DexFile& dex_file = klass->GetDexFile();
9635 if (&dex_file != last_dex_file_) {
9636 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009637 DexCacheResolvedClasses resolved_classes(
9638 dex_file.GetLocation(),
9639 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9640 dex_file.GetLocationChecksum(),
9641 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009642 last_resolved_classes_ = result_->find(resolved_classes);
9643 if (last_resolved_classes_ == result_->end()) {
9644 last_resolved_classes_ = result_->insert(resolved_classes).first;
9645 }
9646 }
9647 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9648 if (UNLIKELY(vlog_is_on_) && added) {
9649 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9650 if (last_extra_stats_ == extra_stats_.end() ||
9651 last_extra_stats_->first != resolved_classes) {
9652 last_extra_stats_ = extra_stats_.find(resolved_classes);
9653 if (last_extra_stats_ == extra_stats_.end()) {
9654 last_extra_stats_ =
9655 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9656 }
9657 }
9658 }
9659 }
9660 return true;
9661 }
9662
9663 void PrintStatistics() const {
9664 if (vlog_is_on_) {
9665 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9666 auto it = extra_stats_.find(std::addressof(resolved_classes));
9667 DCHECK(it != extra_stats_.end());
9668 const ExtraStats& extra_stats = it->second;
9669 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9670 << " has " << resolved_classes.GetClasses().size() << " / "
9671 << extra_stats.number_of_class_defs_ << " resolved classes";
9672 }
9673 }
9674 }
9675
9676 private:
9677 struct ExtraStats {
9678 explicit ExtraStats(uint32_t number_of_class_defs)
9679 : number_of_class_defs_(number_of_class_defs) {}
9680 uint32_t number_of_class_defs_;
9681 };
9682
9683 std::set<DexCacheResolvedClasses>* result_;
9684 bool ignore_boot_classes_;
9685 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9686 const DexFile* last_dex_file_;
9687
9688 // Statistics.
9689 bool vlog_is_on_;
9690 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9691 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9692};
9693
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009694std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009695 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009696 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009697 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009698 std::set<DexCacheResolvedClasses> ret;
9699 VLOG(class_linker) << "Collecting resolved classes";
9700 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009701 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9702 VisitClasses(&visitor);
9703 if (VLOG_IS_ON(class_linker)) {
9704 visitor.PrintStatistics();
9705 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009706 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009707 return ret;
9708}
9709
Mathieu Chartier65975772016-08-05 10:46:36 -07009710class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9711 public:
9712 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9713 : method_(method),
9714 pointer_size_(pointer_size) {}
9715
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009716 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009717 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9718 holder_ = klass;
9719 }
9720 // Return false to stop searching if holder_ is not null.
9721 return holder_ == nullptr;
9722 }
9723
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009724 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009725 const ArtMethod* const method_;
9726 const PointerSize pointer_size_;
9727};
9728
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009729ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009730 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9731 CHECK(method->IsCopied());
9732 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9733 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009734 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009735}
9736
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009737ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9738 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009739 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009740 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009741 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009742}
9743
Roland Levillain0e840272018-08-23 19:55:30 +01009744// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009745template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009746 uint32_t method_idx,
9747 Handle<mirror::DexCache> dex_cache,
9748 Handle<mirror::ClassLoader> class_loader,
9749 ArtMethod* referrer,
9750 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009751template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009752 uint32_t method_idx,
9753 Handle<mirror::DexCache> dex_cache,
9754 Handle<mirror::ClassLoader> class_loader,
9755 ArtMethod* referrer,
9756 InvokeType type);
9757
Roland Levillain0e840272018-08-23 19:55:30 +01009758// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009759template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009760 Thread* self,
9761 ObjPtr<mirror::Class> java_lang_Class,
9762 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009763template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009764 Thread* self,
9765 ObjPtr<mirror::Class> java_lang_Class,
9766 uint32_t class_size);
9767
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009768} // namespace art