blob: 6fdac3f71425512d3fd23793fe08226feb2a1db6 [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"
Orion Hodson005ac512017-10-24 15:43:43 +0100120#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700121#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700122#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700123#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700124#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700125#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700126#include "oat_file_assistant.h"
127#include "oat_file_manager.h"
128#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700129#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700130#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800131#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700132#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700133#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700134#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700135#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100136#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700137#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700138#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700139
140namespace art {
141
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800142using android::base::StringPrintf;
143
Mathieu Chartierc7853442015-03-27 14:35:38 -0700144static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700145static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700146
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700147static void ThrowNoClassDefFoundError(const char* fmt, ...)
148 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700149 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700150static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700151 va_list args;
152 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800153 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000154 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800155 va_end(args);
156}
157
Andreas Gampe99babb62015-11-02 16:20:00 -0800158static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700159 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700160 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700161 StackHandleScope<1> hs(self);
162 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700163 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700164 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700165
166 if (exception_class == nullptr) {
167 // No exc class ~ no <init>-with-string.
168 CHECK(self->IsExceptionPending());
169 self->ClearException();
170 return false;
171 }
172
Vladimir Markoba118822017-06-12 15:41:56 +0100173 ArtMethod* exception_init_method = exception_class->FindConstructor(
174 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700175 return exception_init_method != nullptr;
176}
177
Vladimir Markobb206de2019-03-28 10:30:32 +0000178static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700179 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700180 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
181 if (ext == nullptr) {
182 return nullptr;
183 } else {
184 return ext->GetVerifyError();
185 }
186}
187
188// Helper for ThrowEarlierClassFailure. Throws the stored error.
189static void HandleEarlierVerifyError(Thread* self,
190 ClassLinker* class_linker,
191 ObjPtr<mirror::Class> c)
192 REQUIRES_SHARED(Locks::mutator_lock_) {
193 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800194 DCHECK(obj != nullptr);
195 self->AssertNoPendingException();
196 if (obj->IsClass()) {
197 // Previous error has been stored as class. Create a new exception of that type.
198
199 // It's possible the exception doesn't have a <init>(String).
200 std::string temp;
201 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
202
203 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700204 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800205 } else {
206 self->ThrowNewException(descriptor, nullptr);
207 }
208 } else {
209 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100210 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700211 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800212 CHECK(throwable_class->IsAssignableFrom(error_class));
213 self->SetException(obj->AsThrowable());
214 }
215 self->AssertPendingException();
216}
217
Andreas Gampe5b20b352018-10-11 19:03:20 -0700218// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
219// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
220// before.
221template <bool kNeedsVerified = false>
222static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
223 REQUIRES_SHARED(Locks::mutator_lock_) {
224 if (kNeedsVerified) {
225 // To not fail access-flags access checks, push a minimal state.
226 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
227 }
228 if (!klass->WasVerificationAttempted()) {
229 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
230 klass->SetVerificationAttempted();
231 }
232}
233
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800234void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
235 bool wrap_in_no_class_def,
236 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700237 // The class failed to initialize on a previous attempt, so we want to throw
238 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
239 // failed in verification, in which case v2 5.4.1 says we need to re-throw
240 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800241 Runtime* const runtime = Runtime::Current();
242 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700243 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000244 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
245 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800246 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700247 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800248 } else {
249 extra = verify_error->AsThrowable()->Dump();
250 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700251 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800252 if (log) {
253 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
254 << ": " << extra;
255 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700256 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700257
David Sehr709b0702016-10-13 09:12:37 -0700258 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800259 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800260 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700261 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700262 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000263 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700264 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000265 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
266 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800267 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800268 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800269 }
Alex Lightd6251582016-10-31 11:12:30 -0700270 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
271 // might have meant to go down the earlier if statement with the original error but it got
272 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000273 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800274 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
275 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
276 // exception will be a cause.
277 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700278 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700279 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700280 }
281}
282
Brian Carlstromb23eab12014-10-08 17:55:21 -0700283static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700284 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700285 if (VLOG_IS_ON(class_linker)) {
286 std::string temp;
287 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000288 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700289 }
290}
291
292static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700293 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700294 Thread* self = Thread::Current();
295 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700296
297 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700298 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700299
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800300 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
301 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
302 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800303 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800304 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
305 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
306 // could have caused the error.
307 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
308 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
309 << " failed initialization: "
310 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800311 }
312
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700313 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700314 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
315 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700316
Elliott Hughesa4f94742012-05-29 16:28:38 -0700317 // We only wrap non-Error exceptions; an Error can just be used as-is.
318 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000319 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700320 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700321 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700322}
323
Fred Shih381e4ca2014-08-25 17:24:27 -0700324// Gap between two fields in object layout.
325struct FieldGap {
326 uint32_t start_offset; // The offset from the start of the object.
327 uint32_t size; // The gap size of 1, 2, or 4 bytes.
328};
329struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800330 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700331 }
332 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
333 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800334 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700335 // Note that the priority queue returns the largest element, so operator()
336 // should return true if lhs is less than rhs.
337 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700338 }
339};
Andreas Gampec55bb392018-09-21 00:02:02 +0000340using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700341
342// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800343static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700344 DCHECK(gaps != nullptr);
345
346 uint32_t current_offset = gap_start;
347 while (current_offset != gap_end) {
348 size_t remaining = gap_end - current_offset;
349 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
350 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
351 current_offset += sizeof(uint32_t);
352 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
353 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
354 current_offset += sizeof(uint16_t);
355 } else {
356 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
357 current_offset += sizeof(uint8_t);
358 }
359 DCHECK_LE(current_offset, gap_end) << "Overran gap";
360 }
361}
362// Shuffle fields forward, making use of gaps whenever possible.
363template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000364static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700365 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700366 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700367 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700368 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700369 DCHECK(current_field_idx != nullptr);
370 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700371 DCHECK(gaps != nullptr);
372 DCHECK(field_offset != nullptr);
373
374 DCHECK(IsPowerOfTwo(n));
375 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700376 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700377 Primitive::Type type = field->GetTypeAsPrimitiveType();
378 if (Primitive::ComponentSize(type) < n) {
379 break;
380 }
381 if (!IsAligned<n>(field_offset->Uint32Value())) {
382 MemberOffset old_offset = *field_offset;
383 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
384 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
385 }
David Sehr709b0702016-10-13 09:12:37 -0700386 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700387 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700388 if (!gaps->empty() && gaps->top().size >= n) {
389 FieldGap gap = gaps->top();
390 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100391 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700392 field->SetOffset(MemberOffset(gap.start_offset));
393 if (gap.size > n) {
394 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
395 }
396 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100397 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700398 field->SetOffset(*field_offset);
399 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
400 }
401 ++(*current_field_idx);
402 }
403}
404
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800405ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700406 : boot_class_table_(new ClassTable()),
407 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800408 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800409 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700410 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000411 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700412 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800413 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800414 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100415 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800416 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700417 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700418 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
419 // For CHA disabled during Aot, see b/34193647.
420
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700421 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700422 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
423 "Array cache size wrong.");
424 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700425}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700426
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800427void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700428 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800429 if (c2 == nullptr) {
430 LOG(FATAL) << "Could not find class " << descriptor;
431 UNREACHABLE();
432 }
433 if (c1.Get() != c2) {
434 std::ostringstream os1, os2;
435 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
436 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
437 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
438 << ". This is most likely the result of a broken build. Make sure that "
439 << "libcore and art projects match.\n\n"
440 << os1.str() << "\n\n" << os2.str();
441 UNREACHABLE();
442 }
443}
444
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800445bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
446 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800447 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700448
Mathieu Chartiere401d142015-04-22 13:56:20 -0700449 Thread* const self = Thread::Current();
450 Runtime* const runtime = Runtime::Current();
451 gc::Heap* const heap = runtime->GetHeap();
452
Jeff Haodcdc85b2015-12-04 14:06:18 -0800453 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700454 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700455
Mathieu Chartiere401d142015-04-22 13:56:20 -0700456 // Use the pointer size from the runtime since we are probably creating the image.
457 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
458
Elliott Hughes30646832011-10-13 16:59:46 -0700459 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700460 // 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 -0800461 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700462 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700463 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700464 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
465 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000466 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
467 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800468 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100469 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700470 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700471 if (kUseBakerReadBarrier) {
472 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800473 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700474 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700475 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800476 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700477 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700478
Elliott Hughes418d20f2011-09-22 14:00:39 -0700479 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700481 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700482 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700484
Ian Rogers23435d02012-09-24 11:23:12 -0700485 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700486 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700487 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800488 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700489 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700490 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000491 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700492
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700493 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800494 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
495 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
496 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
497 java_lang_Object.Get(),
498 java_lang_Object->GetObjectSize(),
499 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700500
Igor Murashkin86083f72017-10-27 10:59:04 -0700501 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000502 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700503 // It might seem the lock here is unnecessary, however all the SubtypeCheck
504 // functions are annotated to require locks all the way down.
505 //
506 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
507 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000508 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
509 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700510 }
511
Ian Rogers23435d02012-09-24 11:23:12 -0700512 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700513 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700514 AllocClass(self, java_lang_Class.Get(),
515 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700516 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700517
Roland Levillain0e840272018-08-23 19:55:30 +0100518 // Setup java.lang.String.
519 //
520 // We make this class non-movable for the unlikely case where it were to be
521 // moved by a sticky-bit (minor) collection when using the Generational
522 // Concurrent Copying (CC) collector, potentially creating a stale reference
523 // in the `klass_` field of one of its instances allocated in the Large-Object
524 // Space (LOS) -- see the comment about the dirty card scanning logic in
525 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700526 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700527 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100528 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700529 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000530 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400531
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700532 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700533 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700534 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700535 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000536 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700537
Ian Rogers23435d02012-09-24 11:23:12 -0700538 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700539 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100540 mirror::ObjectArray<mirror::Class>::Alloc(self,
541 object_array_class.Get(),
542 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700543 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100544 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
545 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
546 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
547 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100548 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
549 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550
Mathieu Chartier6beced42016-11-15 15:51:31 -0800551 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
552 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
553
Vladimir Marko02610552018-06-04 14:38:00 +0100554 // Create array interface entries to populate once we can load system classes.
555 object_array_class->SetIfTable(AllocIfTable(self, 2));
556 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
557
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100559 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
560 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100561 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100562 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
563 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
564 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
565 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
566 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
567 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568
Vladimir Markoacb906d2018-05-30 10:23:49 +0100569 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700570 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100571 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100572 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100573 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700574
Vladimir Markoacb906d2018-05-30 10:23:49 +0100575 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700576 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100577 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100578 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100579 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700580
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700581 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700582
Ian Rogers52813c92012-10-11 11:50:38 -0700583 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700584 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700585 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100586 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100587 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700588 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000589 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700590
Alex Lightd6251582016-10-31 11:12:30 -0700591
592 // Setup dalvik.system.ClassExt
593 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
594 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100595 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000596 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700597
Mathieu Chartier66f19252012-09-18 08:57:04 -0700598 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700599 Handle<mirror::Class> object_array_string(hs.NewHandle(
600 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700601 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700602 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100603 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700604
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000605 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700606 // Create runtime resolution and imt conflict methods.
607 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000608 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
609 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700610
Ian Rogers23435d02012-09-24 11:23:12 -0700611 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
612 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
613 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800614 if (boot_class_path.empty()) {
615 *error_msg = "Boot classpath is empty.";
616 return false;
617 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800618 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800619 if (dex_file.get() == nullptr) {
620 *error_msg = "Null dex file.";
621 return false;
622 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700623 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800624 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700625 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626
627 // now we can use FindSystemClass
628
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700629 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
630 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700631 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800632 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700633 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700634 quick_resolution_trampoline_ = GetQuickResolutionStub();
635 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
636 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700637 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700638
Alex Lightd6251582016-10-31 11:12:30 -0700639 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000640 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800641 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700642 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000643 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800644 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000645 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800646 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700647 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000648 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700649 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
650 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700651
Ian Rogers23435d02012-09-24 11:23:12 -0700652 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100653 AllocAndSetPrimitiveArrayClassRoot(self,
654 java_lang_Class.Get(),
655 ClassRoot::kBooleanArrayClass,
656 ClassRoot::kPrimitiveBoolean,
657 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700658
Roland Levillain0e840272018-08-23 19:55:30 +0100659 AllocAndSetPrimitiveArrayClassRoot(
660 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661
Roland Levillain0e840272018-08-23 19:55:30 +0100662 AllocAndSetPrimitiveArrayClassRoot(
663 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700664
Roland Levillain0e840272018-08-23 19:55:30 +0100665 AllocAndSetPrimitiveArrayClassRoot(
666 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800668 CheckSystemClass(self, int_array_class, "[I");
669 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700670
Roland Levillain0e840272018-08-23 19:55:30 +0100671 AllocAndSetPrimitiveArrayClassRoot(
672 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700673
Roland Levillain0e840272018-08-23 19:55:30 +0100674 AllocAndSetPrimitiveArrayClassRoot(
675 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700676
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800677 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
678 // in class_table_.
679 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700680
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800681 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
682 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700683
Ian Rogers23435d02012-09-24 11:23:12 -0700684 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700685 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800686 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700687 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800688 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700689 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
690 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100691 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
692 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700693
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700694 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
695 // suspension.
696 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000697 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700698 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000699 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700700 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000701 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700702 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000703 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700704
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700705 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100706 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700707
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800708 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700709
Ian Rogers23435d02012-09-24 11:23:12 -0700710 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100711 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
712 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700713
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700714 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100715 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700716 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100717 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700718
719 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700720 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
721 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100722 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700723
724 // Create java.lang.reflect.Constructor.class root and array root.
725 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
726 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100727 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700728 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
729 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100730 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700731
732 // Create java.lang.reflect.Method.class root and array root.
733 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
734 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100735 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700736 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
737 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100738 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700739
Orion Hodson005ac512017-10-24 15:43:43 +0100740 // Create java.lang.invoke.CallSite.class root
741 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
742 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100743 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100744
Narayan Kamathafa48272016-08-03 12:46:58 +0100745 // Create java.lang.invoke.MethodType.class root
746 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
747 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100748 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100749
750 // Create java.lang.invoke.MethodHandleImpl.class root
751 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
752 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100753 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100754 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100755
Orion Hodsonc069a302017-01-18 09:23:12 +0000756 // Create java.lang.invoke.MethodHandles.Lookup.class root
757 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
758 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100759 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000760
Orion Hodson005ac512017-10-24 15:43:43 +0100761 // Create java.lang.invoke.VarHandle.class root
762 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000763 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100764 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100765
766 // Create java.lang.invoke.FieldVarHandle.class root
767 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
768 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100769 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100770
771 // Create java.lang.invoke.ArrayElementVarHandle.class root
772 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
773 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100774 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100775
776 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
777 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
778 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100779 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100780
781 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
782 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
783 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100784 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000785
Narayan Kamath000e1882016-10-24 17:14:25 +0100786 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
787 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100788 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100789
Brian Carlstrom1f870082011-08-23 16:02:11 -0700790 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700791 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000792 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800793 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700794 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700795 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
796 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700797 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700798 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700799 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700800 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700801 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700802 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700803 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700804 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700805 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700806 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700807 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700808 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700809
Ian Rogers23435d02012-09-24 11:23:12 -0700810 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700811 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700812 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700813 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100814 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700815
jeffhao8cd6dda2012-02-22 10:15:34 -0800816 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700817 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100818 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700820 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100821 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
822 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
823 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700824 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000825 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
826 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700827
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700828 // Create conflict tables that depend on the class linker.
829 runtime->FixupConflictTables();
830
Ian Rogers98379392014-02-24 16:53:16 -0800831 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700832
Brian Carlstroma004aa92012-02-08 18:05:09 -0800833 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800834
835 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700836}
837
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700838static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
839 REQUIRES_SHARED(Locks::mutator_lock_) {
840 // Find String.<init> -> StringFactory bindings.
841 ObjPtr<mirror::Class> string_factory_class =
842 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
843 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100844 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700845 WellKnownClasses::InitStringInit(string_class, string_factory_class);
846 // Update the primordial thread.
847 self->InitStringEntryPoints();
848}
849
Ian Rogers98379392014-02-24 16:53:16 -0800850void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800851 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700852
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700853 CreateStringInitBindings(self, this);
854
Brian Carlstrom16192862011-09-12 17:50:06 -0700855 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700856 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700857 // as the types of the field can't be resolved prior to the runtime being
858 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700859 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100860 Handle<mirror::Class> java_lang_ref_Reference =
861 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700862 Handle<mirror::Class> java_lang_ref_FinalizerReference =
863 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800864
Mathieu Chartierc7853442015-03-27 14:35:38 -0700865 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700866 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
867 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700868
Mathieu Chartierc7853442015-03-27 14:35:38 -0700869 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700870 CHECK_STREQ(queue->GetName(), "queue");
871 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700872
Mathieu Chartierc7853442015-03-27 14:35:38 -0700873 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700874 CHECK_STREQ(queueNext->GetName(), "queueNext");
875 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700876
Mathieu Chartierc7853442015-03-27 14:35:38 -0700877 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700878 CHECK_STREQ(referent->GetName(), "referent");
879 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700880
Mathieu Chartierc7853442015-03-27 14:35:38 -0700881 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700882 CHECK_STREQ(zombie->GetName(), "zombie");
883 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700884
Brian Carlstroma663ea52011-08-19 23:33:41 -0700885 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100886 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700887 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700888 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700889 CHECK(klass != nullptr);
890 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700891 // note SetClassRoot does additional validation.
892 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700893 }
894
Vladimir Marko02610552018-06-04 14:38:00 +0100895 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700896
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700897 // disable the slow paths in FindClass and CreatePrimitiveClass now
898 // that Object, Class, and Object[] are setup
899 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700900
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700901 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
902 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
903 // ensure that the class will be initialized.
904 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700905 verifier::ClassVerifier::Init(); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700906
907 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
908 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
909 // Strange, but don't crash.
910 LOG(WARNING) << "Could not prepare StackOverflowError.";
911 self->ClearException();
912 }
913 }
914
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800915 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700916}
917
Vladimir Markodcfcce42018-06-27 10:00:28 +0000918void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100919 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
920 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700921 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700922 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100923 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700924 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700925 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000926 } else {
927 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700928 }
929 }
930}
931
Jeff Haodcdc85b2015-12-04 14:06:18 -0800932struct TrampolineCheckData {
933 const void* quick_resolution_trampoline;
934 const void* quick_imt_conflict_trampoline;
935 const void* quick_generic_jni_trampoline;
936 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700937 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800938 ArtMethod* m;
939 bool error;
940};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800941
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800942bool ClassLinker::InitFromBootImage(std::string* error_msg) {
943 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700944 CHECK(!init_done_);
945
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700946 Runtime* const runtime = Runtime::Current();
947 Thread* const self = Thread::Current();
948 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800949 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
950 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700951 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
952 if (!ValidPointerSize(pointer_size_unchecked)) {
953 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800954 return false;
955 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000956 const ImageHeader& image_header = spaces[0]->GetImageHeader();
957 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800958 if (!runtime->IsAotCompiler()) {
959 // Only the Aot compiler supports having an image with a different pointer size than the
960 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
961 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700962 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800963 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700964 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800965 sizeof(void*));
966 return false;
967 }
968 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000969 DCHECK(!runtime->HasResolutionMethod());
970 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
971 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
972 runtime->SetImtUnimplementedMethod(
973 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
974 runtime->SetCalleeSaveMethod(
975 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
976 CalleeSaveType::kSaveAllCalleeSaves);
977 runtime->SetCalleeSaveMethod(
978 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
979 CalleeSaveType::kSaveRefsOnly);
980 runtime->SetCalleeSaveMethod(
981 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
982 CalleeSaveType::kSaveRefsAndArgs);
983 runtime->SetCalleeSaveMethod(
984 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
985 CalleeSaveType::kSaveEverything);
986 runtime->SetCalleeSaveMethod(
987 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
988 CalleeSaveType::kSaveEverythingForClinit);
989 runtime->SetCalleeSaveMethod(
990 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
991 CalleeSaveType::kSaveEverythingForSuspendCheck);
992
Jeff Haodcdc85b2015-12-04 14:06:18 -0800993 std::vector<const OatFile*> oat_files =
994 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
995 DCHECK(!oat_files.empty());
996 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800997 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
998 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
999 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1000 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1001 if (kIsDebugBuild) {
1002 // Check that the other images use the same trampoline.
1003 for (size_t i = 1; i < oat_files.size(); ++i) {
1004 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1005 const void* ith_quick_resolution_trampoline =
1006 ith_oat_header.GetQuickResolutionTrampoline();
1007 const void* ith_quick_imt_conflict_trampoline =
1008 ith_oat_header.GetQuickImtConflictTrampoline();
1009 const void* ith_quick_generic_jni_trampoline =
1010 ith_oat_header.GetQuickGenericJniTrampoline();
1011 const void* ith_quick_to_interpreter_bridge_trampoline =
1012 ith_oat_header.GetQuickToInterpreterBridge();
1013 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1014 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1015 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1016 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1017 // Make sure that all methods in this image do not contain those trampolines as
1018 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1019 TrampolineCheckData data;
1020 data.error = false;
1021 data.pointer_size = GetImagePointerSize();
1022 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1023 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1024 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1025 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1026 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001027 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1028 if (obj->IsClass()) {
1029 ObjPtr<mirror::Class> klass = obj->AsClass();
1030 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1031 const void* entrypoint =
1032 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1033 if (entrypoint == data.quick_resolution_trampoline ||
1034 entrypoint == data.quick_imt_conflict_trampoline ||
1035 entrypoint == data.quick_generic_jni_trampoline ||
1036 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1037 data.m = &m;
1038 data.error = true;
1039 return;
1040 }
1041 }
1042 }
1043 };
1044 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001045 if (data.error) {
1046 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001047 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001048 *error_msg = "Found an ArtMethod with a bad entrypoint";
1049 return false;
1050 }
1051 }
1052 }
1053 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001054
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001055 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001056 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
1057 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001058 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001059
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001060 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001061 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001062 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1063 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001064 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1065 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001066
Vladimir Marko4433c432018-12-04 14:57:47 +00001067 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1068 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001069 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001070 // Boot class loader, use a null handle.
1071 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001072 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001073 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001074 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001075 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001076 /*out*/&dex_files,
1077 error_msg)) {
1078 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001079 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001080 // Append opened dex files at the end.
1081 boot_dex_files_.insert(boot_dex_files_.end(),
1082 std::make_move_iterator(dex_files.begin()),
1083 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001084 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001085 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1086 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1087 }
Ian Rogers98379392014-02-24 16:53:16 -08001088 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001089
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001090 VLOG(startup) << __FUNCTION__ << " exiting";
1091 return true;
1092}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001093
Vladimir Marko4433c432018-12-04 14:57:47 +00001094void ClassLinker::AddExtraBootDexFiles(
1095 Thread* self,
1096 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1097 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1098 AppendToBootClassPath(self, *dex_file);
1099 boot_dex_files_.push_back(std::move(dex_file));
1100 }
1101}
1102
Jeff Hao5872d7c2016-04-27 11:07:41 -07001103bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001104 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001105 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001106 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1107 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001108}
1109
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001110static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1111 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001112 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001113 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001114 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001115 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001116 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 DCHECK(dex_file_field != nullptr);
1118 DCHECK(dex_file_name_field != nullptr);
1119 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001120 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001121 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001123 // Null dex file means it was probably a jar with no dex files, return a null string.
1124 *out_name = nullptr;
1125 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001127 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001129 *out_name = name_object->AsString();
1130 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001131 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001132 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001133}
1134
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001135static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1136 ObjPtr<mirror::ClassLoader> class_loader,
1137 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1138 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001139 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001140 StackHandleScope<1> hs(soa.Self());
1141 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001142 // Get element names. Sets error to true on failure.
1143 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1144 REQUIRES_SHARED(Locks::mutator_lock_) {
1145 if (element == nullptr) {
1146 *error_msg = "Null dex element";
1147 *error = true; // Null element is a critical error.
1148 return false; // Had an error, stop the visit.
1149 }
1150 ObjPtr<mirror::String> name;
1151 if (!GetDexPathListElementName(element, &name)) {
1152 *error_msg = "Invalid dex path list element";
1153 *error = true; // Invalid element, make it a critical error.
1154 return false; // Stop the visit.
1155 }
1156 if (name != nullptr) {
1157 dex_files->push_front(name);
1158 }
1159 return true; // Continue with the next Element.
1160 };
1161 bool error = VisitClassLoaderDexElements(soa,
1162 handle,
1163 add_element_names,
1164 /*defaultReturn=*/ false);
1165 return !error;
1166}
1167
1168static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1169 ObjPtr<mirror::ClassLoader> image_class_loader,
1170 ObjPtr<mirror::ClassLoader> class_loader,
1171 std::string* error_msg)
1172 REQUIRES_SHARED(Locks::mutator_lock_) {
1173 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1174 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1175 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001176 return false;
1177 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001178 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1179 *error_msg = "Hierarchies don't match";
1180 return false;
1181 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1182 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1183 image_class_loader->PrettyTypeOf().c_str(),
1184 class_loader->PrettyTypeOf().c_str());
1185 return false;
1186 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1187 class_loader->GetClass()) {
1188 *error_msg = StringPrintf("Unknown class loader type %s",
1189 class_loader->PrettyTypeOf().c_str());
1190 // Unsupported class loader.
1191 return false;
1192 }
1193 return true;
1194}
1195
1196static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1197 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1198 std::string* error_msg)
1199 REQUIRES_SHARED(Locks::mutator_lock_) {
1200 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1201 std::equal(image_dex_files.begin(),
1202 image_dex_files.end(),
1203 loader_dex_files.begin(),
1204 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1205 REQUIRES_SHARED(Locks::mutator_lock_) {
1206 return lhs->Equals(rhs);
1207 });
1208 if (!equal) {
1209 VLOG(image) << "Image dex files " << image_dex_files.size();
1210 for (ObjPtr<mirror::String> name : image_dex_files) {
1211 VLOG(image) << name->ToModifiedUtf8();
1212 }
1213 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1214 for (ObjPtr<mirror::String> name : loader_dex_files) {
1215 VLOG(image) << name->ToModifiedUtf8();
1216 }
1217 *error_msg = "Mismatch in dex files";
1218 }
1219 return equal;
1220}
1221
1222static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1223 ObjPtr<mirror::ClassLoader> image_class_loader,
1224 ObjPtr<mirror::ClassLoader> class_loader,
1225 bool check_dex_file_names,
1226 std::string* error_msg)
1227 REQUIRES_SHARED(Locks::mutator_lock_) {
1228 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1229 return false;
1230 }
1231
1232 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1233 // No need to check further.
1234 return true;
1235 }
1236
1237 if (check_dex_file_names) {
1238 std::list<ObjPtr<mirror::String>> image_dex_files;
1239 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001240 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001241 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001242
1243 std::list<ObjPtr<mirror::String>> loader_dex_files;
1244 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1245 return false;
1246 }
1247
1248 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1249 return false;
1250 }
1251 }
1252
1253 ArtField* field =
1254 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1255 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1256 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1257 if (shared_libraries_image_loader == nullptr) {
1258 if (shared_libraries_loader != nullptr) {
1259 *error_msg = "Mismatch in shared libraries";
1260 return false;
1261 }
1262 } else if (shared_libraries_loader == nullptr) {
1263 *error_msg = "Mismatch in shared libraries";
1264 return false;
1265 } else {
1266 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1267 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1268 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1269 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1270 if (array1->GetLength() != array2->GetLength()) {
1271 *error_msg = "Mismatch in number of shared libraries";
1272 return false;
1273 }
1274
1275 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1276 // Do a full comparison of the class loaders, including comparing their dex files.
1277 if (!CompareClassLoaders(soa,
1278 array1->Get(i),
1279 array2->Get(i),
1280 /*check_dex_file_names=*/ true,
1281 error_msg)) {
1282 return false;
1283 }
1284 }
1285 }
1286
1287 // Do a full comparison of the class loaders, including comparing their dex files.
1288 if (!CompareClassLoaders(soa,
1289 image_class_loader->GetParent(),
1290 class_loader->GetParent(),
1291 /*check_dex_file_names=*/ true,
1292 error_msg)) {
1293 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001294 }
1295 return true;
1296}
1297
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001298class CHAOnDeleteUpdateClassVisitor {
1299 public:
1300 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1301 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1302 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1303 self_(Thread::Current()) {}
1304
1305 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1306 // This class is going to be unloaded. Tell CHA about it.
1307 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1308 return true;
1309 }
1310 private:
1311 const LinearAlloc* allocator_;
1312 const ClassHierarchyAnalysis* cha_;
1313 const PointerSize pointer_size_;
1314 const Thread* self_;
1315};
1316
Chris Wailes0c61be42018-09-26 17:27:34 -07001317/*
1318 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001319 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001320 */
1321class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001322 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001323 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001324 space_(space),
1325 intern_table_(*Runtime::Current()->GetInternTable()) {}
1326
Chris Wailes0c61be42018-09-26 17:27:34 -07001327 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001328 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001329 if (referred_obj != nullptr &&
1330 space_.HasAddress(referred_obj.Ptr()) &&
1331 referred_obj->IsString()) {
1332 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001333
1334 if (kIsDebugBuild) {
1335 // Saved to temporary variables to aid in debugging.
1336 ObjPtr<mirror::String> strong_lookup_result =
1337 intern_table_.LookupStrong(Thread::Current(), referred_str);
1338 ObjPtr<mirror::String> weak_lookup_result =
1339 intern_table_.LookupWeak(Thread::Current(), referred_str);
1340
1341 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1342 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001343 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001344 }
1345
Chris Wailes0c61be42018-09-26 17:27:34 -07001346 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001347 mirror::CompressedReference<mirror::Object>* root) const
1348 REQUIRES_SHARED(Locks::mutator_lock_) {
1349 if (!root->IsNull()) {
1350 VisitRoot(root);
1351 }
1352 }
1353
Chris Wailes0c61be42018-09-26 17:27:34 -07001354 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001355 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001356 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001357 }
1358
1359 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001360 void operator()(ObjPtr<mirror::Object> obj,
1361 MemberOffset offset,
1362 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001363 REQUIRES_SHARED(Locks::mutator_lock_) {
1364 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1365 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1366 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1367 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001368 ObjPtr<mirror::Object> referred_obj =
1369 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1370
1371 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001372 }
1373 }
1374
1375 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1376 ObjPtr<mirror::Reference> ref) const
1377 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001378 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001379 }
1380
Chris Wailes0c61be42018-09-26 17:27:34 -07001381 const gc::space::ImageSpace& space_;
1382 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001383};
1384
Chris Wailes0c61be42018-09-26 17:27:34 -07001385/*
1386 * This function verifies that string references in the AppImage have been
1387 * properly interned. To be considered properly interned a reference must
1388 * point to the same version of the string that the intern table does.
1389 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001390void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001391 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1392 const ImageHeader& image_header = space.GetImageHeader();
1393 const uint8_t* target_base = space.GetMemMap()->Begin();
1394 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001395
1396 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1397 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001398
1399 VerifyStringInterningVisitor visitor(space);
1400 bitmap->VisitMarkedRange(objects_begin,
1401 objects_end,
1402 [&space, &visitor](mirror::Object* obj)
1403 REQUIRES_SHARED(Locks::mutator_lock_) {
1404 if (space.HasAddress(obj)) {
1405 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001406 obj->VisitReferences</* kVisitNativeRoots= */ true,
1407 kVerifyNone,
1408 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001409 } else {
1410 // Don't visit native roots for non-dex-cache as they can't contain
1411 // native references to strings. This is verified during compilation
1412 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001413 obj->VisitReferences</* kVisitNativeRoots= */ false,
1414 kVerifyNone,
1415 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001416 }
1417 }
1418 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001419}
1420
Andreas Gampe2af99022017-04-25 08:32:59 -07001421// new_class_set is the set of classes that were read from the class table section in the image.
1422// If there was no class table section, it is null.
1423// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001424class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001425 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001426 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001427 ClassLinker* class_linker,
1428 gc::space::ImageSpace* space,
1429 Handle<mirror::ClassLoader> class_loader,
1430 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001431 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001432 REQUIRES(!Locks::dex_lock_)
1433 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001434
Chris Wailesfbeef462018-10-19 14:16:35 -07001435 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001436 REQUIRES_SHARED(Locks::mutator_lock_);
1437
1438 static void UpdateInternStrings(
1439 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001440 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001441 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1442 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001443};
1444
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001445void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001446 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001447 gc::space::ImageSpace* space,
1448 Handle<mirror::ClassLoader> class_loader,
1449 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001450 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001451 REQUIRES(!Locks::dex_lock_)
1452 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001453 ScopedTrace app_image_timing("AppImage:Updating");
1454
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001455 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001456 Runtime* const runtime = Runtime::Current();
1457 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001458 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001459 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001460 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001461 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001462 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001463 const size_t num_dex_caches = dex_caches->GetLength();
1464 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001465 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001466 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001467 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001468 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001469 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1470 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001471 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001472
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001473 if (!load_app_image_startup_cache) {
1474 dex_cache->ClearPreResolvedStrings();
1475 }
1476
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001477 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001478 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001479 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001480 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001481 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001482 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001483 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001484
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001485 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001486 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001487 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001488 DCHECK(it != new_class_set->end());
1489 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001490 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001491
Vladimir Marko1a1de672016-10-13 12:53:15 +01001492 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001493 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001494 DCHECK(it2 != new_class_set->end());
1495 DCHECK_EQ(it2->Read(), super_class);
1496 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001497
Vladimir Marko1a1de672016-10-13 12:53:15 +01001498 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1499 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001500 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1501 if (!class_linker->IsQuickResolutionStub(code) &&
1502 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001503 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001504 !m.IsNative()) {
1505 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001506 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001507 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001508
Vladimir Marko1a1de672016-10-13 12:53:15 +01001509 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1510 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001511 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1512 if (!class_linker->IsQuickResolutionStub(code) &&
1513 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001514 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001515 !m.IsNative()) {
1516 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001517 }
1518 }
1519 }
1520 }
1521 }
1522 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001523 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001524
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001525 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001526 HandleAppImageStrings(space);
1527
1528 if (kIsDebugBuild) {
1529 VerifyStringInterning(*space);
1530 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001531 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001532
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001533 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001534 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001535 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001536 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1537 header.VisitPackedArtMethods([&](ArtMethod& method)
1538 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1539 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1540 if (klass != nullptr) {
1541 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1542 }
1543 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001544 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001545}
1546
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001547void AppImageLoadingHelper::UpdateInternStrings(
1548 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001549 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001550 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1551 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001552 const ImageSection& sro_section =
1553 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1554 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001555 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001556
1557 VLOG(image)
1558 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1559 << num_string_offsets;
1560
Chris Wailesfbeef462018-10-19 14:16:35 -07001561 const auto* sro_base =
1562 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001563
1564 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001565 uint32_t base_offset = sro_base[offset_index].first;
1566
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001567 if (HasDexCacheStringNativeRefTag(base_offset)) {
1568 base_offset = ClearDexCacheNativeRefTags(base_offset);
1569 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001570
1571 ObjPtr<mirror::DexCache> dex_cache =
1572 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1573 uint32_t string_index = sro_base[offset_index].second;
1574
1575 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1576 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001577 DCHECK(referred_string != nullptr);
1578
Chris Wailesfbeef462018-10-19 14:16:35 -07001579 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001580 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001581 // This doesn't use SetResolvedString to maintain consistency with how
1582 // we load the string. The index from the source string must be
1583 // re-used due to the circular nature of the cache. Because we are not
1584 // using a helper function we need to mark the GC card manually.
1585 WriteBarrier::ForEveryFieldWrite(dex_cache);
1586 dex_cache->GetStrings()[string_index].store(
1587 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001588 } else if (!use_preresolved_strings) {
1589 dex_cache->GetStrings()[string_index].store(
1590 mirror::StringDexCachePair(intern_table->InternStrong(referred_string), source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001591 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001592 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001593 if (use_preresolved_strings) {
1594 base_offset = ClearDexCacheNativeRefTags(base_offset);
1595 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001596
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001597 ObjPtr<mirror::DexCache> dex_cache =
1598 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1599 uint32_t string_index = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001600
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001601 ObjPtr<mirror::String> referred_string =
1602 dex_cache->GetPreResolvedStrings()[string_index].Read();
1603 DCHECK(referred_string != nullptr);
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001604
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001605 auto it = intern_remap.find(referred_string.Ptr());
1606 if (it != intern_remap.end()) {
1607 // Because we are not using a helper function we need to mark the GC card manually.
1608 WriteBarrier::ForEveryFieldWrite(dex_cache);
1609 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1610 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001611 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001612 } else {
1613 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001614 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001615 DCHECK_ALIGNED(raw_member_offset, 2);
1616
1617 ObjPtr<mirror::Object> obj_ptr =
1618 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1619 MemberOffset member_offset(raw_member_offset);
1620 ObjPtr<mirror::String> referred_string =
1621 obj_ptr->GetFieldObject<mirror::String,
1622 kVerifyNone,
1623 kWithoutReadBarrier,
1624 /* kIsVolatile= */ false>(member_offset);
1625 DCHECK(referred_string != nullptr);
1626
1627 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001628 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001629 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1630 /* kCheckTransaction= */ false,
1631 kVerifyNone,
1632 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001633 } else if (!use_preresolved_strings) {
1634 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1635 /* kCheckTransaction= */ false,
1636 kVerifyNone,
1637 /* kIsVolatile= */ false>(
1638 member_offset,
1639 intern_table->InternStrong(referred_string));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001640 }
1641 }
1642 }
1643}
1644
Chris Wailesfbeef462018-10-19 14:16:35 -07001645void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001646 // Iterate over the string reference offsets stored in the image and intern
1647 // the strings they point to.
1648 ScopedTrace timing("AppImage:InternString");
1649
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001650 Runtime* const runtime = Runtime::Current();
1651 InternTable* const intern_table = runtime->GetInternTable();
1652
1653 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001654
1655 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1656 // for faster lookup.
1657 // TODO: Optimize with a bitmap or bloom filter
1658 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001659 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001660 REQUIRES_SHARED(Locks::mutator_lock_)
1661 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001662 const size_t non_boot_image_strings = intern_table->CountInterns(
1663 /*visit_boot_images=*/false,
1664 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001665 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001666 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1667 // Visit the smaller of the two sets to compute the intersection.
1668 if (interns.size() < non_boot_image_strings) {
1669 for (auto it = interns.begin(); it != interns.end(); ) {
1670 ObjPtr<mirror::String> string = it->Read();
1671 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1672 if (existing == nullptr) {
1673 existing = intern_table->LookupStrongLocked(string);
1674 }
1675 if (existing != nullptr) {
1676 intern_remap.Put(string.Ptr(), existing.Ptr());
1677 it = interns.erase(it);
1678 } else {
1679 ++it;
1680 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001681 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001682 } else {
1683 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1684 REQUIRES_SHARED(Locks::mutator_lock_)
1685 REQUIRES(Locks::intern_table_lock_) {
1686 auto it = interns.find(root);
1687 if (it != interns.end()) {
1688 ObjPtr<mirror::String> existing = root.Read();
1689 intern_remap.Put(it->Read(), existing.Ptr());
1690 it = interns.erase(it);
1691 }
1692 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1693 }
1694 // Sanity check to ensure correctness.
1695 if (kIsDebugBuild) {
1696 for (GcRoot<mirror::String>& root : interns) {
1697 ObjPtr<mirror::String> string = root.Read();
1698 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1699 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001700 }
1701 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001702 };
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001703
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001704 bool update_intern_strings;
1705 if (load_startup_cache) {
Mathieu Chartiere23b3882019-02-14 07:35:43 -08001706 VLOG(image) << "AppImage:load_startup_cache";
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001707 // Only add the intern table if we are using the startup cache. Otherwise,
1708 // UpdateInternStrings adds the strings to the intern table.
1709 intern_table->AddImageStringsToTable(space, func);
1710 update_intern_strings = kIsDebugBuild || !intern_remap.empty();
1711 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
1712 } else {
1713 update_intern_strings = true;
1714 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001715
1716 // For debug builds, always run the code below to get coverage.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001717 if (update_intern_strings) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001718 // Slow path case is when there are conflicting intern strings to fix up.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001719 UpdateInternStrings(space, /*use_preresolved_strings=*/ load_startup_cache, intern_remap);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001720 }
1721}
1722
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001723static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1724 const char* location,
1725 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001726 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001727 DCHECK(error_msg != nullptr);
1728 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001729 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001730 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001731 return std::unique_ptr<const DexFile>();
1732 }
1733 std::string inner_error_msg;
1734 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1735 if (dex_file == nullptr) {
1736 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1737 location,
1738 oat_file->GetLocation().c_str(),
1739 inner_error_msg.c_str());
1740 return std::unique_ptr<const DexFile>();
1741 }
1742
1743 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1744 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1745 location,
1746 dex_file->GetLocationChecksum(),
1747 oat_dex_file->GetDexFileLocationChecksum());
1748 return std::unique_ptr<const DexFile>();
1749 }
1750 return dex_file;
1751}
1752
1753bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1754 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1755 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001756 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001757 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001758 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001759 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001760 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001761 dex_caches_object->AsObjectArray<mirror::DexCache>();
1762 const OatFile* oat_file = space->GetOatFile();
Vladimir Marko4617d582019-03-28 13:48:31 +00001763 for (int32_t i = 0, length = dex_caches->GetLength(); i != length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001764 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001765 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1766 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1767 dex_file_location.c_str(),
1768 error_msg);
1769 if (dex_file == nullptr) {
1770 return false;
1771 }
1772 dex_cache->SetDexFile(dex_file.get());
1773 out_dex_files->push_back(std::move(dex_file));
1774 }
1775 return true;
1776}
1777
Andreas Gampe0793bec2016-12-01 11:37:33 -08001778// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1779// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001780class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001781 public:
1782 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1783 REQUIRES_SHARED(Locks::mutator_lock_) {
1784 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001785 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1786 DCHECK(obj != nullptr);
1787 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1788 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1789 if (obj->IsClass()) {
1790 auto klass = obj->AsClass();
1791 for (ArtField& field : klass->GetIFields()) {
1792 CHECK_EQ(field.GetDeclaringClass(), klass);
1793 }
1794 for (ArtField& field : klass->GetSFields()) {
1795 CHECK_EQ(field.GetDeclaringClass(), klass);
1796 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001797 const PointerSize pointer_size = isc.pointer_size_;
1798 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001799 isc.SanityCheckArtMethod(&m, klass);
1800 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001801 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001802 if (vtable != nullptr) {
1803 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1804 }
1805 if (klass->ShouldHaveImt()) {
1806 ImTable* imt = klass->GetImt(pointer_size);
1807 for (size_t i = 0; i < ImTable::kSize; ++i) {
1808 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1809 }
1810 }
1811 if (klass->ShouldHaveEmbeddedVTable()) {
1812 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1813 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1814 }
1815 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001816 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001817 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1818 if (iftable->GetMethodArrayCount(i) > 0) {
1819 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1820 }
1821 }
1822 }
1823 };
1824 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001825 }
1826
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001827 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1828 ClassLinker* class_linker,
1829 mirror::MethodDexCacheType* arr,
1830 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001831 REQUIRES_SHARED(Locks::mutator_lock_) {
1832 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001833 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001834 }
1835
Andreas Gampe0793bec2016-12-01 11:37:33 -08001836 private:
1837 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1838 : spaces_(heap->GetBootImageSpaces()),
1839 pointer_size_(class_linker->GetImagePointerSize()) {
1840 space_begin_.reserve(spaces_.size());
1841 method_sections_.reserve(spaces_.size());
1842 runtime_method_sections_.reserve(spaces_.size());
1843 for (gc::space::ImageSpace* space : spaces_) {
1844 space_begin_.push_back(space->Begin());
1845 auto& header = space->GetImageHeader();
1846 method_sections_.push_back(&header.GetMethodsSection());
1847 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1848 }
1849 }
1850
1851 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1852 REQUIRES_SHARED(Locks::mutator_lock_) {
1853 if (m->IsRuntimeMethod()) {
1854 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1855 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1856 } else if (m->IsCopied()) {
1857 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1858 } else if (expected_class != nullptr) {
1859 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1860 }
1861 if (!spaces_.empty()) {
1862 bool contains = false;
1863 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1864 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1865 contains = method_sections_[i]->Contains(offset) ||
1866 runtime_method_sections_[i]->Contains(offset);
1867 }
1868 CHECK(contains) << m << " not found";
1869 }
1870 }
1871
1872 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1873 ObjPtr<mirror::Class> expected_class)
1874 REQUIRES_SHARED(Locks::mutator_lock_) {
1875 CHECK(arr != nullptr);
1876 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1877 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1878 // expected_class == null means we are a dex cache.
1879 if (expected_class != nullptr) {
1880 CHECK(method != nullptr);
1881 }
1882 if (method != nullptr) {
1883 SanityCheckArtMethod(method, expected_class);
1884 }
1885 }
1886 }
1887
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001888 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001889 REQUIRES_SHARED(Locks::mutator_lock_) {
1890 CHECK_EQ(arr != nullptr, size != 0u);
1891 if (arr != nullptr) {
1892 bool contains = false;
1893 for (auto space : spaces_) {
1894 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001895 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001896 contains = true;
1897 break;
1898 }
1899 }
1900 CHECK(contains);
1901 }
1902 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001903 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1904 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001905 // expected_class == null means we are a dex cache.
1906 if (method != nullptr) {
1907 SanityCheckArtMethod(method, nullptr);
1908 }
1909 }
1910 }
1911
1912 const std::vector<gc::space::ImageSpace*>& spaces_;
1913 const PointerSize pointer_size_;
1914
1915 // Cached sections from the spaces.
1916 std::vector<const uint8_t*> space_begin_;
1917 std::vector<const ImageSection*> method_sections_;
1918 std::vector<const ImageSection*> runtime_method_sections_;
1919};
1920
Andreas Gampebe7af222017-07-25 09:57:28 -07001921static void VerifyAppImage(const ImageHeader& header,
1922 const Handle<mirror::ClassLoader>& class_loader,
1923 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1924 ClassTable* class_table, gc::space::ImageSpace* space)
1925 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001926 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1927 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1928 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1929 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1930 << mirror::Class::PrettyClass(klass);
1931 }
1932 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001933 {
1934 // Verify that all direct interfaces of classes in the class table are also resolved.
1935 std::vector<ObjPtr<mirror::Class>> classes;
1936 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1937 REQUIRES_SHARED(Locks::mutator_lock_) {
1938 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1939 classes.push_back(klass);
1940 }
1941 return true;
1942 };
1943 class_table->Visit(verify_direct_interfaces_in_table);
1944 Thread* self = Thread::Current();
1945 for (ObjPtr<mirror::Class> klass : classes) {
1946 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1947 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1948 << klass->PrettyDescriptor() << " iface #" << i;
1949 }
1950 }
1951 }
1952 // Check that all non-primitive classes in dex caches are also in the class table.
1953 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1954 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1955 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1956 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1957 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1958 if (klass != nullptr && !klass->IsPrimitive()) {
1959 CHECK(class_table->Contains(klass))
1960 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1961 }
1962 }
1963 }
1964}
1965
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001966bool ClassLinker::AddImageSpace(
1967 gc::space::ImageSpace* space,
1968 Handle<mirror::ClassLoader> class_loader,
1969 jobjectArray dex_elements,
1970 const char* dex_location,
1971 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1972 std::string* error_msg) {
1973 DCHECK(out_dex_files != nullptr);
1974 DCHECK(error_msg != nullptr);
1975 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001976 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001977 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001978 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001979 DCHECK(dex_caches_object != nullptr);
1980 Runtime* const runtime = Runtime::Current();
1981 gc::Heap* const heap = runtime->GetHeap();
1982 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001983 // Check that the image is what we are expecting.
1984 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1985 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1986 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1987 image_pointer_size_);
1988 return false;
1989 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001990 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1991 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1992 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1993 expected_image_roots,
1994 header.GetImageRoots()->GetLength());
1995 return false;
1996 }
1997 StackHandleScope<3> hs(self);
1998 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1999 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2000 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2001 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002002 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002003 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2004 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002005 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002006 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002007 *error_msg = StringPrintf("Expected %d class roots but got %d",
2008 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002009 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002010 return false;
2011 }
2012 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002013 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2014 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2015 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002016 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2017 return false;
2018 }
2019 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002020 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002021 if (oat_file->GetOatHeader().GetDexFileCount() !=
2022 static_cast<uint32_t>(dex_caches->GetLength())) {
2023 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2024 "image";
2025 return false;
2026 }
2027
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002028 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002029 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2030 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002031 // TODO: Only store qualified paths.
2032 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002033 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002034 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2035 dex_file_location.c_str(),
2036 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002037 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002038 return false;
2039 }
2040
2041 if (app_image) {
2042 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2043 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002044 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002045 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002046 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002047 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002048 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002049 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002050 }
2051 }
2052 } else {
2053 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002054 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2055 this,
2056 dex_cache->GetResolvedMethods(),
2057 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002058 }
2059 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002060 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002061 }
2062 out_dex_files->push_back(std::move(dex_file));
2063 }
2064
2065 if (app_image) {
2066 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002067 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002068 // Check that the class loader resolves the same way as the ones in the image.
2069 // Image class loader [A][B][C][image dex files]
2070 // Class loader = [???][dex_elements][image dex files]
2071 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002072 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002073 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2074 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2075 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002076 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2077 *error_msg = "Unexpected BootClassLoader in app image";
2078 return false;
2079 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002080 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2081 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2082 // special case the comparison of dex files of the two class loaders, but then do full
2083 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002084 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002085 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002086 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2087 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2088 if (element != nullptr) {
2089 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002090 ObjPtr<mirror::String> name;
2091 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2092 loader_dex_file_names.push_back(name);
2093 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002094 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002095 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002096 std::string temp_error_msg;
2097 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2098 bool success = GetDexFileNames(
2099 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2100 if (success) {
2101 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2102 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2103 static_cast<size_t>(dex_caches->GetLength()));
2104 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2105 image_dex_file_names.resize(image_count);
2106 success = success && CompareDexFiles(image_dex_file_names,
2107 loader_dex_file_names,
2108 &temp_error_msg);
2109 success = success && CompareClassLoaders(soa,
2110 image_class_loader.Get(),
2111 class_loader.Get(),
2112 /*check_dex_file_names=*/ false,
2113 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002114 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002115 if (!success) {
2116 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2117 temp_error_msg.c_str());
2118 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002119 }
2120 }
2121
2122 if (kSanityCheckObjects) {
2123 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002124 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002125 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2126 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2127 if (field != nullptr) {
2128 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2129 }
2130 }
2131 }
2132 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002133 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002134 }
2135 }
2136
2137 // Set entry point to interpreter if in InterpretOnly mode.
2138 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002139 // Set image methods' entry point to interpreter.
2140 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2141 if (!method.IsRuntimeMethod()) {
2142 DCHECK(method.GetDeclaringClass() != nullptr);
2143 if (!method.IsNative() && !method.IsResolutionMethod()) {
2144 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2145 image_pointer_size_);
2146 }
2147 }
2148 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002149 }
2150
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002151 ClassTable* class_table = nullptr;
2152 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002153 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002154 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002155 }
2156 // If we have a class table section, read it and use it for verification in
2157 // UpdateAppImageClassLoadersAndDexCaches.
2158 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002159 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002160 const bool added_class_table = class_table_section.Size() > 0u;
2161 if (added_class_table) {
2162 const uint64_t start_time2 = NanoTime();
2163 size_t read_count = 0;
2164 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2165 /*make copy*/false,
2166 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002167 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002168 }
2169 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002170 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002171
2172 {
2173 ScopedTrace trace("AppImage:UpdateClassLoaders");
2174 // Update class loader and resolved strings. If added_class_table is false, the resolved
2175 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002176 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002177 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002178 // Note: We probably don't need the read barrier unless we copy the app image objects into
2179 // the region space.
2180 ObjPtr<mirror::Class> klass(root.Read());
2181 // Do not update class loader for boot image classes where the app image
2182 // class loader is only the initiating loader but not the defining loader.
2183 // Avoid read barrier since we are comparing against null.
2184 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2185 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2186 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002187 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002188 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002189
Vladimir Marko305c38b2018-02-14 11:50:07 +00002190 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002191 // Every class in the app image has initially SubtypeCheckInfo in the
2192 // Uninitialized state.
2193 //
2194 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2195 // after class initialization is complete. The app image ClassStatus as-is
2196 // are almost all ClassStatus::Initialized, and being in the
2197 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2198 //
2199 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2200 //
2201 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002202 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002203 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2204 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002205 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002206 }
2207 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002208 }
2209 if (!oat_file->GetBssGcRoots().empty()) {
2210 // Insert oat file to class table for visiting .bss GC roots.
2211 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002212 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002213
Mathieu Chartier69731002016-03-02 16:08:31 -08002214 if (added_class_table) {
2215 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2216 class_table->AddClassSet(std::move(temp_set));
2217 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002218
Mathieu Chartier69731002016-03-02 16:08:31 -08002219 if (kIsDebugBuild && app_image) {
2220 // This verification needs to happen after the classes have been added to the class loader.
2221 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002222 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002223 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002224 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002225
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002226 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002227 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002228}
2229
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002230bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002231 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2232 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002233}
2234
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002235void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002236 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2237 // enabling tracing requires the mutator lock, there are no race conditions here.
2238 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002239 Thread* const self = Thread::Current();
2240 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002241 if (kUseReadBarrier) {
2242 // We do not track new roots for CC.
2243 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2244 kVisitRootFlagClearRootLog |
2245 kVisitRootFlagStartLoggingNewRoots |
2246 kVisitRootFlagStopLoggingNewRoots));
2247 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002248 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002249 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2250 // There is 3 GC cases to handle:
2251 // Non moving concurrent:
2252 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002253 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002254 //
2255 // Moving non-concurrent:
2256 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2257 // To prevent missing roots, this case needs to ensure that there is no
2258 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2259 // class which is in the class table.
2260 //
2261 // Moving concurrent:
2262 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2263 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002264 //
2265 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2266 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2267 // these objects.
2268 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002269 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002270 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002271 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002272 for (const ClassLoaderData& data : class_loaders_) {
2273 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2274 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2275 }
2276 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002277 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002278 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002279 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002280 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002281 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002282 // Concurrent moving GC marked new roots through the to-space invariant.
2283 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002284 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002285 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2286 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2287 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2288 if (old_ref != nullptr) {
2289 DCHECK(old_ref->IsClass());
2290 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2291 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2292 // Concurrent moving GC marked new roots through the to-space invariant.
2293 CHECK_EQ(new_ref, old_ref);
2294 }
2295 }
2296 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002297 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002298 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002299 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002300 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002301 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002302 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002303 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002304 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002305 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002306 }
2307 // We deliberately ignore the class roots in the image since we
2308 // handle image roots by using the MS/CMS rescanning of dirty cards.
2309}
2310
Brian Carlstroma663ea52011-08-19 23:33:41 -07002311// Keep in sync with InitCallback. Anything we visit, we need to
2312// reinit references to when reinitializing a ClassLinker from a
2313// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002314void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002315 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002316 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002317 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2318 // unloading if we are marking roots.
2319 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002320}
2321
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002322class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2323 public:
2324 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2325 : visitor_(visitor),
2326 done_(false) {}
2327
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002328 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002329 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002330 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002331 if (!done_ && class_table != nullptr) {
2332 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2333 if (!class_table->Visit(visitor)) {
2334 // If the visitor ClassTable returns false it means that we don't need to continue.
2335 done_ = true;
2336 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002337 }
2338 }
2339
2340 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002341 // Class visitor that limits the class visits from a ClassTable to the classes with
2342 // the provided defining class loader. This filter is used to avoid multiple visits
2343 // of the same class which can be recorded for multiple initiating class loaders.
2344 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2345 public:
2346 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2347 ClassVisitor* visitor)
2348 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2349
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002350 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002351 if (klass->GetClassLoader() != defining_class_loader_) {
2352 return true;
2353 }
2354 return (*visitor_)(klass);
2355 }
2356
Vladimir Marko0984e482019-03-27 16:41:41 +00002357 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002358 ClassVisitor* const visitor_;
2359 };
2360
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002361 ClassVisitor* const visitor_;
2362 // If done is true then we don't need to do any more visiting.
2363 bool done_;
2364};
2365
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002366void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002367 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002368 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2369 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002370 }
2371}
2372
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002373void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002374 Thread* const self = Thread::Current();
2375 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2376 // Not safe to have thread suspension when we are holding a lock.
2377 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002378 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002379 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002380 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002381 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002382 }
2383}
2384
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002385class GetClassesInToVector : public ClassVisitor {
2386 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002387 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002388 classes_.push_back(klass);
2389 return true;
2390 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002391 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002392};
2393
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002394class GetClassInToObjectArray : public ClassVisitor {
2395 public:
2396 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2397 : arr_(arr), index_(0) {}
2398
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002399 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002400 ++index_;
2401 if (index_ <= arr_->GetLength()) {
2402 arr_->Set(index_ - 1, klass);
2403 return true;
2404 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002405 return false;
2406 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002407
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002408 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002409 return index_ <= arr_->GetLength();
2410 }
2411
2412 private:
2413 mirror::ObjectArray<mirror::Class>* const arr_;
2414 int32_t index_;
2415};
2416
2417void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002418 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2419 // is avoiding duplicates.
2420 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002421 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002422 GetClassesInToVector accumulator;
2423 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002424 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002425 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002426 return;
2427 }
2428 }
2429 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002430 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002431 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002432 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002433 // We size the array assuming classes won't be added to the class table during the visit.
2434 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002435 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002436 size_t class_table_size;
2437 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002438 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002439 // Add 100 in case new classes get loaded when we are filling in the object array.
2440 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002441 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002442 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002443 classes.Assign(
2444 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002445 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002446 GetClassInToObjectArray accumulator(classes.Get());
2447 VisitClasses(&accumulator);
2448 if (accumulator.Succeeded()) {
2449 break;
2450 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002451 }
2452 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2453 // If the class table shrank during creation of the clases array we expect null elements. If
2454 // the class table grew then the loop repeats. If classes are created after the loop has
2455 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002456 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002457 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002458 return;
2459 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002460 }
2461 }
2462}
2463
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002464ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002465 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002466 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002467 // CHA unloading analysis is not needed. No negative consequences are expected because
2468 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002469 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002470 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002471 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002472}
2473
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002474void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002475 Runtime* const runtime = Runtime::Current();
2476 JavaVMExt* const vm = runtime->GetJavaVM();
2477 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002478 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002479 if (runtime->GetJit() != nullptr) {
2480 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2481 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002482 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002483 code_cache->RemoveMethodsIn(self, *data.allocator);
2484 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002485 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002486 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002487 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002488 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002489 // Cleanup references to single implementation ArtMethods that will be deleted.
2490 if (cleanup_cha) {
2491 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2492 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2493 }
2494
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002495 delete data.allocator;
2496 delete data.class_table;
2497}
2498
Vladimir Markobcf17522018-06-01 13:14:32 +01002499ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2500 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002501 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002502 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2503 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002504}
2505
Vladimir Markobcf17522018-06-01 13:14:32 +01002506ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2507 Thread* self,
2508 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002509 StackHandleScope<1> hs(self);
2510 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002511 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002512 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002513 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002514 self->AssertPendingOOMException();
2515 return nullptr;
2516 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002517 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002518 if (location == nullptr) {
2519 self->AssertPendingOOMException();
2520 return nullptr;
2521 }
2522 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002523 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002524}
2525
Vladimir Markobcf17522018-06-01 13:14:32 +01002526ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2527 const DexFile& dex_file,
2528 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002529 ObjPtr<mirror::String> location = nullptr;
2530 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002531 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002532 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002533 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002534 mirror::DexCache::InitializeDexCache(self,
2535 dex_cache,
2536 location,
2537 &dex_file,
2538 linear_alloc,
2539 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002540 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002541 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002542}
2543
Roland Levillain0e840272018-08-23 19:55:30 +01002544template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002545ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2546 ObjPtr<mirror::Class> java_lang_Class,
2547 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002548 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002549 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002550 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002551 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002552 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2553 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002554 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002555 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002556 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002557 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002558 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002559}
2560
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002561ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002562 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002563}
2564
Roland Levillain0e840272018-08-23 19:55:30 +01002565ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2566 ObjPtr<mirror::Class> java_lang_Class) {
2567 // We make this class non-movable for the unlikely case where it were to be
2568 // moved by a sticky-bit (minor) collection when using the Generational
2569 // Concurrent Copying (CC) collector, potentially creating a stale reference
2570 // in the `klass_` field of one of its instances allocated in the Large-Object
2571 // Space (LOS) -- see the comment about the dirty card scanning logic in
2572 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002573 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002574 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2575}
2576
Vladimir Markobcf17522018-06-01 13:14:32 +01002577ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002578 Thread* self,
2579 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002580 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002581 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002582}
2583
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002584ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2585 const char* descriptor,
2586 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002587 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002588 if (kIsDebugBuild) {
2589 StackHandleScope<1> hs(self);
2590 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2591 Thread::PoisonObjectPointersIfDebug();
2592 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002593
2594 // For temporary classes we must wait for them to be retired.
2595 if (init_done_ && klass->IsTemp()) {
2596 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002597 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002598 ThrowEarlierClassFailure(klass);
2599 return nullptr;
2600 }
2601 StackHandleScope<1> hs(self);
2602 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2603 ObjectLock<mirror::Class> lock(self, h_class);
2604 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002605 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002606 lock.WaitIgnoringInterrupts();
2607 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002608 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002609 ThrowEarlierClassFailure(h_class.Get());
2610 return nullptr;
2611 }
2612 CHECK(h_class->IsRetired());
2613 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002614 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002615 }
2616
Brian Carlstromaded5f72011-10-07 17:15:04 -07002617 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002618 size_t index = 0;
2619 // Maximum number of yield iterations until we start sleeping.
2620 static const size_t kNumYieldIterations = 1000;
2621 // How long each sleep is in us.
2622 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002623 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002624 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002625 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002626 {
2627 ObjectTryLock<mirror::Class> lock(self, h_class);
2628 // Can not use a monitor wait here since it may block when returning and deadlock if another
2629 // thread has locked klass.
2630 if (lock.Acquired()) {
2631 // Check for circular dependencies between classes, the lock is required for SetStatus.
2632 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2633 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002634 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002635 return nullptr;
2636 }
2637 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002638 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002639 {
2640 // Handle wrapper deals with klass moving.
2641 ScopedThreadSuspension sts(self, kSuspended);
2642 if (index < kNumYieldIterations) {
2643 sched_yield();
2644 } else {
2645 usleep(kSleepDurationUS);
2646 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002647 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002648 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002650
Vladimir Marko72ab6842017-01-20 19:32:50 +00002651 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002652 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002653 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002654 }
2655 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002656 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002657 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002658 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002659}
2660
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002661using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002662
2663// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002664ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002665 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002666 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002667 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002668 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002669 return ClassPathEntry(dex_file, dex_class_def);
2670 }
2671 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002672 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002673}
2674
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002675bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2676 Thread* self,
2677 const char* descriptor,
2678 size_t hash,
2679 Handle<mirror::ClassLoader> class_loader,
2680 /*out*/ ObjPtr<mirror::Class>* result) {
2681 ArtField* field =
2682 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2683 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2684 if (raw_shared_libraries == nullptr) {
2685 return true;
2686 }
2687
2688 StackHandleScope<2> hs(self);
2689 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2690 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2691 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2692 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2693 temp_loader.Assign(shared_libraries->Get(i));
2694 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2695 return false; // One of the shared libraries is not supported.
2696 }
2697 if (*result != nullptr) {
2698 return true; // Found the class up the chain.
2699 }
2700 }
2701 return true;
2702}
2703
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002704bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2705 Thread* self,
2706 const char* descriptor,
2707 size_t hash,
2708 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002709 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002710 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002711 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002712 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002713 return true;
2714 }
2715
David Brazdil05909d82018-12-06 16:25:16 +00002716 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002717 // For regular path or dex class loader the search order is:
2718 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002719 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002721
Calin Juravlecdd49122017-07-05 20:09:53 -07002722 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2723 StackHandleScope<1> hs(self);
2724 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2725 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2726 return false; // One of the parents is not supported.
2727 }
2728 if (*result != nullptr) {
2729 return true; // Found the class up the chain.
2730 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002731
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002732 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2733 return false; // One of the shared library loader is not supported.
2734 }
2735 if (*result != nullptr) {
2736 return true; // Found the class in a shared library.
2737 }
2738
Calin Juravlecdd49122017-07-05 20:09:53 -07002739 // Search the current class loader classpath.
2740 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002741 return true;
2742 }
2743
Calin Juravlecdd49122017-07-05 20:09:53 -07002744 if (IsDelegateLastClassLoader(soa, class_loader)) {
2745 // For delegate last, the search order is:
2746 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002747 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002748 // - class loader dex files
2749 // - parent
2750 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2751 if (*result != nullptr) {
2752 return true; // The class is part of the boot class path.
2753 }
2754
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002755 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2756 return false; // One of the shared library loader is not supported.
2757 }
2758 if (*result != nullptr) {
2759 return true; // Found the class in a shared library.
2760 }
2761
Calin Juravlecdd49122017-07-05 20:09:53 -07002762 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2763 if (*result != nullptr) {
2764 return true; // Found the class in the current class loader
2765 }
2766
2767 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2768 StackHandleScope<1> hs(self);
2769 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2770 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2771 }
2772
2773 // Unsupported class loader.
2774 *result = nullptr;
2775 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002776}
2777
2778// Finds the class in the boot class loader.
2779// If the class is found the method returns the resolved class. Otherwise it returns null.
2780ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2781 const char* descriptor,
2782 size_t hash) {
2783 ObjPtr<mirror::Class> result = nullptr;
2784 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2785 if (pair.second != nullptr) {
2786 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2787 if (klass != nullptr) {
2788 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002789 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002790 result = DefineClass(self,
2791 descriptor,
2792 hash,
2793 ScopedNullHandle<mirror::ClassLoader>(),
2794 *pair.first,
2795 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002796 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002797 if (result == nullptr) {
2798 CHECK(self->IsExceptionPending()) << descriptor;
2799 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002800 }
2801 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002802 return result;
2803}
Andreas Gampef865ea92015-04-13 22:14:19 -07002804
Calin Juravle415dc3d2017-06-28 11:03:12 -07002805ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2806 ScopedObjectAccessAlreadyRunnable& soa,
2807 const char* descriptor,
2808 size_t hash,
2809 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002810 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2811 IsInMemoryDexClassLoader(soa, class_loader) ||
2812 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002813 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002814
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002815 ObjPtr<mirror::Class> ret;
2816 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002817 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002818 if (dex_class_def != nullptr) {
2819 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2820 descriptor,
2821 hash,
2822 class_loader,
2823 *cp_dex_file,
2824 *dex_class_def);
2825 if (klass == nullptr) {
2826 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2827 soa.Self()->ClearException();
2828 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002829 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002830 ret = klass;
2831 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002832 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002833 return true; // Continue with the next DexFile.
2834 };
2835
2836 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2837 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002838}
2839
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002840ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2841 const char* descriptor,
2842 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002843 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002844 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002845 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002846 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002847 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002848 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2849 // for primitive classes that aren't backed by dex files.
2850 return FindPrimitiveClass(descriptor[0]);
2851 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002852 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002853 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002854 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002855 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002856 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002857 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002858 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002859 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002860 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002861 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002862 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002863 return DefineClass(self,
2864 descriptor,
2865 hash,
2866 ScopedNullHandle<mirror::ClassLoader>(),
2867 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002868 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002869 } else {
2870 // The boot class loader is searched ahead of the application class loader, failures are
2871 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2872 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002873 ObjPtr<mirror::Throwable> pre_allocated =
2874 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002875 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002876 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002877 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002878 }
2879 ObjPtr<mirror::Class> result_ptr;
2880 bool descriptor_equals;
2881 if (descriptor[0] == '[') {
2882 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2883 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2884 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2885 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002886 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002887 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002888 bool known_hierarchy =
2889 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2890 if (result_ptr != nullptr) {
2891 // The chain was understood and we found the class. We still need to add the class to
2892 // the class table to protect from racy programs that can try and redefine the path list
2893 // which would change the Class<?> returned for subsequent evaluation of const-class.
2894 DCHECK(known_hierarchy);
2895 DCHECK(result_ptr->DescriptorEquals(descriptor));
2896 descriptor_equals = true;
2897 } else {
2898 // Either the chain wasn't understood or the class wasn't found.
2899 //
2900 // If the chain was understood but we did not find the class, let the Java-side
2901 // rediscover all this and throw the exception with the right stack trace. Note that
2902 // the Java-side could still succeed for racy programs if another thread is actively
2903 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002904
Alex Light185a4612018-10-04 15:54:25 -07002905 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002906 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002907 // Oops, we can't call into java so we can't run actual class-loader code.
2908 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002909 ObjPtr<mirror::Throwable> pre_allocated =
2910 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2911 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002912 return nullptr;
2913 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002914
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002915 // Inlined DescriptorToDot(descriptor) with extra validation.
2916 //
2917 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2918 // the DescriptorEquals() check below and give a confusing error message. For example,
2919 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2920 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2921 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2922 size_t descriptor_length = strlen(descriptor);
2923 if (UNLIKELY(descriptor[0] != 'L') ||
2924 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2925 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2926 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2927 return nullptr;
2928 }
2929 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2930 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2931
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002932 ScopedLocalRef<jobject> class_loader_object(
2933 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002934 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2935 {
2936 ScopedThreadStateChange tsc(self, kNative);
2937 ScopedLocalRef<jobject> class_name_object(
2938 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2939 if (class_name_object.get() == nullptr) {
2940 DCHECK(self->IsExceptionPending()); // OOME.
2941 return nullptr;
2942 }
2943 CHECK(class_loader_object.get() != nullptr);
2944 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2945 WellKnownClasses::java_lang_ClassLoader_loadClass,
2946 class_name_object.get()));
2947 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002948 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002949 // broken loader - throw NPE to be compatible with Dalvik
2950 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2951 class_name_string.c_str()).c_str());
2952 return nullptr;
2953 }
2954 result_ptr = soa.Decode<mirror::Class>(result.get());
2955 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002956 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002957 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002958 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002959
2960 if (self->IsExceptionPending()) {
2961 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2962 // However, to comply with the RI behavior, first check if another thread succeeded.
2963 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2964 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2965 self->ClearException();
2966 return EnsureResolved(self, descriptor, result_ptr);
2967 }
2968 return nullptr;
2969 }
2970
2971 // Try to insert the class to the class table, checking for mismatch.
2972 ObjPtr<mirror::Class> old;
2973 {
2974 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2975 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2976 old = class_table->Lookup(descriptor, hash);
2977 if (old == nullptr) {
2978 old = result_ptr; // For the comparison below, after releasing the lock.
2979 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002980 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002981 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002982 } // else throw below, after releasing the lock.
2983 }
2984 }
2985 if (UNLIKELY(old != result_ptr)) {
2986 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2987 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002988 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002989 const char* loader_class_name =
2990 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2991 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2992 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2993 << DescriptorToDot(descriptor) << "\").";
2994 return EnsureResolved(self, descriptor, old);
2995 }
2996 if (UNLIKELY(!descriptor_equals)) {
2997 std::string result_storage;
2998 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2999 std::string loader_storage;
3000 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3001 ThrowNoClassDefFoundError(
3002 "Initiating class loader of type %s returned class %s instead of %s.",
3003 DescriptorToDot(loader_class_name).c_str(),
3004 DescriptorToDot(result_name).c_str(),
3005 DescriptorToDot(descriptor).c_str());
3006 return nullptr;
3007 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003008 // Success.
3009 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003010}
3011
Vladimir Markob9c29f62019-03-20 14:22:51 +00003012static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3013 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003014 return
3015 // Reserved conscrypt packages (includes sub-packages under these paths).
3016 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3017 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3018 // Reserved updatable-media package (includes sub-packages under this path).
3019 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003020}
3021
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003022ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3023 const char* descriptor,
3024 size_t hash,
3025 Handle<mirror::ClassLoader> class_loader,
3026 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003027 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003028 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003029 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003030
Brian Carlstromaded5f72011-10-07 17:15:04 -07003031 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003032 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003033 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003034 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003035 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003036 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003037 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003038 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003039 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003040 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003041 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003042 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003043 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003044 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003045 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003046 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003047 }
3048
Vladimir Markob9c29f62019-03-20 14:22:51 +00003049 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3050 // some runtime modules. Prevent definition of classes in app class loader that could clash
3051 // with these modules as these classes could be resolved differently during execution.
3052 if (class_loader != nullptr &&
3053 Runtime::Current()->IsAotCompiler() &&
3054 IsReservedBootClassPathDescriptor(descriptor)) {
3055 ObjPtr<mirror::Throwable> pre_allocated =
3056 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3057 self->SetException(pre_allocated);
3058 return nullptr;
3059 }
3060
Alex Lighte9f61032018-09-24 16:04:51 -07003061 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3062 // code to be executed. We put it up here so we can avoid all the allocations associated with
3063 // creating the class. This can happen with (eg) jit threads.
3064 if (!self->CanLoadClasses()) {
3065 // Make sure we don't try to load anything, potentially causing an infinite loop.
3066 ObjPtr<mirror::Throwable> pre_allocated =
3067 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3068 self->SetException(pre_allocated);
3069 return nullptr;
3070 }
3071
Andreas Gampefa4333d2017-02-14 11:10:34 -08003072 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003073 // Allocate a class with the status of not ready.
3074 // Interface object should get the right size here. Regular class will
3075 // figure out the right size later and be replaced with one of the right
3076 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003077 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003078 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003079 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003080 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003081 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003082 }
Alex Lightb0f11922017-01-23 14:25:17 -08003083 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3084 // nothing.
3085 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003086 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003087 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3088 // will only be called once.
3089 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3090 klass,
3091 class_loader,
3092 dex_file,
3093 dex_class_def,
3094 &new_dex_file,
3095 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003096 // Check to see if an exception happened during runtime callbacks. Return if so.
3097 if (self->IsExceptionPending()) {
3098 return nullptr;
3099 }
Alex Lightb0f11922017-01-23 14:25:17 -08003100 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003101 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003102 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003103 return nullptr;
3104 }
3105 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003106 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003107
Jeff Hao848f70a2014-01-15 13:49:50 -08003108 // Mark the string class by setting its access flag.
3109 if (UNLIKELY(!init_done_)) {
3110 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3111 klass->SetStringClass();
3112 }
3113 }
3114
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003115 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003116 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003117 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003118 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003119
Mathieu Chartier590fee92013-09-13 13:46:47 -07003120 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003121 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003122 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003123 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3124 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003125 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003126 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003127
Mathieu Chartierc7853442015-03-27 14:35:38 -07003128 // Load the fields and other things after we are inserted in the table. This is so that we don't
3129 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3130 // other reason is that the field roots are only visited from the class table. So we need to be
3131 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003132 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003133 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003134 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003135 // An exception occured during load, set status to erroneous while holding klass' lock in case
3136 // notification is necessary.
3137 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003138 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003139 }
3140 return nullptr;
3141 }
3142
Brian Carlstromaded5f72011-10-07 17:15:04 -07003143 // Finish loading (if necessary) by finding parents
3144 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003145 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003146 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003147 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003148 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003149 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003150 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003151 }
3152 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003153
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003154 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003155 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003156 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003157
Brian Carlstromaded5f72011-10-07 17:15:04 -07003158 // Link the class (if necessary)
3159 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003160 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003161 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003162
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003163 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003164 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003165 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003166 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003167 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003168 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003169 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003170 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003171 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003172 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003173 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003174
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003175 // Instrumentation may have updated entrypoints for all methods of all
3176 // classes. However it could not update methods of this class while we
3177 // were loading it. Now the class is resolved, we can update entrypoints
3178 // as required by instrumentation.
3179 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3180 // We must be in the kRunnable state to prevent instrumentation from
3181 // suspending all threads to update entrypoints while we are doing it
3182 // for this class.
3183 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003184 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003185 }
3186
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003187 /*
3188 * We send CLASS_PREPARE events to the debugger from here. The
3189 * definition of "preparation" is creating the static fields for a
3190 * class and initializing them to the standard default values, but not
3191 * executing any code (that comes later, during "initialization").
3192 *
3193 * We did the static preparation in LinkClass.
3194 *
3195 * The class has been prepared and resolved but possibly not yet verified
3196 * at this point.
3197 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003198 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003199
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003200 // Notify native debugger of the new class and its layout.
3201 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3202
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003203 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003204}
3205
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003206uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003207 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003208 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003209 size_t num_8 = 0;
3210 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003211 size_t num_32 = 0;
3212 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003213 ClassAccessor accessor(dex_file, dex_class_def);
3214 // We allow duplicate definitions of the same field in a class_data_item
3215 // but ignore the repeated indexes here, b/21868015.
3216 uint32_t last_field_idx = dex::kDexNoIndex;
3217 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3218 uint32_t field_idx = field.GetIndex();
3219 // Ordering enforced by DexFileVerifier.
3220 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3221 if (UNLIKELY(field_idx == last_field_idx)) {
3222 continue;
3223 }
3224 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003225 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003226 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3227 char c = descriptor[0];
3228 switch (c) {
3229 case 'L':
3230 case '[':
3231 num_ref++;
3232 break;
3233 case 'J':
3234 case 'D':
3235 num_64++;
3236 break;
3237 case 'I':
3238 case 'F':
3239 num_32++;
3240 break;
3241 case 'S':
3242 case 'C':
3243 num_16++;
3244 break;
3245 case 'B':
3246 case 'Z':
3247 num_8++;
3248 break;
3249 default:
3250 LOG(FATAL) << "Unknown descriptor: " << c;
3251 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003252 }
3253 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003254 return mirror::Class::ComputeClassSize(false,
3255 0,
3256 num_8,
3257 num_16,
3258 num_32,
3259 num_64,
3260 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003261 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003262}
3263
Alex Lightfc49fec2018-01-16 22:28:36 +00003264// Special case to get oat code without overwriting a trampoline.
3265const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003266 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003267 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003268 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003269 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003270 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3271 if (code != nullptr) {
3272 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003273 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003274 if (method->IsNative()) {
3275 // No code and native? Use generic trampoline.
3276 return GetQuickGenericJniStub();
3277 }
3278 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003279}
3280
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003281bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003282 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003283 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3284 return false;
3285 }
3286
Elliott Hughes956af0f2014-12-11 14:34:28 -08003287 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003288 return true;
3289 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003290
3291 Runtime* runtime = Runtime::Current();
3292 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3293 if (instr->InterpretOnly()) {
3294 return true;
3295 }
3296
3297 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3298 // Doing this check avoids doing compiled/interpreter transitions.
3299 return true;
3300 }
3301
Alex Light3dacdd62019-03-12 15:45:47 +00003302 if (Thread::Current()->IsForceInterpreter() ||
3303 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003304 // Force the use of interpreter when it is required by the debugger.
3305 return true;
3306 }
3307
Alex Light8f34aba2017-10-09 13:46:32 -07003308 if (Thread::Current()->IsAsyncExceptionPending()) {
3309 // Force use of interpreter to handle async-exceptions
3310 return true;
3311 }
3312
Alex Light2d441b12018-06-08 15:33:21 -07003313 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3314 const void* instr_target = instr->GetCodeForInvoke(method);
3315 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3316 return ShouldUseInterpreterEntrypoint(method, instr_target);
3317 }
3318
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003319 if (runtime->IsJavaDebuggable()) {
3320 // For simplicity, we ignore precompiled code and go to the interpreter
3321 // assuming we don't already have jitted code.
3322 // We could look at the oat file where `quick_code` is being defined,
3323 // and check whether it's been compiled debuggable, but we decided to
3324 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003325 jit::Jit* jit = Runtime::Current()->GetJit();
3326 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3327 }
3328
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003329 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003330 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003331 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003332 // since we want to JIT it (at first use) with extra stackmaps for native
3333 // debugging. We keep however all AOT code from the boot image,
3334 // since the JIT-at-first-use is blocking and would result in non-negligible
3335 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003336 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003337 }
3338
3339 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003340}
3341
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003342void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003343 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003344 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003345 if (klass->NumDirectMethods() == 0) {
3346 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003347 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003348 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003349 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003350 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003351 return; // OAT file unavailable.
3352 }
Ian Rogers19846512012-02-24 11:42:47 -08003353 }
Alex Light64ad14d2014-08-19 14:23:13 -07003354
Mathieu Chartierf8322842014-05-16 10:59:25 -07003355 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003356 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3357 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3358 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003359 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003360 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003361 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003362 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3363 klass->GetDexClassDefIndex(),
3364 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003365 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003366 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003367 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003368 if (!method->IsStatic()) {
3369 // Only update static methods.
3370 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003371 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003372 const void* quick_code = nullptr;
3373 if (has_oat_class) {
3374 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003375 quick_code = oat_method.GetQuickCode();
3376 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003377 // Check whether the method is native, in which case it's generic JNI.
3378 if (quick_code == nullptr && method->IsNative()) {
3379 quick_code = GetQuickGenericJniStub();
3380 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003381 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003382 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003383 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003384 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003385 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003386 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003387}
3388
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003389// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3390// method. Should only be called on non-invokable methods.
3391inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003392 DCHECK(method != nullptr);
3393 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003394 method->SetEntryPointFromQuickCompiledCodePtrSize(
3395 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3396 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003397}
3398
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003399static void LinkCode(ClassLinker* class_linker,
3400 ArtMethod* method,
3401 const OatFile::OatClass* oat_class,
3402 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003403 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003404 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003405 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003406 // The following code only applies to a non-compiler runtime.
3407 return;
3408 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003409 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003410 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003411 if (oat_class != nullptr) {
3412 // Every kind of method should at least get an invoke stub from the oat_method.
3413 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003414 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003415 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003416 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003417
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003418 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003419 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003420 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003421
Alex Light9139e002015-10-09 15:59:48 -07003422 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003423 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003424 return;
3425 }
Ian Rogers19846512012-02-24 11:42:47 -08003426
3427 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003428 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003429 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3430 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003431 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003432 } else if (quick_code == nullptr && method->IsNative()) {
3433 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003434 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003435 // Set entry point from compiled code if there's no code or in interpreter only mode.
3436 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003437 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003438
Ian Rogers62d6c772013-02-27 08:32:07 -08003439 if (method->IsNative()) {
3440 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003441 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003442
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003443 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003444 // We have a native method here without code. Then it should have either the generic JNI
3445 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3446 // TODO: this doesn't handle all the cases where trampolines may be installed.
3447 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003448 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3449 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003450 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003451 }
3452}
3453
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003454void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003455 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003456 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003457 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003458 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003459 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003460 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003461 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003462 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003463
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003464 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003465 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003466 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003467 klass->SetAccessFlags(access_flags);
3468 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003469 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003470 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003471
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003472 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003473 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003474}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003475
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003476LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3477 LinearAlloc* allocator,
3478 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003479 if (length == 0) {
3480 return nullptr;
3481 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003482 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3483 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3484 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003485 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003486 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003487 CHECK(ret != nullptr);
3488 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3489 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003490}
3491
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003492LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3493 LinearAlloc* allocator,
3494 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003495 if (length == 0) {
3496 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003497 }
Vladimir Marko14632852015-08-17 12:07:23 +01003498 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3499 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003500 const size_t storage_size =
3501 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003502 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003503 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003504 CHECK(ret != nullptr);
3505 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003506 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003507 }
3508 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003509}
3510
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003511LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003512 if (class_loader == nullptr) {
3513 return Runtime::Current()->GetLinearAlloc();
3514 }
3515 LinearAlloc* allocator = class_loader->GetAllocator();
3516 DCHECK(allocator != nullptr);
3517 return allocator;
3518}
3519
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003520LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003521 if (class_loader == nullptr) {
3522 return Runtime::Current()->GetLinearAlloc();
3523 }
3524 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3525 LinearAlloc* allocator = class_loader->GetAllocator();
3526 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003527 RegisterClassLoader(class_loader);
3528 allocator = class_loader->GetAllocator();
3529 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003530 }
3531 return allocator;
3532}
3533
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003534void ClassLinker::LoadClass(Thread* self,
3535 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003536 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003537 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003538 ClassAccessor accessor(dex_file,
3539 dex_class_def,
3540 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003541 if (!accessor.HasClassData()) {
3542 return;
3543 }
3544 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003545 {
3546 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3547 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003548 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003549 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003550 // We allow duplicate definitions of the same field in a class_data_item
3551 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003552 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003553 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3554 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003555 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003556 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3557 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003558 accessor.NumInstanceFields());
3559 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003560 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003561 uint32_t last_static_field_idx = 0u;
3562 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003563
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003564 // Methods
3565 bool has_oat_class = false;
3566 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3567 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3568 : OatFile::OatClass::Invalid();
3569 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3570 klass->SetMethodsPtr(
3571 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3572 accessor.NumDirectMethods(),
3573 accessor.NumVirtualMethods());
3574 size_t class_def_method_index = 0;
3575 uint32_t last_dex_method_index = dex::kDexNoIndex;
3576 size_t last_class_def_method_index = 0;
3577
3578 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3579 // methods needs to decode all of the fields.
3580 accessor.VisitFieldsAndMethods([&](
3581 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3582 uint32_t field_idx = field.GetIndex();
3583 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3584 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3585 LoadField(field, klass, &sfields->At(num_sfields));
3586 ++num_sfields;
3587 last_static_field_idx = field_idx;
3588 }
3589 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3590 uint32_t field_idx = field.GetIndex();
3591 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3592 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3593 LoadField(field, klass, &ifields->At(num_ifields));
3594 ++num_ifields;
3595 last_instance_field_idx = field_idx;
3596 }
3597 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3598 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3599 image_pointer_size_);
3600 LoadMethod(dex_file, method, klass, art_method);
3601 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3602 uint32_t it_method_index = method.GetIndex();
3603 if (last_dex_method_index == it_method_index) {
3604 // duplicate case
3605 art_method->SetMethodIndex(last_class_def_method_index);
3606 } else {
3607 art_method->SetMethodIndex(class_def_method_index);
3608 last_dex_method_index = it_method_index;
3609 last_class_def_method_index = class_def_method_index;
3610 }
3611 ++class_def_method_index;
3612 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3613 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3614 class_def_method_index - accessor.NumDirectMethods(),
3615 image_pointer_size_);
3616 LoadMethod(dex_file, method, klass, art_method);
3617 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3618 ++class_def_method_index;
3619 });
3620
3621 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003622 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003623 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3624 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3625 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003626 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3627 if (sfields != nullptr) {
3628 sfields->SetSize(num_sfields);
3629 }
3630 if (ifields != nullptr) {
3631 ifields->SetSize(num_ifields);
3632 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003633 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003634 // Set the field arrays.
3635 klass->SetSFieldsPtr(sfields);
3636 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003637 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003638 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003639 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003640 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003641 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003642 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003643}
3644
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003645void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003646 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003647 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003648 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003649 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003650 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003651
David Brazdil85865692018-10-30 17:26:20 +00003652 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3653 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003654}
3655
Mathieu Chartier268764d2016-09-13 12:09:38 -07003656void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003657 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003658 Handle<mirror::Class> klass,
3659 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003660 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003661 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003662 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003663
Mathieu Chartier268764d2016-09-13 12:09:38 -07003664 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003665 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003666 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003667 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003668
David Brazdil85865692018-10-30 17:26:20 +00003669 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3670 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003671
Ian Rogersdfb325e2013-10-30 01:00:44 -07003672 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003673 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003674 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3675 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003676 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003677 klass->SetFinalizable();
3678 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003679 std::string temp;
3680 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003681 // The Enum class declares a "final" finalize() method to prevent subclasses from
3682 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3683 // subclasses, so we exclude it here.
3684 // We also want to avoid setting the flag on Object, where we know that finalize() is
3685 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003686 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3687 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003688 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003689 }
3690 }
3691 }
3692 } else if (method_name[0] == '<') {
3693 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003694 bool is_init = (strcmp("<init>", method_name) == 0);
3695 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003696 if (UNLIKELY(!is_init && !is_clinit)) {
3697 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3698 } else {
3699 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3700 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003701 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003702 access_flags |= kAccConstructor;
3703 }
3704 }
3705 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003706 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3707 // Check if the native method is annotated with @FastNative or @CriticalNative.
3708 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3709 dex_file, dst->GetClassDef(), dex_method_idx);
3710 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003711 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003712 // Must be done after SetAccessFlags since IsAbstract depends on it.
3713 if (klass->IsInterface() && dst->IsAbstract()) {
3714 dst->CalculateAndSetImtIndex();
3715 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003716}
3717
Ian Rogers7b078e82014-09-10 14:44:24 -07003718void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003719 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003720 self,
3721 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003722 Runtime::Current()->GetLinearAlloc());
3723 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003724 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003725}
3726
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003727void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003728 ObjPtr<mirror::DexCache> dex_cache) {
3729 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003730 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003731 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003732 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003733}
3734
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003735void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003736 ObjPtr<mirror::DexCache> dex_cache,
3737 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003738 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003739 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003740 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003741 // For app images, the dex cache location may be a suffix of the dex file location since the
3742 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003743 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3744 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003745 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3746 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003747 // The following paths checks don't work on preopt when using boot dex files, where the dex
3748 // cache location is the one on device, and the dex_file's location is the one on host.
3749 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3750 CHECK_GE(dex_file_location.length(), dex_cache_length)
3751 << dex_cache_location << " " << dex_file.GetLocation();
3752 const std::string dex_file_suffix = dex_file_location.substr(
3753 dex_file_location.length() - dex_cache_length,
3754 dex_cache_length);
3755 // Example dex_cache location is SettingsProvider.apk and
3756 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3757 CHECK_EQ(dex_cache_location, dex_file_suffix);
3758 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003759 const OatFile* oat_file =
3760 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003761 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3762 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3763 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3764 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003765 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003766 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3767 DexCacheData data = *it;
3768 if (self->IsJWeakCleared(data.weak_root)) {
3769 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003770 it = dex_caches_.erase(it);
3771 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003772 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003773 it->dex_file->GetOatDexFile() != nullptr &&
3774 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003775 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003776 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003777 ++it;
3778 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003779 }
Vladimir Markob066d432018-01-03 13:14:37 +00003780 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003781 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003782 }
David Brazdila5c3a802019-03-08 14:59:41 +00003783 // Let hiddenapi assign a domain to the newly registered dex file.
3784 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3785
Vladimir Markocd556b02017-02-03 11:47:34 +00003786 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003787 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003788 DexCacheData data;
3789 data.weak_root = dex_cache_jweak;
3790 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003791 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003792 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003793 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003794 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3795 // path dex caches without an image.
3796 data.class_table->InsertStrongRoot(dex_cache);
3797 if (class_loader != nullptr) {
3798 // Since we added a strong root to the class table, do the write barrier as required for
3799 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003800 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003801 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003802 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003803}
3804
Vladimir Markocd556b02017-02-03 11:47:34 +00003805ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3806 return data.IsValid()
3807 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3808 : nullptr;
3809}
3810
3811ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3812 Thread* self,
3813 ObjPtr<mirror::DexCache> dex_cache,
3814 const DexCacheData& data,
3815 ObjPtr<mirror::ClassLoader> class_loader) {
3816 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3817 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3818 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3819 "Attempt to register dex file %s with multiple class loaders",
3820 data.dex_file->GetLocation().c_str());
3821 return nullptr;
3822 }
3823 return dex_cache;
3824}
3825
Alex Light07f06212017-06-01 14:01:43 -07003826void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3827 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003828 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003829 Thread* self = Thread::Current();
3830 StackHandleScope<2> hs(self);
3831 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3832 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3833 const DexFile* dex_file = dex_cache->GetDexFile();
3834 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3835 if (kIsDebugBuild) {
3836 DexCacheData old_data;
3837 {
3838 ReaderMutexLock mu(self, *Locks::dex_lock_);
3839 old_data = FindDexCacheDataLocked(*dex_file);
3840 }
3841 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3842 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3843 << "been registered on dex file " << dex_file->GetLocation();
3844 }
3845 ClassTable* table;
3846 {
3847 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3848 table = InsertClassTableForClassLoader(h_class_loader.Get());
3849 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003850 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3851 // a thread holding the dex lock and blocking on a condition variable regarding
3852 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003853 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003854 WriterMutexLock mu(self, *Locks::dex_lock_);
3855 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3856 table->InsertStrongRoot(h_dex_cache.Get());
3857 if (h_class_loader.Get() != nullptr) {
3858 // Since we added a strong root to the class table, do the write barrier as required for
3859 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003860 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003861 }
3862}
3863
Vladimir Markocd556b02017-02-03 11:47:34 +00003864ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3865 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003866 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003867 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003868 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003869 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003870 old_data = FindDexCacheDataLocked(dex_file);
3871 }
3872 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3873 if (old_dex_cache != nullptr) {
3874 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003875 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003876 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003877 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3878 DCHECK(linear_alloc != nullptr);
3879 ClassTable* table;
3880 {
3881 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3882 table = InsertClassTableForClassLoader(class_loader);
3883 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003884 // Don't alloc while holding the lock, since allocation may need to
3885 // suspend all threads and another thread may need the dex_lock_ to
3886 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003887 StackHandleScope<3> hs(self);
3888 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003889 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003890 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3891 self,
3892 dex_file)));
3893 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003894 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003895 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3896 // a thread holding the dex lock and blocking on a condition variable regarding
3897 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003898 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003899 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003900 old_data = FindDexCacheDataLocked(dex_file);
3901 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003902 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003903 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3904 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3905 // that the arrays are null.
3906 mirror::DexCache::InitializeDexCache(self,
3907 h_dex_cache.Get(),
3908 h_location.Get(),
3909 &dex_file,
3910 linear_alloc,
3911 image_pointer_size_);
3912 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003913 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003914 }
3915 if (old_dex_cache != nullptr) {
3916 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3917 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003918 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003919 self->ClearException();
3920 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3921 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3922 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003923 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003924 self->AssertPendingOOMException();
3925 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003926 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003927 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003928 if (h_class_loader.Get() != nullptr) {
3929 // Since we added a strong root to the class table, do the write barrier as required for
3930 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003931 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003932 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003933 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003934}
3935
Vladimir Markocd556b02017-02-03 11:47:34 +00003936bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003937 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003938 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003939}
3940
Vladimir Markocd556b02017-02-03 11:47:34 +00003941ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3942 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003943 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3944 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003945 if (dex_cache != nullptr) {
3946 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003947 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003948 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003949 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003950 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003951 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003952 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003953 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003954 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3955 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003956 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003957}
3958
Vladimir Markocd556b02017-02-03 11:47:34 +00003959ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3960 const DexFile* dex_file = dex_cache->GetDexFile();
3961 DCHECK(dex_file != nullptr);
3962 ReaderMutexLock mu(self, *Locks::dex_lock_);
3963 // Search assuming unique-ness of dex file.
3964 for (const DexCacheData& data : dex_caches_) {
3965 // Avoid decoding (and read barriers) other unrelated dex caches.
3966 if (data.dex_file == dex_file) {
3967 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3968 if (registered_dex_cache != nullptr) {
3969 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3970 return data.class_table;
3971 }
3972 }
3973 }
3974 return nullptr;
3975}
3976
3977ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3978 // Search assuming unique-ness of dex file.
3979 for (const DexCacheData& data : dex_caches_) {
3980 // Avoid decoding (and read barriers) other unrelated dex caches.
3981 if (data.dex_file == &dex_file) {
3982 return data;
3983 }
3984 }
3985 return DexCacheData();
3986}
3987
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003988ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003989 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003990 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003991 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003992 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003993 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003994 }
Ian Rogers1f539342012-10-03 21:09:42 -07003995 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003996 StackHandleScope<1> hs(self);
3997 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003998 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003999 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
4000 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004001 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07004002 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004003 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004004 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004005 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4006 h_class.Get(),
4007 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004008 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004009 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004010}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004011
Vladimir Marko02610552018-06-04 14:38:00 +01004012inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4013 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4014}
4015
Brian Carlstrombe977852011-07-19 14:54:54 -07004016// Create an array class (i.e. the class object for the array, not the
4017// array itself). "descriptor" looks like "[C" or "[[[[B" or
4018// "[Ljava/lang/String;".
4019//
4020// If "descriptor" refers to an array of primitives, look up the
4021// primitive type's internally-generated class object.
4022//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004023// "class_loader" is the class loader of the class that's referring to
4024// us. It's used to ensure that we're looking for the element type in
4025// the right context. It does NOT become the class loader for the
4026// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004027//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004028// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004029ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4030 const char* descriptor,
4031 size_t hash,
4032 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004033 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004034 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004035 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004036
4037 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4038 // code to be executed. We put it up here so we can avoid all the allocations associated with
4039 // creating the class. This can happen with (eg) jit threads.
4040 if (!self->CanLoadClasses()) {
4041 // Make sure we don't try to load anything, potentially causing an infinite loop.
4042 ObjPtr<mirror::Throwable> pre_allocated =
4043 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4044 self->SetException(pre_allocated);
4045 return nullptr;
4046 }
4047
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004048 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4049 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004050 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004051 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004052 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004053 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4054 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004055 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004056 DCHECK(self->IsExceptionPending());
4057 return nullptr;
4058 } else {
4059 self->ClearException();
4060 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004061 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004062 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4063 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4064 return nullptr;
4065 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004066 // See if the component type is already loaded. Array classes are
4067 // always associated with the class loader of their underlying
4068 // element type -- an array of Strings goes with the loader for
4069 // java/lang/String -- so we need to look for it there. (The
4070 // caller should have checked for the existence of the class
4071 // before calling here, but they did so with *their* class loader,
4072 // not the component type's loader.)
4073 //
4074 // If we find it, the caller adds "loader" to the class' initiating
4075 // loader list, which should prevent us from going through this again.
4076 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004077 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004078 // are the same, because our caller (FindClass) just did the
4079 // lookup. (Even if we get this wrong we still have correct behavior,
4080 // because we effectively do this lookup again when we add the new
4081 // class to the hash table --- necessary because of possible races with
4082 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004083 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004084 ObjPtr<mirror::Class> new_class =
4085 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004086 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004087 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004088 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004089 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004090
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004091 // Fill out the fields in the Class.
4092 //
4093 // It is possible to execute some methods against arrays, because
4094 // all arrays are subclasses of java_lang_Object_, so we need to set
4095 // up a vtable. We can just point at the one in java_lang_Object_.
4096 //
4097 // Array classes are simple enough that we don't need to do a full
4098 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004099 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004100 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004101 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004102 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004103 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004104 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004105 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4106 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4107 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004108 } else if (strcmp(descriptor, "[Z") == 0) {
4109 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4110 } else if (strcmp(descriptor, "[B") == 0) {
4111 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4112 } else if (strcmp(descriptor, "[C") == 0) {
4113 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4114 } else if (strcmp(descriptor, "[S") == 0) {
4115 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004116 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004117 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004118 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004119 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004120 } else if (strcmp(descriptor, "[F") == 0) {
4121 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4122 } else if (strcmp(descriptor, "[D") == 0) {
4123 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004124 }
4125 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004126 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004127 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004128 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004129 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004130 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004131 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004132 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004133 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004134 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004135 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004136 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004137 new_class->SetSuperClass(java_lang_Object);
4138 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004139 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004140 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004141 if (component_type->IsPrimitive()) {
4142 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4143 } else {
4144 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4145 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004146 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004147 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4148 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4149 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004150 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004151 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004152 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004153 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004154
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004155 // All arrays have java/lang/Cloneable and java/io/Serializable as
4156 // interfaces. We need to set that up here, so that stuff like
4157 // "instanceof" works right.
4158 //
4159 // Note: The GC could run during the call to FindSystemClass,
4160 // so we need to make sure the class object is GC-valid while we're in
4161 // there. Do this by clearing the interface list so the GC will just
4162 // think that the entries are null.
4163
4164
4165 // Use the single, global copies of "interfaces" and "iftable"
4166 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004167 {
Vladimir Marko02610552018-06-04 14:38:00 +01004168 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004169 CHECK(array_iftable != nullptr);
4170 new_class->SetIfTable(array_iftable);
4171 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004172
Elliott Hughes00626c22013-06-14 15:04:14 -07004173 // Inherit access flags from the component type.
4174 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4175 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4176 access_flags &= kAccJavaFlagsMask;
4177 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004178 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004179 access_flags |= kAccAbstract | kAccFinal;
4180 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004181 // Arrays are access-checks-clean and preverified.
4182 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004183
4184 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004185
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004186 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004187 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004188 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4189 // duplicate events in case of races. Array classes don't really follow dedicated
4190 // load and prepare, anyways.
4191 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4192 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4193
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004194 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004195 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004196 }
4197 // Another thread must have loaded the class after we
4198 // started but before we finished. Abandon what we've
4199 // done.
4200 //
4201 // (Yes, this happens.)
4202
Vladimir Markobcf17522018-06-01 13:14:32 +01004203 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004204}
4205
Vladimir Marko9186b182018-11-06 14:55:54 +00004206ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4207 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004208 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004209 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4210 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4211 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4212 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4213 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4214 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4215 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4216 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4217 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004218 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004219 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004220 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004221 return GetClassRoot(class_root, this);
4222}
4223
4224ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4225 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4226 if (UNLIKELY(result == nullptr)) {
4227 std::string printable_type(PrintableChar(type));
4228 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4229 }
4230 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004231}
4232
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004233ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4234 ObjPtr<mirror::Class> klass,
4235 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004236 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004237 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004238 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004239 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004240 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004241 source += " from ";
4242 source += dex_cache->GetLocation()->ToModifiedUtf8();
4243 }
4244 LOG(INFO) << "Loaded class " << descriptor << source;
4245 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004246 {
4247 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004248 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004249 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004250 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004251 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004252 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004253 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004254 VerifyObject(klass);
4255 class_table->InsertWithHash(klass, hash);
4256 if (class_loader != nullptr) {
4257 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004258 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004259 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004260 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004261 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004262 }
4263 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004264 if (kIsDebugBuild) {
4265 // Test that copied methods correctly can find their holder.
4266 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4267 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4268 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004269 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004270 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271}
4272
Vladimir Marko1998cd02017-01-13 13:02:58 +00004273void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004274 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4275 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4276 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4277 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004278 }
4279}
4280
Alex Lighte64300b2015-12-15 15:02:47 -08004281// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004282void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004283 LengthPrefixedArray<ArtMethod>* new_methods) {
4284 klass->SetMethodsPtrUnchecked(new_methods,
4285 klass->NumDirectMethods(),
4286 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004287 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004288 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004289}
4290
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004291ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4292 const char* descriptor,
4293 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004294 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4295}
4296
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004297ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4298 const char* descriptor,
4299 size_t hash,
4300 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004301 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4302 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4303 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004304 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004305 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004306 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004307 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004308 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004309 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004310}
4311
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004312class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4313 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004314 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004315
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004316 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004317 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004318 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004319 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004320 if (class_table != nullptr) {
4321 class_table->FreezeSnapshot();
4322 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004323 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004324};
4325
4326void ClassLinker::MoveClassTableToPreZygote() {
4327 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004328 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004329 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004330 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004331}
4332
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004333// Look up classes by hash and descriptor and put all matching ones in the result array.
4334class LookupClassesVisitor : public ClassLoaderVisitor {
4335 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004336 LookupClassesVisitor(const char* descriptor,
4337 size_t hash,
4338 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004339 : descriptor_(descriptor),
4340 hash_(hash),
4341 result_(result) {}
4342
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004343 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004344 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004345 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004346 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004347 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4348 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004349 result_->push_back(klass);
4350 }
4351 }
4352
4353 private:
4354 const char* const descriptor_;
4355 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004356 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004357};
4358
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004359void ClassLinker::LookupClasses(const char* descriptor,
4360 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004361 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004362 Thread* const self = Thread::Current();
4363 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004364 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004365 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004366 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004367 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004368 result.push_back(klass);
4369 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004370 LookupClassesVisitor visitor(descriptor, hash, &result);
4371 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004372}
4373
Alex Lightf1f10492015-10-07 16:08:36 -07004374bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4375 Handle<mirror::Class> klass,
4376 Handle<mirror::Class> supertype) {
4377 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004378 DCHECK(klass != nullptr);
4379 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004380
Alex Lightf1f10492015-10-07 16:08:36 -07004381 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4382 VerifyClass(self, supertype);
4383 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004384
4385 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4386 // The supertype is either verified, or we soft failed at AOT time.
4387 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004388 return true;
4389 }
4390 // If we got this far then we have a hard failure.
4391 std::string error_msg =
4392 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004393 klass->PrettyDescriptor().c_str(),
4394 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004395 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004396 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004397 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004398 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004399 // Set during VerifyClass call (if at all).
4400 self->ClearException();
4401 }
4402 // Change into a verify error.
4403 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004404 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004405 self->GetException()->SetCause(cause.Get());
4406 }
4407 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4408 if (Runtime::Current()->IsAotCompiler()) {
4409 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4410 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004411 // Need to grab the lock to change status.
4412 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004413 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004414 return false;
4415}
4416
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004417verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004418 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004419 {
4420 // TODO: assert that the monitor on the Class is held
4421 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004422
Andreas Gampe884f3b82016-03-30 19:52:58 -07004423 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004424 ClassStatus old_status = klass->GetStatus();
4425 while (old_status == ClassStatus::kVerifying ||
4426 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004427 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004428 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4429 // case we may see the same status again. b/62912904. This is why the check is
4430 // greater or equal.
4431 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004432 << "Class '" << klass->PrettyClass()
4433 << "' performed an illegal verification state transition from " << old_status
4434 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004435 old_status = klass->GetStatus();
4436 }
jeffhao98eacac2011-09-14 16:11:53 -07004437
Andreas Gampe884f3b82016-03-30 19:52:58 -07004438 // The class might already be erroneous, for example at compile time if we attempted to verify
4439 // this class as a parent to another.
4440 if (klass->IsErroneous()) {
4441 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004442 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004443 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004444
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004445 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004446 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004447 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004448 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004449 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004450
4451 // For AOT, don't attempt to re-verify if we have already found we should
4452 // verify at runtime.
4453 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004454 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004455 }
jeffhao98eacac2011-09-14 16:11:53 -07004456
Vladimir Marko2c64a832018-01-04 11:31:56 +00004457 if (klass->GetStatus() == ClassStatus::kResolved) {
4458 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004459 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004460 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004461 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004462 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004463 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004464 }
4465
4466 // Skip verification if disabled.
4467 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004468 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004469 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004470 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004471 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004472 }
4473
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004474 VLOG(class_linker) << "Beginning verification for class: "
4475 << klass->PrettyDescriptor()
4476 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4477
Ian Rogers9ffb0392012-09-10 11:56:50 -07004478 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004479 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004480 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4481 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004482 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004483 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004484 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004485 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004486
Alex Lightf1f10492015-10-07 16:08:36 -07004487 // Verify all default super-interfaces.
4488 //
4489 // (1) Don't bother if the superclass has already had a soft verification failure.
4490 //
4491 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4492 // recursive initialization by themselves. This is because when an interface is initialized
4493 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4494 // but choose not to for an optimization. If the interfaces is being verified due to a class
4495 // initialization (which would need all the default interfaces to be verified) the class code
4496 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004497 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004498 && !klass->IsInterface()) { // See (2)
4499 int32_t iftable_count = klass->GetIfTableCount();
4500 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4501 // Loop through all interfaces this class has defined. It doesn't matter the order.
4502 for (int32_t i = 0; i < iftable_count; i++) {
4503 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004504 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004505 // We only care if we have default interfaces and can skip if we are already verified...
4506 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4507 continue;
4508 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4509 // We had a hard failure while verifying this interface. Just return immediately.
4510 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004511 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004512 } else if (UNLIKELY(!iface->IsVerified())) {
4513 // We softly failed to verify the iface. Stop checking and clean up.
4514 // Put the iface into the supertype handle so we know what caused us to fail.
4515 supertype.Assign(iface.Get());
4516 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004517 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004518 }
4519 }
4520
Alex Lightf1f10492015-10-07 16:08:36 -07004521 // At this point if verification failed, then supertype is the "first" supertype that failed
4522 // verification (without a specific order). If verification succeeded, then supertype is either
4523 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004524 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004525 supertype.Get() == klass->GetSuperClass() ||
4526 !supertype->IsVerified());
4527
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004528 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004529 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004530 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004531 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004532
4533 VLOG(class_linker) << "Class preverified status for class "
4534 << klass->PrettyDescriptor()
4535 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4536 << ": "
4537 << preverified;
4538
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004539 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4540 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004541 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4542 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004543
Ian Rogers62d6c772013-02-27 08:32:07 -08004544 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004545 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004546 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004547 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004548 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004549
4550 // Verification is done, grab the lock again.
4551 ObjectLock<mirror::Class> lock(self, klass);
4552
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004553 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4554 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004555 VLOG(class_linker) << "Soft verification failure in class "
4556 << klass->PrettyDescriptor()
4557 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4558 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004559 }
Ian Rogers1f539342012-10-03 21:09:42 -07004560 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004561 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004562 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004563 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004564 // Even though there were no verifier failures we need to respect whether the super-class and
4565 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004566 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004567 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004568 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004569 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4570 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004571 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004572 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004573 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004574 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004575 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004576 // Soft failures at compile time should be retried at runtime. Soft
4577 // failures at runtime will be handled by slow paths in the generated
4578 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004579 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004580 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004581 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004582 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004583 // As this is a fake verified status, make sure the methods are _not_ marked
4584 // kAccSkipAccessChecks later.
4585 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004586 }
4587 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004588 } else {
David Sehr709b0702016-10-13 09:12:37 -07004589 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004590 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4591 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004592 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004593 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004594 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004595 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004596 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004597 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004598 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004599 // method.
4600 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004601 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004602 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004603
4604 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4605 // Never skip access checks if the verification soft fail is forced.
4606 // Mark the class as having a verification attempt to avoid re-running the verifier.
4607 klass->SetVerificationAttempted();
4608 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004609 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004610 }
Andreas Gampe48498592014-09-10 19:48:05 -07004611 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004612 // Done verifying. Notify the compiler about the verification status, in case the class
4613 // was verified implicitly (eg super class of a compiled class).
4614 if (Runtime::Current()->IsAotCompiler()) {
4615 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4616 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4617 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004618 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004619}
4620
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004621verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4622 Handle<mirror::Class> klass,
4623 verifier::HardFailLogMode log_level,
4624 std::string* error_msg) {
4625 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004626 return verifier::ClassVerifier::VerifyClass(self,
4627 klass.Get(),
4628 runtime->GetCompilerCallbacks(),
4629 runtime->IsAotCompiler(),
4630 log_level,
4631 Runtime::Current()->GetTargetSdkVersion(),
4632 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004633}
4634
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004635bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004636 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004637 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004638 // If we're compiling, we can only verify the class using the oat file if
4639 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004640 // the compilation unit (app - dependencies). We will let the compiler callback
4641 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004642 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004643 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004644 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004645 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004646 return false;
4647 }
4648 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004649 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004650 return false;
4651 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004652 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004653
Andreas Gampeb40d3612018-06-26 15:49:42 -07004654 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004655 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004656 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004657 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4658 // For boot classpath classes in the case we're not using a default boot image:
4659 // we don't have the infrastructure yet to query verification data on individual
4660 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4661 // verified. This should be taken into account when measuring boot time and app
4662 // startup compare to the (current) production system where both:
4663 // 1) updatable boot classpath classes, and
4664 // 2) classes in /system referencing updatable classes
4665 // will be verified at runtime.
4666 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4667 oat_file_class_status = ClassStatus::kVerified;
4668 return true;
4669 }
4670 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004671 return false;
4672 }
4673
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004674 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004675 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004676 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004677 return true;
4678 }
4679 // If we only verified a subset of the classes at compile time, we can end up with classes that
4680 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004681 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004682 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004683 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004684 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004685 // Compile time verification failed with a soft error. Compile time verification can fail
4686 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004687 // class ... {
4688 // Foo x;
4689 // .... () {
4690 // if (...) {
4691 // v1 gets assigned a type of resolved class Foo
4692 // } else {
4693 // v1 gets assigned a type of unresolved class Bar
4694 // }
4695 // iput x = v1
4696 // } }
4697 // when we merge v1 following the if-the-else it results in Conflict
4698 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4699 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4700 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4701 // at compile time).
4702 return false;
4703 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004704 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004705 // Compile time verification failed with a hard error. This is caused by invalid instructions
4706 // in the class. These errors are unrecoverable.
4707 return false;
4708 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004709 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004710 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4711 // not loading the class.
4712 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4713 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004714 return false;
4715 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004716 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004717 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004718 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004719 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004720 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004721}
4722
Alex Light5a559862016-01-29 12:24:48 -08004723void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004724 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004725 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004726 }
4727}
4728
Alex Light5a559862016-01-29 12:24:48 -08004729void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004730 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004731 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004732 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004733 return; // native or abstract method
4734 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004735 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004736 return; // nothing to process
4737 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004738 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004739 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004740 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4741 CatchHandlerIterator iterator(handlers_ptr);
4742 for (; iterator.HasNext(); iterator.Next()) {
4743 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4744 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004745 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004746 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004747 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004748 DCHECK(Thread::Current()->IsExceptionPending());
4749 Thread::Current()->ClearException();
4750 }
4751 }
4752 }
4753 handlers_ptr = iterator.EndDataPointer();
4754 }
4755}
4756
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004757ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4758 jstring name,
4759 jobjectArray interfaces,
4760 jobject loader,
4761 jobjectArray methods,
4762 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004763 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004764
4765 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4766 // code to be executed. We put it up here so we can avoid all the allocations associated with
4767 // creating the class. This can happen with (eg) jit-threads.
4768 if (!self->CanLoadClasses()) {
4769 // Make sure we don't try to load anything, potentially causing an infinite loop.
4770 ObjPtr<mirror::Throwable> pre_allocated =
4771 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4772 self->SetException(pre_allocated);
4773 return nullptr;
4774 }
4775
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004776 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004777 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004778 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004779 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004780 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004781 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004782 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004783 DCHECK(temp_klass->GetClass() != nullptr);
4784 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004785 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4786 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004787 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4788 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4789 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4790 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004791 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004792 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004793 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004794 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004795 std::string storage;
4796 const char* descriptor = temp_klass->GetDescriptor(&storage);
4797 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004798
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004799 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004800 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004801
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004802 // Insert the class before loading the fields as the field roots
4803 // (ArtField::declaring_class_) are only visited from the class
4804 // table. There can't be any suspend points between inserting the
4805 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004806 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004807 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004808
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004809 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004810 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004811 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004812 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004813
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004814 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4815 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004816 ArtField& interfaces_sfield = sfields->At(0);
4817 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004818 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004819 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004820
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004821 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004822 ArtField& throws_sfield = sfields->At(1);
4823 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004824 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004825 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004826
Ian Rogers466bb252011-10-14 03:29:56 -07004827 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004828 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004829
Alex Lighte64300b2015-12-15 15:02:47 -08004830 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004831 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004832 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004833 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004834 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004835
4836 // Create the methods array.
4837 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4838 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004839 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4840 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004841 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004842 self->AssertPendingOOMException();
4843 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004844 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004845 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004846
4847 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004848 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004849
4850 // Create virtual method using specified prototypes.
4851 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004852 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004853 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004854 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004855 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004856 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4857 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004858 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004859
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004860 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004861 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004862 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004863 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004864 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004865
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004866 // At this point the class is loaded. Publish a ClassLoad event.
4867 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4868 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4869
4870 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004871 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004872 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004873 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004874 // Link the fields and virtual methods, creating vtable and iftables.
4875 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004876 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004877 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004878 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004879 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004880 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004881 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004882 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004883 CHECK(temp_klass->IsRetired());
4884 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004885
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004886 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004887 interfaces_sfield.SetObject<false>(
4888 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004889 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004890 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4891 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004892 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004893 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004894
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004895 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4896
Vladimir Marko305c38b2018-02-14 11:50:07 +00004897 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4898 // See also ClassLinker::EnsureInitialized().
4899 if (kBitstringSubtypeCheckEnabled) {
4900 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4901 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4902 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4903 }
4904
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004905 {
4906 // Lock on klass is released. Lock new class object.
4907 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004908 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004909 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004910 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004911
4912 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004913 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004914 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004915 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4916
Ian Rogersc2b44472011-12-14 21:17:17 -08004917 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004918 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4919 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004920 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004921 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004922
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004923 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004924 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004925 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004926 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004927 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004928
4929 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004930 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004931 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004932
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004933 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004934 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004935 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004936 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004937 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004938 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004939}
4940
Mathieu Chartiere401d142015-04-22 13:56:20 -07004941void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4942 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004943 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4944 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004945
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004946 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4947 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004948 ArtMethod* proxy_constructor =
4949 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004950 DCHECK(proxy_constructor != nullptr)
4951 << "Could not find <init> method in java.lang.reflect.Proxy";
4952
Jeff Haodb8a6642014-08-14 17:18:52 -07004953 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4954 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004955 DCHECK(out != nullptr);
4956 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004957 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004958 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004959 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004960 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4961 kAccPublic |
4962 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004963 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004964
4965 // Set the original constructor method.
4966 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004967}
4968
Mathieu Chartiere401d142015-04-22 13:56:20 -07004969void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004970 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004971 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4972 CHECK_STREQ(np->GetName(), "<init>");
4973 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004974 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004975}
4976
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004977void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004978 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004979 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004980 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004981 DCHECK(out != nullptr);
4982 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004983
Alex Lighte9dd04f2016-03-16 16:09:45 -07004984 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004985 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004986 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4987 // preference to the invocation handler.
4988 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4989 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004990 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4991 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004992 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4993
4994 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4995 // method they copy might (if it's a default method).
4996 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004997
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004998 // Set the original interface method.
4999 out->SetDataPtrSize(prototype, image_pointer_size_);
5000
Ian Rogers466bb252011-10-14 03:29:56 -07005001 // At runtime the method looks like a reference and argument saving method, clone the code
5002 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005003 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005004}
Jesse Wilson95caa792011-10-12 18:14:17 -04005005
Mathieu Chartiere401d142015-04-22 13:56:20 -07005006void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005007 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005008 CHECK(!prototype->IsFinal());
5009 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005010 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005011
5012 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5013 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005014 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005015 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005016}
5017
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005018bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005019 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005020 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005021 return true;
5022 }
5023 if (!can_init_statics) {
5024 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005026 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005027 return false;
5028 }
5029 // Check if there are encoded static values needing initialization.
5030 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005031 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005032 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005033 if (dex_class_def->static_values_off_ != 0) {
5034 return false;
5035 }
5036 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005037 // If we are a class we need to initialize all interfaces with default methods when we are
5038 // initialized. Check all of them.
5039 if (!klass->IsInterface()) {
5040 size_t num_interfaces = klass->GetIfTableCount();
5041 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005042 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005043 if (iface->HasDefaultMethods() &&
5044 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5045 return false;
5046 }
5047 }
5048 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005049 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005050 if (klass->IsInterface() || !klass->HasSuperClass()) {
5051 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005052 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005053 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005054 if (!can_init_parents && !super_class->IsInitialized()) {
5055 return false;
5056 }
5057 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005058}
5059
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005060bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5061 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005062 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5063
5064 // Are we already initialized and therefore done?
5065 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5066 // an initialized class will never change its state.
5067 if (klass->IsInitialized()) {
5068 return true;
5069 }
5070
5071 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005072 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005073 return false;
5074 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005075
Ian Rogers7b078e82014-09-10 14:44:24 -07005076 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005077 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005078 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005079 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005080
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005081 // Re-check under the lock in case another thread initialized ahead of us.
5082 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005083 return true;
5084 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005085
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005086 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005087 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005088 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005089 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005090 return false;
5091 }
5092
Vladimir Marko72ab6842017-01-20 19:32:50 +00005093 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5094 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005095
5096 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005097 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005098 if (!klass->IsVerified()) {
5099 // We failed to verify, expect either the klass to be erroneous or verification failed at
5100 // compile time.
5101 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005102 // The class is erroneous. This may be a verifier error, or another thread attempted
5103 // verification and/or initialization and failed. We can distinguish those cases by
5104 // whether an exception is already pending.
5105 if (self->IsExceptionPending()) {
5106 // Check that it's a VerifyError.
5107 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005108 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005109 } else {
5110 // Check that another thread attempted initialization.
5111 DCHECK_NE(0, klass->GetClinitThreadId());
5112 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5113 // Need to rethrow the previous failure now.
5114 ThrowEarlierClassFailure(klass.Get(), true);
5115 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005116 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005117 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005118 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005119 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005120 self->AssertNoPendingException();
5121 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005122 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005123 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005124 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005125 } else {
5126 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005127 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005128
5129 // A separate thread could have moved us all the way to initialized. A "simple" example
5130 // involves a subclass of the current class being initialized at the same time (which
5131 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005132 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005133 if (klass->IsInitialized()) {
5134 return true;
5135 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005136 }
5137
Vladimir Marko2c64a832018-01-04 11:31:56 +00005138 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005139 // initializing higher up the stack or another thread has beat us
5140 // to initializing and we need to wait. Either way, this
5141 // invocation of InitializeClass will not be responsible for
5142 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005143 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005144 // Could have got an exception during verification.
5145 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005146 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005147 return false;
5148 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005149 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005150 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005151 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005152 return true;
5153 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005154 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005155 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005156 }
5157
Jeff Haoe2e40342017-07-19 10:45:18 -07005158 // Try to get the oat class's status for this class if the oat file is present. The compiler
5159 // tries to validate superclass descriptors, and writes the result into the oat file.
5160 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5161 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5162 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005163 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005164 const Runtime* runtime = Runtime::Current();
5165 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5166 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5167 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005168 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005169 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005170 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005171 return false;
5172 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005173 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005174
Vladimir Marko2c64a832018-01-04 11:31:56 +00005175 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005176 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005177
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005178 // From here out other threads may observe that we're initializing and so changes of state
5179 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005180 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005181 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005182
5183 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005184 }
5185
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005186 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005187 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005188 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005189 if (!super_class->IsInitialized()) {
5190 CHECK(!super_class->IsInterface());
5191 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005192 StackHandleScope<1> hs(self);
5193 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005194 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005195 if (!super_initialized) {
5196 // The super class was verified ahead of entering initializing, we should only be here if
5197 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005198 // For the case of aot compiler, the super class might also be initializing but we don't
5199 // want to process circular dependencies in pre-compile.
5200 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005201 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005202 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005203 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005204 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005205 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005206 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005207 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005208 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005209 return false;
5210 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005211 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005212 }
5213
Alex Lighteb7c1442015-08-31 13:17:42 -07005214 if (!klass->IsInterface()) {
5215 // Initialize interfaces with default methods for the JLS.
5216 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005217 // Only setup the (expensive) handle scope if we actually need to.
5218 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005219 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005220 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5221 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005222 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005223 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005224 CHECK(handle_scope_iface->IsInterface());
5225 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5226 // We have already done this for this interface. Skip it.
5227 continue;
5228 }
5229 // We cannot just call initialize class directly because we need to ensure that ALL
5230 // interfaces with default methods are initialized. Non-default interface initialization
5231 // will not affect other non-default super-interfaces.
5232 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5233 handle_scope_iface,
5234 can_init_statics,
5235 can_init_parents);
5236 if (!iface_initialized) {
5237 ObjectLock<mirror::Class> lock(self, klass);
5238 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005239 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005240 return false;
5241 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005242 }
5243 }
5244 }
5245
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005246 const size_t num_static_fields = klass->NumStaticFields();
5247 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005248 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005249 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005250 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005251 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005252 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005253
5254 // Eagerly fill in static fields so that the we don't have to do as many expensive
5255 // Class::FindStaticField in ResolveField.
5256 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005257 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005258 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005259 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005260 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005261 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005262 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5263 field,
5264 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5265 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005266 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005267 } else {
5268 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005269 }
5270 }
5271
Vladimir Markoe11dd502017-12-08 14:09:45 +00005272 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5273 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005274 this,
5275 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005276 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005277
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005278 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005279 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005280 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005281 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5282 if (!value_it.HasNext()) {
5283 break;
5284 }
5285 ArtField* art_field = ResolveField(field.GetIndex(),
5286 dex_cache,
5287 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005288 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005289 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005290 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005291 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005292 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005293 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005294 if (self->IsExceptionPending()) {
5295 break;
5296 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005297 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005298 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005299 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005300 }
5301 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005302
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005303
Mathieu Chartierda595be2016-08-10 13:57:39 -07005304 if (!self->IsExceptionPending()) {
5305 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5306 if (clinit != nullptr) {
5307 CHECK(can_init_statics);
5308 JValue result;
5309 clinit->Invoke(self, nullptr, 0, &result, "V");
5310 }
5311 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005312 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005313 uint64_t t1 = NanoTime();
5314
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005315 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005316 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005317 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005318
5319 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005320 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005321 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005322 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005323 } else if (Runtime::Current()->IsTransactionAborted()) {
5324 // The exception thrown when the transaction aborted has been caught and cleared
5325 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005326 VLOG(compiler) << "Return from class initializer of "
5327 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005328 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005329 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005330 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005331 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005332 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005333 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5334 RuntimeStats* thread_stats = self->GetStats();
5335 ++global_stats->class_init_count;
5336 ++thread_stats->class_init_count;
5337 global_stats->class_init_time_ns += (t1 - t0);
5338 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005339 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005340 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005341 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005342 std::string temp;
5343 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005344 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005345 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005346 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005347 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005348 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005349 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005350 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005351}
5352
Alex Lighteb7c1442015-08-31 13:17:42 -07005353// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5354// and perform the initialization only on those interfaces that contain default methods.
5355bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5356 Handle<mirror::Class> iface,
5357 bool can_init_statics,
5358 bool can_init_parents) {
5359 CHECK(iface->IsInterface());
5360 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005361 // Only create the (expensive) handle scope if we need it.
5362 if (UNLIKELY(num_direct_ifaces > 0)) {
5363 StackHandleScope<1> hs(self);
5364 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5365 // First we initialize all of iface's super-interfaces recursively.
5366 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005367 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005368 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005369 if (!super_iface->HasBeenRecursivelyInitialized()) {
5370 // Recursive step
5371 handle_super_iface.Assign(super_iface);
5372 if (!InitializeDefaultInterfaceRecursive(self,
5373 handle_super_iface,
5374 can_init_statics,
5375 can_init_parents)) {
5376 return false;
5377 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005378 }
5379 }
5380 }
5381
5382 bool result = true;
5383 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5384 // initialize if we don't have default methods.
5385 if (iface->HasDefaultMethods()) {
5386 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5387 }
5388
5389 // Mark that this interface has undergone recursive default interface initialization so we know we
5390 // can skip it on any later class initializations. We do this even if we are not a default
5391 // interface since we can still avoid the traversal. This is purely a performance optimization.
5392 if (result) {
5393 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005394 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5395 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5396 // initialization is a performance optimization (to avoid another idempotent visit
5397 // for other implementing classes/interfaces), and can be revisited later.
5398 ObjectTryLock<mirror::Class> lock(self, iface);
5399 if (lock.Acquired()) {
5400 iface->SetRecursivelyInitialized();
5401 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005402 }
5403 return result;
5404}
5405
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005406bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5407 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005408 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005409 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005410 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005411 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005412 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005413 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005414
5415 // When we wake up, repeat the test for init-in-progress. If
5416 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005417 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005418 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005419 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005420 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005421 return false;
5422 }
5423 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005424 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005425 continue;
5426 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005427 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005428 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005429 // Compile time initialization failed.
5430 return false;
5431 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005432 if (klass->IsErroneous()) {
5433 // The caller wants an exception, but it was thrown in a
5434 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005435 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005436 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005437 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005438 return false;
5439 }
5440 if (klass->IsInitialized()) {
5441 return true;
5442 }
David Sehr709b0702016-10-13 09:12:37 -07005443 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005444 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005445 }
Ian Rogers07140832014-09-30 15:43:59 -07005446 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005447}
5448
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005449static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5450 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005451 ArtMethod* method,
5452 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005453 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005454 DCHECK(Thread::Current()->IsExceptionPending());
5455 DCHECK(!m->IsProxyMethod());
5456 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005457 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5458 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005459 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005460 std::string return_type = dex_file->PrettyType(return_type_idx);
5461 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005462 ThrowWrappedLinkageError(klass.Get(),
5463 "While checking class %s method %s signature against %s %s: "
5464 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005465 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5466 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005467 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005468 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005469 return_type.c_str(), class_loader.c_str());
5470}
5471
5472static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5473 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005474 ArtMethod* method,
5475 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005476 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005477 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005478 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005479 DCHECK(Thread::Current()->IsExceptionPending());
5480 DCHECK(!m->IsProxyMethod());
5481 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005482 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5483 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005484 ThrowWrappedLinkageError(klass.Get(),
5485 "While checking class %s method %s signature against %s %s: "
5486 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005487 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5488 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005489 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005490 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005491 index, arg_type.c_str(), class_loader.c_str());
5492}
5493
5494static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5495 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005496 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005497 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005498 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005499 ThrowLinkageError(klass.Get(),
5500 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005501 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5502 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005503 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005504 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005505 error_msg.c_str());
5506}
5507
Ian Rogersb5fb2072014-12-02 17:22:02 -08005508static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005509 Handle<mirror::Class> klass,
5510 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005511 ArtMethod* method1,
5512 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005513 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005514 {
5515 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005516 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005517 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005518 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005519 return false;
5520 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005521 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005522 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005523 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005524 return false;
5525 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005526 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005527 ThrowSignatureMismatch(klass, super_klass, method1,
5528 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005529 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005530 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005531 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005532 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005533 return false;
5534 }
5535 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005536 const dex::TypeList* types1 = method1->GetParameterTypeList();
5537 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005538 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005539 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005540 ThrowSignatureMismatch(klass, super_klass, method1,
5541 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005542 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005543 return false;
5544 }
5545 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005546 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005547 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005548 ThrowSignatureMismatch(klass, super_klass, method1,
5549 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005550 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005551 return false;
5552 }
5553 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005554 }
5555 uint32_t num_types = types1->Size();
5556 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005557 ThrowSignatureMismatch(klass, super_klass, method1,
5558 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005559 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005560 return false;
5561 }
5562 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005563 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005564 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005565 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005566 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005567 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005568 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005569 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005570 return false;
5571 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005572 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005573 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005574 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005575 if (UNLIKELY(other_param_type == nullptr)) {
5576 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005577 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005578 return false;
5579 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005580 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005581 ThrowSignatureMismatch(klass, super_klass, method1,
5582 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5583 i,
David Sehr709b0702016-10-13 09:12:37 -07005584 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005585 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005586 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005587 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005588 return false;
5589 }
5590 }
5591 return true;
5592}
5593
5594
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005595bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005596 if (klass->IsInterface()) {
5597 return true;
5598 }
Ian Rogers151f2212014-05-06 11:27:27 -07005599 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005600 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005601 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005602 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005603 if (klass->HasSuperClass() &&
5604 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005605 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005606 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005607 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5608 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5609 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005610 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5611 klass,
5612 super_klass,
5613 m,
5614 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005615 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005616 return false;
5617 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005618 }
5619 }
5620 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005621 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005622 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5623 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5624 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005625 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005626 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5627 j, image_pointer_size_);
5628 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5629 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005630 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5631 klass,
5632 super_klass,
5633 m,
5634 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005635 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005636 return false;
5637 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005638 }
5639 }
5640 }
5641 }
5642 return true;
5643}
5644
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005645bool ClassLinker::EnsureInitialized(Thread* self,
5646 Handle<mirror::Class> c,
5647 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005648 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005649 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005650
Mathieu Chartier524507a2014-08-27 15:28:28 -07005651 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005652 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005653 return true;
5654 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005655 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5656 //
5657 // Ensure the bitstring is initialized before any of the class initialization
5658 // logic occurs. Once a class initializer starts running, objects can
5659 // escape into the heap and use the subtype checking code.
5660 //
5661 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5662 // can be used as a source for the IsSubClass check, and that all ancestors
5663 // of the class are Assigned (can be used as a target for IsSubClass check)
5664 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005665 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005666 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005667 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005668 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5669 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005670 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005671 if (!success) {
5672 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005673 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005674 }
5675 } else {
5676 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005677 }
5678 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005679}
5680
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005681void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5682 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005683 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005684 for (ArtField& field : new_class->GetIFields()) {
5685 if (field.GetDeclaringClass() == temp_class) {
5686 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005687 }
5688 }
5689
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005690 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005691 for (ArtField& field : new_class->GetSFields()) {
5692 if (field.GetDeclaringClass() == temp_class) {
5693 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005694 }
5695 }
5696
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005697 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005698 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005699 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005700 if (method.GetDeclaringClass() == temp_class) {
5701 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005702 }
5703 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005704
5705 // Make sure the remembered set and mod-union tables know that we updated some of the native
5706 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005707 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005708}
5709
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005710void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005711 CHECK(class_loader->GetAllocator() == nullptr);
5712 CHECK(class_loader->GetClassTable() == nullptr);
5713 Thread* const self = Thread::Current();
5714 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005715 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005716 // Create and set the class table.
5717 data.class_table = new ClassTable;
5718 class_loader->SetClassTable(data.class_table);
5719 // Create and set the linear allocator.
5720 data.allocator = Runtime::Current()->CreateLinearAlloc();
5721 class_loader->SetAllocator(data.allocator);
5722 // Add to the list so that we know to free the data later.
5723 class_loaders_.push_back(data);
5724}
5725
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005726ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005727 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005728 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005729 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005730 ClassTable* class_table = class_loader->GetClassTable();
5731 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005732 RegisterClassLoader(class_loader);
5733 class_table = class_loader->GetClassTable();
5734 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005735 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005736 return class_table;
5737}
5738
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005739ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005740 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005741}
5742
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005743static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005744 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005745 while (klass->HasSuperClass()) {
5746 klass = klass->GetSuperClass();
5747 if (klass->ShouldHaveImt()) {
5748 return klass->GetImt(pointer_size);
5749 }
5750 }
5751 return nullptr;
5752}
5753
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005754bool ClassLinker::LinkClass(Thread* self,
5755 const char* descriptor,
5756 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005757 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005758 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005759 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005760
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005761 if (!LinkSuperClass(klass)) {
5762 return false;
5763 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005764 ArtMethod* imt_data[ImTable::kSize];
5765 // If there are any new conflicts compared to super class.
5766 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005767 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005768 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005769 return false;
5770 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005771 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005772 return false;
5773 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005774 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005775 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005776 return false;
5777 }
5778 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005779 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005780
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005781 ImTable* imt = nullptr;
5782 if (klass->ShouldHaveImt()) {
5783 // If there are any new conflicts compared to the super class we can not make a copy. There
5784 // can be cases where both will have a conflict method at the same slot without having the same
5785 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5786 // will possibly create a table that is incorrect for either of the classes.
5787 // Same IMT with new_conflict does not happen very often.
5788 if (!new_conflict) {
5789 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5790 if (super_imt != nullptr) {
5791 bool imt_equals = true;
5792 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5793 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5794 }
5795 if (imt_equals) {
5796 imt = super_imt;
5797 }
5798 }
5799 }
5800 if (imt == nullptr) {
5801 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5802 imt = reinterpret_cast<ImTable*>(
5803 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5804 if (imt == nullptr) {
5805 return false;
5806 }
5807 imt->Populate(imt_data, image_pointer_size_);
5808 }
5809 }
5810
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005811 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5812 // We don't need to retire this class as it has no embedded tables or it was created the
5813 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005814 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005815
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005816 if (klass->ShouldHaveEmbeddedVTable()) {
5817 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005818 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005819 if (klass->ShouldHaveImt()) {
5820 klass->SetImt(imt, image_pointer_size_);
5821 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005822
5823 // Update CHA info based on whether we override methods.
5824 // Have to do this before setting the class as resolved which allows
5825 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005826 if (cha_ != nullptr) {
5827 cha_->UpdateAfterLoadingOf(klass);
5828 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005829
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005830 // This will notify waiters on klass that saw the not yet resolved
5831 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005832 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005833 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005834 } else {
5835 CHECK(!klass->IsResolved());
5836 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005837 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005838 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005839 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5840 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5841 // may not see any references to the target space and clean the card for a class if another
5842 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005843 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005844 klass->SetSFieldsPtrUnchecked(nullptr);
5845 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005846 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005847 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005848 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005849 return false;
5850 }
5851
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005852 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5853 ObjectLock<mirror::Class> lock(self, h_new_class);
5854 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005855
5856 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005857 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005858 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005859 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005860 const ObjPtr<mirror::Class> existing =
5861 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005862 if (class_loader != nullptr) {
5863 // We updated the class in the class table, perform the write barrier so that the GC knows
5864 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005865 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005866 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005867 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005868 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005869 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5870 }
5871 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005872
Mingyao Yang063fc772016-08-02 11:02:54 -07005873 // Update CHA info based on whether we override methods.
5874 // Have to do this before setting the class as resolved which allows
5875 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005876 if (cha_ != nullptr) {
5877 cha_->UpdateAfterLoadingOf(h_new_class);
5878 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005879
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005880 // This will notify waiters on temp class that saw the not yet resolved class in the
5881 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005882 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005883
Vladimir Marko2c64a832018-01-04 11:31:56 +00005884 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005885 // This will notify waiters on new_class that saw the not yet resolved
5886 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005887 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005888 // Return the new class.
5889 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005890 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005891 return true;
5892}
5893
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005894bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005895 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005896 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005897 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5898 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005899 // Check that a class does not inherit from itself directly.
5900 //
5901 // TODO: This is a cheap check to detect the straightforward case
5902 // of a class extending itself (b/28685551), but we should do a
5903 // proper cycle detection on loaded classes, to detect all cases
5904 // of class circularity errors (b/28830038).
5905 if (super_class_idx == class_def.class_idx_) {
5906 ThrowClassCircularityError(klass.Get(),
5907 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005908 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005909 return false;
5910 }
5911
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005912 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005913 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005914 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005915 return false;
5916 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005917 // Verify
5918 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005919 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005920 super_class->PrettyDescriptor().c_str(),
5921 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005922 return false;
5923 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005924 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005925 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005926 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005927 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005928 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005929 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005930 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005931 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005932 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005933 DCHECK(Thread::Current()->IsExceptionPending());
5934 return false;
5935 }
5936 // Verify
5937 if (!klass->CanAccess(interface)) {
5938 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005939 ThrowIllegalAccessError(klass.Get(),
5940 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005941 interface->PrettyDescriptor().c_str(),
5942 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005943 return false;
5944 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005945 }
5946 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005947 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005948 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005949 return true;
5950}
5951
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005952bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005953 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005954 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005955 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5956 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005957 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005958 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005959 return false;
5960 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005961 return true;
5962 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005963 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005964 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005965 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005966 return false;
5967 }
5968 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005969 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005970 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5971 return false;
5972 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005973 if (super->IsFinal()) {
5974 ThrowVerifyError(klass.Get(),
5975 "Superclass %s of %s is declared final",
5976 super->PrettyDescriptor().c_str(),
5977 klass->PrettyDescriptor().c_str());
5978 return false;
5979 }
5980 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005981 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005982 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005983 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005984 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005985 return false;
5986 }
5987 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005988 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005989 super->PrettyDescriptor().c_str(),
5990 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005991 return false;
5992 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005993
Brian Carlstromf3632832014-05-20 15:36:53 -07005994 // Inherit kAccClassIsFinalizable from the superclass in case this
5995 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005996 if (super->IsFinalizable()) {
5997 klass->SetFinalizable();
5998 }
5999
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006000 // Inherit class loader flag form super class.
6001 if (super->IsClassLoaderClass()) {
6002 klass->SetClassLoaderClass();
6003 }
6004
Elliott Hughes2da50362011-10-10 16:57:08 -07006005 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006006 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006007 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006008 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006009 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006010 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006011 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006012 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006013 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006014 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006015 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006016 return false;
6017 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006018
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006019 if (kIsDebugBuild) {
6020 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006021 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006022 CHECK(super->IsResolved());
6023 super = super->GetSuperClass();
6024 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006025 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006026 return true;
6027}
6028
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006029// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006030bool ClassLinker::LinkMethods(Thread* self,
6031 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006032 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006033 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006034 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006035 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006036 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6037 // need to have default methods be in the virtuals array of each class but we don't set that up
6038 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006039 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006040 // Link virtual methods then interface methods.
6041 // We set up the interface lookup table first because we need it to determine if we need to update
6042 // any vtable entries with new default method implementations.
6043 return SetupInterfaceLookupTable(self, klass, interfaces)
6044 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006045 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006046}
6047
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006048// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6049// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6050// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006051class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006052 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006053 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006054 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006055 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6056 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006057 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006058 }
6059
6060 const char* GetName() {
6061 if (name_ == nullptr) {
6062 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6063 }
6064 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006065 }
6066
Mathieu Chartiere401d142015-04-22 13:56:20 -07006067 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006068 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006069 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006070 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006071 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006072 if (dex_file_ == other_dex_file) {
6073 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6074 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006075 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006076 uint32_t other_name_len;
6077 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6078 &other_name_len);
6079 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6080 return false;
6081 }
6082 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6083 }
6084
6085 private:
6086 // Dex file for the method to compare against.
6087 const DexFile* const dex_file_;
6088 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006089 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006090 // Lazily computed name from the dex file's strings.
6091 const char* name_;
6092 // Lazily computed name length.
6093 uint32_t name_len_;
6094};
6095
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006096class LinkVirtualHashTable {
6097 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006098 LinkVirtualHashTable(Handle<mirror::Class> klass,
6099 size_t hash_size,
6100 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006101 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006102 : klass_(klass),
6103 hash_size_(hash_size),
6104 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006105 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006106 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6107 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006108
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006109 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006110 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6111 virtual_method_index, image_pointer_size_);
6112 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006113 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006114 uint32_t index = hash % hash_size_;
6115 // Linear probe until we have an empty slot.
6116 while (hash_table_[index] != invalid_index_) {
6117 if (++index == hash_size_) {
6118 index = 0;
6119 }
6120 }
6121 hash_table_[index] = virtual_method_index;
6122 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006123
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006124 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006125 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006126 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006127 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006128 size_t index = hash % hash_size_;
6129 while (true) {
6130 const uint32_t value = hash_table_[index];
6131 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6132 // the block and can safely assume not found.
6133 if (value == invalid_index_) {
6134 break;
6135 }
6136 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006137 ArtMethod* virtual_method =
6138 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6139 if (comparator->HasSameNameAndSignature(
6140 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006141 hash_table_[index] = removed_index_;
6142 return value;
6143 }
6144 }
6145 if (++index == hash_size_) {
6146 index = 0;
6147 }
6148 }
6149 return GetNotFoundIndex();
6150 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006151
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006152 static uint32_t GetNotFoundIndex() {
6153 return invalid_index_;
6154 }
6155
6156 private:
6157 static const uint32_t invalid_index_;
6158 static const uint32_t removed_index_;
6159
6160 Handle<mirror::Class> klass_;
6161 const size_t hash_size_;
6162 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006163 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006164};
6165
6166const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6167const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6168
Stephen Hines1ddd9132017-02-08 01:51:18 -08006169bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006170 Thread* self,
6171 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006172 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006173 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006174 if (klass->IsInterface()) {
6175 // No vtable.
6176 if (!IsUint<16>(num_virtual_methods)) {
6177 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6178 return false;
6179 }
6180 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006181 // Assign each method an IMT index and set the default flag.
6182 for (size_t i = 0; i < num_virtual_methods; ++i) {
6183 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6184 m->SetMethodIndex(i);
6185 if (!m->IsAbstract()) {
6186 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6187 has_defaults = true;
6188 }
6189 }
6190 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6191 // during initialization. This is a performance optimization. We could simply traverse the
6192 // virtual_methods_ array again during initialization.
6193 if (has_defaults) {
6194 klass->SetHasDefaultMethods();
6195 }
6196 return true;
6197 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006198 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6199 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006200 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006201 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006202 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006203 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006204 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006205 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006206 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006207 return false;
6208 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006209 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006210 vtable->SetElementPtrSize(
6211 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006212 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006213 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6214 // might give us new default methods). If no new interfaces then we can skip the rest since
6215 // the class cannot override any of the super-class's methods. This is required for
6216 // correctness since without it we might not update overridden default method vtable entries
6217 // correctly.
6218 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006219 klass->SetVTable(vtable.Get());
6220 return true;
6221 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006222 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006223 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Markoc524e9e2019-03-26 10:54:50 +00006224 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006225 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006226 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6227 // might give us new default methods). See comment above.
6228 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006229 klass->SetVTable(super_vtable);
6230 return true;
6231 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006232 vtable = hs.NewHandle(
6233 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006234 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006235 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006236 return false;
6237 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006238 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006239 // How the algorithm works:
6240 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6241 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6242 // method which has not been matched to a vtable method, and j if the virtual method at the
6243 // index overrode the super virtual method at index j.
6244 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6245 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6246 // the need for the initial vtable which we later shrink back down).
6247 // 3. Add non overridden methods to the end of the vtable.
6248 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006249 // + 1 so that even if we only have new default methods we will still be able to use this hash
6250 // table (i.e. it will never have 0 size).
6251 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006252 uint32_t* hash_table_ptr;
6253 std::unique_ptr<uint32_t[]> hash_heap_storage;
6254 if (hash_table_size <= kMaxStackHash) {
6255 hash_table_ptr = reinterpret_cast<uint32_t*>(
6256 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6257 } else {
6258 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6259 hash_table_ptr = hash_heap_storage.get();
6260 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006261 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006262 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006263 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006264 DCHECK(klass->GetVirtualMethodDuringLinking(
6265 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006266 hash_table.Add(i);
6267 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006268 // 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 -07006269 // the hash table.
6270 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006271 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006272 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006273 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6274 super_method->GetAccessFlags())) {
6275 // Continue on to the next method since this one is package private and canot be overridden.
6276 // Before Android 4.1, the package-private method super_method might have been incorrectly
6277 // overridden.
6278 continue;
6279 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006280 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006281 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006282 // We remove the method so that subsequent lookups will be faster by making the hash-map
6283 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006284 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6285 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006286 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6287 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006288 if (super_method->IsFinal()) {
6289 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6290 virtual_method->PrettyMethod().c_str(),
6291 super_method->GetDeclaringClassDescriptor());
6292 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006293 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006294 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6295 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006296 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006297 // We didn't directly override this method but we might through default methods...
6298 // Check for default method update.
6299 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006300 switch (FindDefaultMethodImplementation(self,
6301 super_method,
6302 klass,
6303 /*out*/&default_method)) {
6304 case DefaultMethodSearchResult::kDefaultConflict: {
6305 // A conflict was found looking for default methods. Note this (assuming it wasn't
6306 // pre-existing) in the translations map.
6307 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6308 // Don't generate another conflict method to reduce memory use as an optimization.
6309 default_translations->insert(
6310 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6311 }
6312 break;
6313 }
6314 case DefaultMethodSearchResult::kAbstractFound: {
6315 // No conflict but method is abstract.
6316 // We note that this vtable entry must be made abstract.
6317 if (UNLIKELY(!super_method->IsAbstract())) {
6318 default_translations->insert(
6319 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6320 }
6321 break;
6322 }
6323 case DefaultMethodSearchResult::kDefaultFound: {
6324 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6325 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6326 // Found a default method implementation that is new.
6327 // TODO Refactor this add default methods to virtuals here and not in
6328 // LinkInterfaceMethods maybe.
6329 // The problem is default methods might override previously present
6330 // default-method or miranda-method vtable entries from the superclass.
6331 // Unfortunately we need these to be entries in this class's virtuals. We do not
6332 // give these entries there until LinkInterfaceMethods so we pass this map around
6333 // to let it know which vtable entries need to be updated.
6334 // Make a note that vtable entry j must be updated, store what it needs to be updated
6335 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6336 // then.
6337 default_translations->insert(
6338 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006339 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6340 << " overridden by default "
6341 << default_method->PrettyMethod()
6342 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006343 }
6344 break;
6345 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006346 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006347 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006348 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006349 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006350 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006351 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006352 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006353 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6354 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006355 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006356 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006357 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006358 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006359 local_method->SetMethodIndex(actual_count);
6360 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006361 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006362 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006363 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006364 return false;
6365 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006366 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006367 CHECK_LE(actual_count, max_count);
6368 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006369 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006370 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006371 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006372 return false;
6373 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006374 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006375 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006376 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006377 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006378 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006379 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6380 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006381 return false;
6382 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006383 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006384 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006385 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006386 return false;
6387 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006388 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006389 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6390 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006391 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006392 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006393 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006394 }
6395 return true;
6396}
6397
Alex Light9139e002015-10-09 15:59:48 -07006398// Determine if the given iface has any subinterface in the given list that declares the method
6399// specified by 'target'.
6400//
6401// Arguments
6402// - self: The thread we are running on
6403// - target: A comparator that will match any method that overrides the method we are checking for
6404// - iftable: The iftable we are searching for an overriding method on.
6405// - ifstart: The index of the interface we are checking to see if anything overrides
6406// - iface: The interface we are checking to see if anything overrides.
6407// - image_pointer_size:
6408// The image pointer size.
6409//
6410// Returns
6411// - True: There is some method that matches the target comparator defined in an interface that
6412// is a subtype of iface.
6413// - False: There is no method that matches the target comparator in any interface that is a subtype
6414// of iface.
6415static bool ContainsOverridingMethodOf(Thread* self,
6416 MethodNameAndSignatureComparator& target,
6417 Handle<mirror::IfTable> iftable,
6418 size_t ifstart,
6419 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006420 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006421 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006422 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006423 DCHECK(iface != nullptr);
6424 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006425 DCHECK_GE(ifstart, 0u);
6426 DCHECK_LT(ifstart, iftable->Count());
6427 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6428 DCHECK(iface->IsInterface());
6429
6430 size_t iftable_count = iftable->Count();
6431 StackHandleScope<1> hs(self);
6432 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6433 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6434 // Skip ifstart since our current interface obviously cannot override itself.
6435 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006436 // Iterate through every method on this interface. The order does not matter.
6437 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006438 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006439 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006440 // Check if the i'th interface is a subtype of this one.
6441 if (iface->IsAssignableFrom(current_iface.Get())) {
6442 return true;
6443 }
6444 break;
6445 }
6446 }
6447 }
6448 return false;
6449}
6450
Alex Lighteb7c1442015-08-31 13:17:42 -07006451// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006452// out_default_method and returns kDefaultFound on success. If no default method was found return
6453// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6454// default_method conflict) it will return kDefaultConflict.
6455ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6456 Thread* self,
6457 ArtMethod* target_method,
6458 Handle<mirror::Class> klass,
6459 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006460 DCHECK(self != nullptr);
6461 DCHECK(target_method != nullptr);
6462 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006463
6464 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006465
6466 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6467 // table. This lets us walk the table backwards when searching for default methods. The first one
6468 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6469 // track of it and then continue checking all other interfaces, since we need to throw an error if
6470 // we encounter conflicting default method implementations (one is not a subtype of the other).
6471 //
6472 // The order of unrelated interfaces does not matter and is not defined.
6473 size_t iftable_count = klass->GetIfTableCount();
6474 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006475 // No interfaces. We have already reset out to null so just return kAbstractFound.
6476 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006477 }
6478
Alex Light9139e002015-10-09 15:59:48 -07006479 StackHandleScope<3> hs(self);
6480 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006481 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006482 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006483 MethodNameAndSignatureComparator target_name_comparator(
6484 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6485 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006486 for (size_t k = iftable_count; k != 0; ) {
6487 --k;
6488
Alex Lighteb7c1442015-08-31 13:17:42 -07006489 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006490
6491 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006492 // Iterate through every declared method on this interface. The order does not matter.
6493 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6494 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006495 // Skip abstract methods and methods with different names.
6496 if (current_method->IsAbstract() ||
6497 !target_name_comparator.HasSameNameAndSignature(
6498 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6499 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006500 } else if (!current_method->IsPublic()) {
6501 // The verifier should have caught the non-public method for dex version 37. Just warn and
6502 // skip it since this is from before default-methods so we don't really need to care that it
6503 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006504 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6505 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006506 << "This will be a fatal error in subsequent versions of android. "
6507 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006508 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006509 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006510 // We have multiple default impls of the same method. This is a potential default conflict.
6511 // We need to check if this possibly conflicting method is either a superclass of the chosen
6512 // default implementation or is overridden by a non-default interface method. In either case
6513 // there is no conflict.
6514 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6515 !ContainsOverridingMethodOf(self,
6516 target_name_comparator,
6517 iftable,
6518 k,
6519 iface,
6520 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006521 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006522 << current_method->PrettyMethod() << " and "
6523 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6524 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006525 *out_default_method = nullptr;
6526 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006527 } else {
6528 break; // Continue checking at the next interface.
6529 }
6530 } else {
Alex Light9139e002015-10-09 15:59:48 -07006531 // chosen_iface == null
6532 if (!ContainsOverridingMethodOf(self,
6533 target_name_comparator,
6534 iftable,
6535 k,
6536 iface,
6537 image_pointer_size_)) {
6538 // Don't set this as the chosen interface if something else is overriding it (because that
6539 // other interface would be potentially chosen instead if it was default). If the other
6540 // interface was abstract then we wouldn't select this interface as chosen anyway since
6541 // the abstract method masks it.
6542 *out_default_method = current_method;
6543 chosen_iface.Assign(iface.Get());
6544 // We should now finish traversing the graph to find if we have default methods that
6545 // conflict.
6546 } else {
David Sehr709b0702016-10-13 09:12:37 -07006547 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6548 << "' was "
6549 << "skipped because it was overridden by an abstract method in a "
6550 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006551 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006552 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006553 break;
6554 }
6555 }
Alex Light9139e002015-10-09 15:59:48 -07006556 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006557 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6558 << "' selected "
6559 << "as the implementation for '" << target_method->PrettyMethod()
6560 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006561 return DefaultMethodSearchResult::kDefaultFound;
6562 } else {
6563 return DefaultMethodSearchResult::kAbstractFound;
6564 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006565}
6566
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006567ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006568 ArtMethod* conflict_method,
6569 ArtMethod* interface_method,
6570 ArtMethod* method,
6571 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006572 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006573 Runtime* const runtime = Runtime::Current();
6574 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6575 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6576
6577 // Create a new entry if the existing one is the shared conflict method.
6578 ArtMethod* new_conflict_method = new_entry
6579 ? runtime->CreateImtConflictMethod(linear_alloc)
6580 : conflict_method;
6581
6582 // Allocate a new table. Note that we will leak this table at the next conflict,
6583 // but that's a tradeoff compared to making the table fixed size.
6584 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006585 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6586 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006587 if (data == nullptr) {
6588 LOG(ERROR) << "Failed to allocate conflict table";
6589 return conflict_method;
6590 }
6591 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6592 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006593 method,
6594 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006595
6596 // Do a fence to ensure threads see the data in the table before it is assigned
6597 // to the conflict method.
6598 // Note that there is a race in the presence of multiple threads and we may leak
6599 // memory from the LinearAlloc, but that's a tradeoff compared to using
6600 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006601 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006602 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006603 return new_conflict_method;
6604}
6605
Vladimir Marko921094a2017-01-12 18:37:06 +00006606bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6607 Handle<mirror::Class> klass,
6608 Handle<mirror::IfTable> iftable) {
6609 DCHECK(!klass->IsInterface());
6610 const bool has_superclass = klass->HasSuperClass();
6611 const bool extend_super_iftable = has_superclass;
6612 const size_t ifcount = klass->GetIfTableCount();
6613 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6614 for (size_t i = 0; i < ifcount; ++i) {
6615 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6616 if (num_methods > 0) {
6617 const bool is_super = i < super_ifcount;
6618 // This is an interface implemented by a super-class. Therefore we can just copy the method
6619 // array from the superclass.
6620 const bool super_interface = is_super && extend_super_iftable;
6621 ObjPtr<mirror::PointerArray> method_array;
6622 if (super_interface) {
6623 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6624 DCHECK(if_table != nullptr);
6625 DCHECK(if_table->GetMethodArray(i) != nullptr);
6626 // If we are working on a super interface, try extending the existing method array.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00006627 method_array = ObjPtr<mirror::PointerArray>::DownCast(
6628 if_table->GetMethodArray(i)->Clone(self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006629 } else {
6630 method_array = AllocPointerArray(self, num_methods);
6631 }
6632 if (UNLIKELY(method_array == nullptr)) {
6633 self->AssertPendingOOMException();
6634 return false;
6635 }
6636 iftable->SetMethodArray(i, method_array);
6637 }
6638 }
6639 return true;
6640}
6641
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006642void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6643 ArtMethod* imt_conflict_method,
6644 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006645 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006646 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006647 // Place method in imt if entry is empty, place conflict otherwise.
6648 if (*imt_ref == unimplemented_method) {
6649 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006650 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006651 // If we are not a conflict and we have the same signature and name as the imt
6652 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006653 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6654 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006655 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006656 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006657 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006658 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006659 *imt_ref = current_method;
6660 } else {
Alex Light9139e002015-10-09 15:59:48 -07006661 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006662 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006663 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006664 } else {
6665 // Place the default conflict method. Note that there may be an existing conflict
6666 // method in the IMT, but it could be one tailored to the super class, with a
6667 // specific ImtConflictTable.
6668 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006669 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006670 }
6671}
6672
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006673void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006674 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6675 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006676 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006677 Runtime* const runtime = Runtime::Current();
6678 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6679 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006680 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006681 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006682 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006683 FillIMTFromIfTable(klass->GetIfTable(),
6684 unimplemented_method,
6685 conflict_method,
6686 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006687 /*create_conflict_tables=*/true,
6688 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006689 &new_conflict,
6690 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006691 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006692 if (!klass->ShouldHaveImt()) {
6693 return;
6694 }
6695 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6696 // we can just use the same pointer.
6697 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006698 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006699 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6700 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6701 bool same = true;
6702 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6703 ArtMethod* method = imt_data[i];
6704 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6705 if (method != super_method) {
6706 bool is_conflict_table = method->IsRuntimeMethod() &&
6707 method != unimplemented_method &&
6708 method != conflict_method;
6709 // Verify conflict contents.
6710 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6711 super_method != unimplemented_method &&
6712 super_method != conflict_method;
6713 if (!is_conflict_table || !super_conflict_table) {
6714 same = false;
6715 } else {
6716 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6717 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6718 same = same && table1->Equals(table2, image_pointer_size_);
6719 }
6720 }
6721 }
6722 if (same) {
6723 imt = super_imt;
6724 }
6725 }
6726 if (imt == nullptr) {
6727 imt = klass->GetImt(image_pointer_size_);
6728 DCHECK(imt != nullptr);
6729 imt->Populate(imt_data, image_pointer_size_);
6730 } else {
6731 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006732 }
6733}
6734
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006735ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6736 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006737 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006738 void* data = linear_alloc->Alloc(Thread::Current(),
6739 ImtConflictTable::ComputeSize(count,
6740 image_pointer_size));
6741 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6742}
6743
6744ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6745 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6746}
6747
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006748void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006749 ArtMethod* unimplemented_method,
6750 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006751 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006752 bool create_conflict_tables,
6753 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006754 /*out*/bool* new_conflict,
6755 /*out*/ArtMethod** imt) {
6756 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006757 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006758 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006759 const size_t num_virtuals = interface->NumVirtualMethods();
6760 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6761 // Virtual methods can be larger than the if table methods if there are default methods.
6762 DCHECK_GE(num_virtuals, method_array_count);
6763 if (kIsDebugBuild) {
6764 if (klass->IsInterface()) {
6765 DCHECK_EQ(method_array_count, 0u);
6766 } else {
6767 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6768 }
6769 }
6770 if (method_array_count == 0) {
6771 continue;
6772 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006773 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006774 for (size_t j = 0; j < method_array_count; ++j) {
6775 ArtMethod* implementation_method =
6776 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6777 if (ignore_copied_methods && implementation_method->IsCopied()) {
6778 continue;
6779 }
6780 DCHECK(implementation_method != nullptr);
6781 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6782 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6783 // or interface methods in the IMT here they will not create extra conflicts since we compare
6784 // names and signatures in SetIMTRef.
6785 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006786 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006787
6788 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6789 // the same implementation method, keep track of this to avoid creating a conflict table in
6790 // this case.
6791
6792 // Conflict table size for each IMT slot.
6793 ++conflict_counts[imt_index];
6794
6795 SetIMTRef(unimplemented_method,
6796 imt_conflict_method,
6797 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006798 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006799 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006800 }
6801 }
6802
6803 if (create_conflict_tables) {
6804 // Create the conflict tables.
6805 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006806 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006807 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006808 if (imt[i] == imt_conflict_method) {
6809 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6810 if (new_table != nullptr) {
6811 ArtMethod* new_conflict_method =
6812 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6813 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6814 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006815 } else {
6816 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006817 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006818 }
6819 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006820 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821 }
6822 }
6823
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006824 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006825 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006826 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6827 // Virtual methods can be larger than the if table methods if there are default methods.
6828 if (method_array_count == 0) {
6829 continue;
6830 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006831 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006832 for (size_t j = 0; j < method_array_count; ++j) {
6833 ArtMethod* implementation_method =
6834 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6835 if (ignore_copied_methods && implementation_method->IsCopied()) {
6836 continue;
6837 }
6838 DCHECK(implementation_method != nullptr);
6839 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006840 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006841 if (!imt[imt_index]->IsRuntimeMethod() ||
6842 imt[imt_index] == unimplemented_method ||
6843 imt[imt_index] == imt_conflict_method) {
6844 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006845 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006846 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6847 const size_t num_entries = table->NumEntries(image_pointer_size_);
6848 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6849 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006850 }
6851 }
6852 }
6853}
6854
Alex Lighteb7c1442015-08-31 13:17:42 -07006855// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6856// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006857static bool NotSubinterfaceOfAny(
6858 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6859 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006860 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006861 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006862 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006863 for (ObjPtr<mirror::Class> c : classes) {
6864 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006865 return false;
6866 }
6867 }
6868 return true;
6869}
6870
6871// Fills in and flattens the interface inheritance hierarchy.
6872//
6873// By the end of this function all interfaces in the transitive closure of to_process are added to
6874// the iftable and every interface precedes all of its sub-interfaces in this list.
6875//
6876// all I, J: Interface | I <: J implies J precedes I
6877//
6878// (note A <: B means that A is a subtype of B)
6879//
6880// This returns the total number of items in the iftable. The iftable might be resized down after
6881// this call.
6882//
6883// We order this backwards so that we do not need to reorder superclass interfaces when new
6884// interfaces are added in subclass's interface tables.
6885//
6886// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6887// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6888// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6889// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006890static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006891 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006892 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006893 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006894 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 // This is the set of all class's already in the iftable. Used to make checking if a class has
6896 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006897 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006898 // The first super_ifcount elements are from the superclass. We note that they are already added.
6899 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006900 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006901 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6902 classes_in_iftable.insert(iface);
6903 }
6904 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006905 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006906 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6907 // At this point in the loop current-iface-list has the invariant that:
6908 // for every pair of interfaces I,J within it:
6909 // if index_of(I) < index_of(J) then I is not a subtype of J
6910
6911 // If we have already seen this element then all of its super-interfaces must already be in the
6912 // current-iface-list so we can skip adding it.
6913 if (!ContainsElement(classes_in_iftable, interface)) {
6914 // We haven't seen this interface so add all of its super-interfaces onto the
6915 // current-iface-list, skipping those already on it.
6916 int32_t ifcount = interface->GetIfTableCount();
6917 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006918 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006919 if (!ContainsElement(classes_in_iftable, super_interface)) {
6920 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6921 classes_in_iftable.insert(super_interface);
6922 iftable->SetInterface(filled_ifcount, super_interface);
6923 filled_ifcount++;
6924 }
6925 }
6926 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6927 // Place this interface onto the current-iface-list after all of its super-interfaces.
6928 classes_in_iftable.insert(interface);
6929 iftable->SetInterface(filled_ifcount, interface);
6930 filled_ifcount++;
6931 } else if (kIsDebugBuild) {
6932 // Check all super-interfaces are already in the list.
6933 int32_t ifcount = interface->GetIfTableCount();
6934 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006935 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006936 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006937 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6938 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006939 }
6940 }
6941 }
6942 if (kIsDebugBuild) {
6943 // Check that the iftable is ordered correctly.
6944 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006945 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006946 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006947 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006948 // !(if_a <: if_b)
6949 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006950 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6951 << ") extends "
6952 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006953 << "interface list.";
6954 }
6955 }
6956 }
6957 return filled_ifcount;
6958}
6959
6960bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6961 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6962 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006963 const bool has_superclass = klass->HasSuperClass();
6964 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006965 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006966 const size_t num_interfaces =
6967 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006968 if (num_interfaces == 0) {
6969 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006970 if (LIKELY(has_superclass)) {
6971 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6972 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006973 // Class implements no interfaces.
6974 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006975 return true;
6976 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006977 // Class implements same interfaces as parent, are any of these not marker interfaces?
6978 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006979 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006980 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006981 if (super_iftable->GetMethodArrayCount(i) > 0) {
6982 has_non_marker_interface = true;
6983 break;
6984 }
6985 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006986 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006987 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006988 klass->SetIfTable(super_iftable);
6989 return true;
6990 }
6991 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006992 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006993 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006994 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006995 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006996 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006997 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006998 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006999 if (UNLIKELY(!interface->IsInterface())) {
7000 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007001 ThrowIncompatibleClassChangeError(klass.Get(),
7002 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007003 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007004 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7005 return false;
7006 }
7007 ifcount += interface->GetIfTableCount();
7008 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007009 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007010 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007011 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007012 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007013 return false;
7014 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007015 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007016 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007017 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007018 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007019 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007020 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007021 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007022 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007023
7024 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7025 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7026 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007027 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007028
7029 size_t new_ifcount;
7030 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007031 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007032 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007033 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007034 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007035 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007036 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007037 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007038
7039 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007040 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007041
Ian Rogers7b078e82014-09-10 14:44:24 -07007042 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007043
Ian Rogersb52b01a2012-01-12 17:01:38 -08007044 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007045 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007046 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007047 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007048 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007049 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007050 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007051 return false;
7052 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007053 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007054 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007055 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007056 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007057 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007058 return true;
7059}
7060
Alex Light1f3925d2016-09-07 12:04:20 -07007061// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7062// of methods must be unique.
7063static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7064 return nullptr;
7065}
7066
7067template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007068static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007069 const ScopedArenaVector<ArtMethod*>& list,
7070 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007071 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007072 for (ArtMethod* method : list) {
7073 if (cmp.HasSameNameAndSignature(method)) {
7074 return method;
7075 }
7076 }
Alex Light1f3925d2016-09-07 12:04:20 -07007077 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007078}
7079
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007080namespace {
7081
Alex Light1f3925d2016-09-07 12:04:20 -07007082// Check that all vtable entries are present in this class's virtuals or are the same as a
7083// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007084void CheckClassOwnsVTableEntries(Thread* self,
7085 Handle<mirror::Class> klass,
7086 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007087 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007088 StackHandleScope<2> hs(self);
7089 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007090 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007091 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007092 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007093 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7094 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7095 CHECK(m != nullptr);
7096
Alex Lighta41a30782017-03-29 11:33:19 -07007097 if (m->GetMethodIndexDuringLinking() != i) {
7098 LOG(WARNING) << m->PrettyMethod()
7099 << " has an unexpected method index for its spot in the vtable for class"
7100 << klass->PrettyClass();
7101 }
Alex Lighte64300b2015-12-15 15:02:47 -08007102 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7103 auto is_same_method = [m] (const ArtMethod& meth) {
7104 return &meth == m;
7105 };
Alex Light3f980532017-03-17 15:10:32 -07007106 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7107 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7108 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7109 << klass->PrettyClass() << " or any of its superclasses!";
7110 }
Alex Lighte64300b2015-12-15 15:02:47 -08007111 }
7112}
7113
Alex Light1f3925d2016-09-07 12:04:20 -07007114// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7115// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007116template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007117void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007118 REQUIRES_SHARED(Locks::mutator_lock_) {
7119 StackHandleScope<1> hs(self);
7120 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7121 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007122
7123 // Observations:
7124 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7125 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7126 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7127 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7128 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7129 // * The single-pass algorithm will trade memory for speed, but that is OK.
7130
7131 CHECK_GT(num_entries, 0);
7132
7133 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7134 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7135 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7136 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7137 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7138 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7139 << m2->PrettyMethod() << " (0x" << std::hex
7140 << reinterpret_cast<uintptr_t>(m2) << ")";
7141 };
7142 struct BaseHashType {
7143 static size_t HashCombine(size_t seed, size_t val) {
7144 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7145 }
7146 };
7147
7148 // Check assuming all entries come from the same dex file.
7149 {
7150 // Find the first interesting method and its dex file.
7151 int32_t start = 0;
7152 for (; start < num_entries; ++start) {
7153 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7154 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7155 // maybe).
7156 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7157 vtable_entry->GetAccessFlags())) {
7158 continue;
7159 }
7160 break;
7161 }
7162 if (start == num_entries) {
7163 return;
7164 }
7165 const DexFile* dex_file =
7166 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7167 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7168
7169 // Helper function to avoid logging if we have to run the cross-file checks.
7170 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7171 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7172 using PairType = std::pair<uint32_t, uint16_t>;
7173 struct PairHash : BaseHashType {
7174 size_t operator()(const PairType& key) const {
7175 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7176 }
7177 };
7178 std::unordered_map<PairType, int32_t, PairHash> seen;
7179 seen.reserve(2 * num_entries);
7180 bool need_slow_path = false;
7181 bool found_dup = false;
7182 for (int i = start; i < num_entries; ++i) {
7183 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7184 // wrt/ kPointerSize.
7185 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7186 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7187 vtable_entry->GetAccessFlags())) {
7188 continue;
7189 }
7190 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7191 if (dex_file != m->GetDexFile()) {
7192 need_slow_path = true;
7193 break;
7194 }
7195 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7196 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7197 auto it = seen.find(pair);
7198 if (it != seen.end()) {
7199 found_dup = true;
7200 if (log_warn) {
7201 log_fn(it->second, i);
7202 }
7203 } else {
7204 seen.emplace(pair, i);
7205 }
7206 }
7207 return std::make_pair(need_slow_path, found_dup);
7208 };
7209 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7210 if (!result.first) {
7211 if (result.second) {
7212 check_fn(/* log_warn= */ true);
7213 }
7214 return;
7215 }
7216 }
7217
7218 // Need to check across dex files.
7219 struct Entry {
7220 size_t cached_hash = 0;
7221 const char* name = nullptr;
7222 Signature signature = Signature::NoSignature();
7223 uint32_t name_len = 0;
7224
7225 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7226 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7227 signature(dex_file->GetMethodSignature(mid)) {
7228 }
7229
7230 bool operator==(const Entry& other) const {
7231 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7232 return false;
7233 }
7234 return signature == other.signature;
7235 }
7236 };
7237 struct EntryHash {
7238 size_t operator()(const Entry& key) const {
7239 return key.cached_hash;
7240 }
7241 };
7242 std::unordered_map<Entry, int32_t, EntryHash> map;
7243 for (int32_t i = 0; i < num_entries; ++i) {
7244 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7245 // wrt/ kPointerSize.
7246 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7247 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7248 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007249 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7250 vtable_entry->GetAccessFlags())) {
7251 continue;
7252 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007253 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7254 const DexFile* dex_file = m->GetDexFile();
7255 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7256
7257 Entry e(dex_file, mid);
7258
7259 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7260 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7261 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7262 sig_hash);
7263
7264 auto it = map.find(e);
7265 if (it != map.end()) {
7266 log_fn(it->second, i);
7267 } else {
7268 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007269 }
7270 }
7271}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007272
7273void CheckVTableHasNoDuplicates(Thread* self,
7274 Handle<mirror::Class> klass,
7275 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007276 REQUIRES_SHARED(Locks::mutator_lock_) {
7277 switch (pointer_size) {
7278 case PointerSize::k64:
7279 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7280 break;
7281 case PointerSize::k32:
7282 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7283 break;
7284 }
7285}
Alex Light1f3925d2016-09-07 12:04:20 -07007286
7287static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7288 REQUIRES_SHARED(Locks::mutator_lock_) {
7289 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7290 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7291}
7292
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007293} // namespace
7294
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007295void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7296 ArtMethod* unimplemented_method,
7297 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007298 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007299 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007300 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007301 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007302 if (super_class->ShouldHaveImt()) {
7303 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7304 for (size_t i = 0; i < ImTable::kSize; ++i) {
7305 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007306 }
7307 } else {
7308 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007309 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007310 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007311 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007312 FillIMTFromIfTable(if_table,
7313 unimplemented_method,
7314 imt_conflict_method,
7315 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007316 /*create_conflict_tables=*/false,
7317 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007318 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007319 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007320 }
7321 }
7322}
7323
Vladimir Marko921094a2017-01-12 18:37:06 +00007324class ClassLinker::LinkInterfaceMethodsHelper {
7325 public:
7326 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7327 Handle<mirror::Class> klass,
7328 Thread* self,
7329 Runtime* runtime)
7330 : class_linker_(class_linker),
7331 klass_(klass),
7332 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7333 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7334 self_(self),
7335 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7336 allocator_(&stack_),
7337 default_conflict_methods_(allocator_.Adapter()),
7338 overriding_default_conflict_methods_(allocator_.Adapter()),
7339 miranda_methods_(allocator_.Adapter()),
7340 default_methods_(allocator_.Adapter()),
7341 overriding_default_methods_(allocator_.Adapter()),
7342 move_table_(allocator_.Adapter()) {
7343 }
7344
7345 ArtMethod* FindMethod(ArtMethod* interface_method,
7346 MethodNameAndSignatureComparator& interface_name_comparator,
7347 ArtMethod* vtable_impl)
7348 REQUIRES_SHARED(Locks::mutator_lock_);
7349
7350 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7351 MethodNameAndSignatureComparator& interface_name_comparator)
7352 REQUIRES_SHARED(Locks::mutator_lock_);
7353
7354 bool HasNewVirtuals() const {
7355 return !(miranda_methods_.empty() &&
7356 default_methods_.empty() &&
7357 overriding_default_methods_.empty() &&
7358 overriding_default_conflict_methods_.empty() &&
7359 default_conflict_methods_.empty());
7360 }
7361
7362 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7363
7364 ObjPtr<mirror::PointerArray> UpdateVtable(
7365 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7366 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7367
7368 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7369
7370 void UpdateIMT(ArtMethod** out_imt);
7371
7372 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7373 if (kIsDebugBuild) {
7374 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7375 // Check that there are no stale methods are in the dex cache array.
7376 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7377 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007378 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7379 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007380 CHECK(move_table_.find(m) == move_table_.end() ||
7381 // The original versions of copied methods will still be present so allow those too.
7382 // Note that if the first check passes this might fail to GetDeclaringClass().
7383 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7384 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7385 [m] (ArtMethod& meth) {
7386 return &meth == m;
7387 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7388 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7389 }
7390 }
7391 }
7392
7393 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7394 LengthPrefixedArray<ArtMethod>* methods) {
7395 if (kIsDebugBuild) {
7396 CHECK(methods != nullptr);
7397 // Put some random garbage in old methods to help find stale pointers.
7398 if (methods != old_methods && old_methods != nullptr) {
7399 // Need to make sure the GC is not running since it could be scanning the methods we are
7400 // about to overwrite.
7401 ScopedThreadStateChange tsc(self_, kSuspended);
7402 gc::ScopedGCCriticalSection gcs(self_,
7403 gc::kGcCauseClassLinker,
7404 gc::kCollectorTypeClassLinker);
7405 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7406 method_size_,
7407 method_alignment_);
7408 memset(old_methods, 0xFEu, old_size);
7409 }
7410 }
7411 }
7412
7413 private:
7414 size_t NumberOfNewVirtuals() const {
7415 return miranda_methods_.size() +
7416 default_methods_.size() +
7417 overriding_default_conflict_methods_.size() +
7418 overriding_default_methods_.size() +
7419 default_conflict_methods_.size();
7420 }
7421
7422 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7423 return !klass_->IsInterface();
7424 }
7425
7426 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7427 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7428 << "Interfaces should only have default-conflict methods appended to them.";
7429 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7430 << miranda_methods_.size()
7431 << " default_methods=" << default_methods_.size()
7432 << " overriding_default_methods=" << overriding_default_methods_.size()
7433 << " default_conflict_methods=" << default_conflict_methods_.size()
7434 << " overriding_default_conflict_methods="
7435 << overriding_default_conflict_methods_.size();
7436 }
7437
7438 ClassLinker* class_linker_;
7439 Handle<mirror::Class> klass_;
7440 size_t method_alignment_;
7441 size_t method_size_;
7442 Thread* const self_;
7443
7444 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7445 // the virtual methods array.
7446 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7447 // during cross compilation.
7448 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7449 ArenaStack stack_;
7450 ScopedArenaAllocator allocator_;
7451
7452 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7453 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7454 ScopedArenaVector<ArtMethod*> miranda_methods_;
7455 ScopedArenaVector<ArtMethod*> default_methods_;
7456 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7457
7458 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7459};
7460
7461ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7462 ArtMethod* interface_method,
7463 MethodNameAndSignatureComparator& interface_name_comparator,
7464 ArtMethod* vtable_impl) {
7465 ArtMethod* current_method = nullptr;
7466 switch (class_linker_->FindDefaultMethodImplementation(self_,
7467 interface_method,
7468 klass_,
7469 /*out*/&current_method)) {
7470 case DefaultMethodSearchResult::kDefaultConflict: {
7471 // Default method conflict.
7472 DCHECK(current_method == nullptr);
7473 ArtMethod* default_conflict_method = nullptr;
7474 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7475 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7476 default_conflict_method = vtable_impl;
7477 } else {
7478 // See if we already have a conflict method for this method.
7479 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7480 interface_name_comparator,
7481 default_conflict_methods_,
7482 overriding_default_conflict_methods_);
7483 if (LIKELY(preexisting_conflict != nullptr)) {
7484 // We already have another conflict we can reuse.
7485 default_conflict_method = preexisting_conflict;
7486 } else {
7487 // Note that we do this even if we are an interface since we need to create this and
7488 // cannot reuse another classes.
7489 // Create a new conflict method for this to use.
7490 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7491 new(default_conflict_method) ArtMethod(interface_method,
7492 class_linker_->GetImagePointerSize());
7493 if (vtable_impl == nullptr) {
7494 // Save the conflict method. We need to add it to the vtable.
7495 default_conflict_methods_.push_back(default_conflict_method);
7496 } else {
7497 // Save the conflict method but it is already in the vtable.
7498 overriding_default_conflict_methods_.push_back(default_conflict_method);
7499 }
7500 }
7501 }
7502 current_method = default_conflict_method;
7503 break;
7504 } // case kDefaultConflict
7505 case DefaultMethodSearchResult::kDefaultFound: {
7506 DCHECK(current_method != nullptr);
7507 // Found a default method.
7508 if (vtable_impl != nullptr &&
7509 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7510 // We found a default method but it was the same one we already have from our
7511 // superclass. Don't bother adding it to our vtable again.
7512 current_method = vtable_impl;
7513 } else if (LIKELY(FillTables())) {
7514 // Interfaces don't need to copy default methods since they don't have vtables.
7515 // Only record this default method if it is new to save space.
7516 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7517 // would make lookup for interface super much faster. (We would only need to scan
7518 // the iftable to find if there is a NSME or AME.)
7519 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7520 default_methods_,
7521 overriding_default_methods_);
7522 if (old == nullptr) {
7523 // We found a default method implementation and there were no conflicts.
7524 if (vtable_impl == nullptr) {
7525 // Save the default method. We need to add it to the vtable.
7526 default_methods_.push_back(current_method);
7527 } else {
7528 // Save the default method but it is already in the vtable.
7529 overriding_default_methods_.push_back(current_method);
7530 }
7531 } else {
7532 CHECK(old == current_method) << "Multiple default implementations selected!";
7533 }
7534 }
7535 break;
7536 } // case kDefaultFound
7537 case DefaultMethodSearchResult::kAbstractFound: {
7538 DCHECK(current_method == nullptr);
7539 // Abstract method masks all defaults.
7540 if (vtable_impl != nullptr &&
7541 vtable_impl->IsAbstract() &&
7542 !vtable_impl->IsDefaultConflicting()) {
7543 // We need to make this an abstract method but the version in the vtable already is so
7544 // don't do anything.
7545 current_method = vtable_impl;
7546 }
7547 break;
7548 } // case kAbstractFound
7549 }
7550 return current_method;
7551}
7552
7553ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7554 ArtMethod* interface_method,
7555 MethodNameAndSignatureComparator& interface_name_comparator) {
7556 // Find out if there is already a miranda method we can use.
7557 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7558 miranda_methods_);
7559 if (miranda_method == nullptr) {
7560 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7561 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7562 CHECK(miranda_method != nullptr);
7563 // Point the interface table at a phantom slot.
7564 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7565 miranda_methods_.push_back(miranda_method);
7566 }
7567 return miranda_method;
7568}
7569
7570void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7571 LogNewVirtuals();
7572
7573 const size_t old_method_count = klass_->NumMethods();
7574 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7575 DCHECK_NE(old_method_count, new_method_count);
7576
7577 // Attempt to realloc to save RAM if possible.
7578 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7579 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7580 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7581 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7582 // CopyFrom has internal read barriers.
7583 //
7584 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7585 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7586 method_size_,
7587 method_alignment_);
7588 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7589 method_size_,
7590 method_alignment_);
7591 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7592 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007593 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007594 self_, old_methods, old_methods_ptr_size, new_size));
7595 CHECK(methods != nullptr); // Native allocation failure aborts.
7596
7597 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7598 if (methods != old_methods) {
7599 // Maps from heap allocated miranda method to linear alloc miranda method.
7600 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7601 // Copy over the old methods.
7602 for (auto& m : klass_->GetMethods(pointer_size)) {
7603 move_table_.emplace(&m, &*out);
7604 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7605 // barriers when it copies.
7606 out->CopyFrom(&m, pointer_size);
7607 ++out;
7608 }
7609 }
7610 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7611 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7612 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007613 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7614 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007615 ArtMethod& new_method = *out;
7616 new_method.CopyFrom(mir_method, pointer_size);
7617 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7618 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7619 << "Miranda method should be abstract!";
7620 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007621 // Update the entry in the method array, as the array will be used for future lookups,
7622 // where thread suspension is allowed.
7623 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7624 // would not see them.
7625 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007626 ++out;
7627 }
7628 // We need to copy the default methods into our own method table since the runtime requires that
7629 // every method on a class's vtable be in that respective class's virtual method table.
7630 // NOTE This means that two classes might have the same implementation of a method from the same
7631 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7632 // default method found on a class with one found on the declaring interface directly and must
7633 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007634 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7635 &overriding_default_methods_}) {
7636 for (size_t i = 0; i < methods_vec->size(); ++i) {
7637 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007638 ArtMethod& new_method = *out;
7639 new_method.CopyFrom(def_method, pointer_size);
7640 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7641 // verified yet it shouldn't have methods that are skipping access checks.
7642 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7643 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007644 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007645 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7646 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7647 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7648 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007649 // Update the entry in the method array, as the array will be used for future lookups,
7650 // where thread suspension is allowed.
7651 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7652 // would not see them.
7653 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007654 ++out;
7655 }
7656 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007657 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7658 &overriding_default_conflict_methods_}) {
7659 for (size_t i = 0; i < methods_vec->size(); ++i) {
7660 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007661 ArtMethod& new_method = *out;
7662 new_method.CopyFrom(conf_method, pointer_size);
7663 // This is a type of default method (there are default method impls, just a conflict) so
7664 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7665 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7666 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007667 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7668 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007669 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007670 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007671 constexpr uint32_t kMaskFlags =
7672 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007673 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7674 DCHECK(new_method.IsDefaultConflicting());
7675 // The actual method might or might not be marked abstract since we just copied it from a
7676 // (possibly default) interface method. We need to set it entry point to be the bridge so
7677 // that the compiler will not invoke the implementation of whatever method we copied from.
7678 EnsureThrowsInvocationError(class_linker_, &new_method);
7679 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007680 // Update the entry in the method array, as the array will be used for future lookups,
7681 // where thread suspension is allowed.
7682 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7683 // would not see them.
7684 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007685 ++out;
7686 }
7687 }
7688 methods->SetSize(new_method_count);
7689 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7690}
7691
7692ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7693 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7694 ObjPtr<mirror::PointerArray> old_vtable) {
7695 // Update the vtable to the new method structures. We can skip this for interfaces since they
7696 // do not have vtables.
7697 const size_t old_vtable_count = old_vtable->GetLength();
7698 const size_t new_vtable_count = old_vtable_count +
7699 miranda_methods_.size() +
7700 default_methods_.size() +
7701 default_conflict_methods_.size();
7702
7703 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007704 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007705 if (UNLIKELY(vtable == nullptr)) {
7706 self_->AssertPendingOOMException();
7707 return nullptr;
7708 }
7709
7710 size_t vtable_pos = old_vtable_count;
7711 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7712 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7713 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7714 default_conflict_methods_,
7715 miranda_methods_}) {
7716 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007717 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007718 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7719 // fields are references into the dex file the method was defined in. Since the ArtMethod
7720 // does not store that information it uses declaring_class_->dex_cache_.
7721 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7722 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7723 ++vtable_pos;
7724 }
7725 }
7726 DCHECK_EQ(vtable_pos, new_vtable_count);
7727
7728 // Update old vtable methods. We use the default_translations map to figure out what each
7729 // vtable entry should be updated to, if they need to be at all.
7730 for (size_t i = 0; i < old_vtable_count; ++i) {
7731 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7732 // Try and find what we need to change this method to.
7733 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007734 if (translation_it != default_translations.end()) {
7735 if (translation_it->second.IsInConflict()) {
7736 // Find which conflict method we are to use for this method.
7737 MethodNameAndSignatureComparator old_method_comparator(
7738 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7739 // We only need to look through overriding_default_conflict_methods since this is an
7740 // overridden method we are fixing up here.
7741 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7742 old_method_comparator, overriding_default_conflict_methods_);
7743 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7744 translated_method = new_conflict_method;
7745 } else if (translation_it->second.IsAbstract()) {
7746 // Find which miranda method we are to use for this method.
7747 MethodNameAndSignatureComparator old_method_comparator(
7748 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7749 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7750 miranda_methods_);
7751 DCHECK(miranda_method != nullptr);
7752 translated_method = miranda_method;
7753 } else {
7754 // Normal default method (changed from an older default or abstract interface method).
7755 DCHECK(translation_it->second.IsTranslation());
7756 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007757 auto it = move_table_.find(translated_method);
7758 DCHECK(it != move_table_.end());
7759 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007760 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007761 } else {
7762 auto it = move_table_.find(translated_method);
7763 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007764 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007765
7766 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007767 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007768 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007769 if (kIsDebugBuild) {
7770 auto* methods = klass_->GetMethodsPtr();
7771 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007772 reinterpret_cast<uintptr_t>(translated_method));
7773 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007774 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7775 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007776 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007777 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007778 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007779 }
7780 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007781 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007782 return vtable;
7783}
7784
7785void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7786 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7787 const size_t ifcount = klass_->GetIfTableCount();
7788 // Go fix up all the stale iftable pointers.
7789 for (size_t i = 0; i < ifcount; ++i) {
7790 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007791 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7792 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007793 DCHECK(m != nullptr) << klass_->PrettyClass();
7794 auto it = move_table_.find(m);
7795 if (it != move_table_.end()) {
7796 auto* new_m = it->second;
7797 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7798 method_array->SetElementPtrSize(j, new_m, pointer_size);
7799 }
7800 }
7801 }
7802}
7803
7804void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7805 // Fix up IMT next.
7806 for (size_t i = 0; i < ImTable::kSize; ++i) {
7807 auto it = move_table_.find(out_imt[i]);
7808 if (it != move_table_.end()) {
7809 out_imt[i] = it->second;
7810 }
7811 }
7812}
7813
Alex Light705ad492015-09-21 11:36:30 -07007814// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007815bool ClassLinker::LinkInterfaceMethods(
7816 Thread* self,
7817 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007818 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007819 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007820 ArtMethod** out_imt) {
7821 StackHandleScope<3> hs(self);
7822 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007823
7824 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007825 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007826 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007827 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007828 const size_t ifcount = klass->GetIfTableCount();
7829
Vladimir Marko921094a2017-01-12 18:37:06 +00007830 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007831
7832 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7833 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007834 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007835 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007836 const bool extend_super_iftable = has_superclass;
7837 if (has_superclass && fill_tables) {
7838 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007839 unimplemented_method,
7840 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007841 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007842 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007843 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007844 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7845 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007846 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007847 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7848 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007849 }
7850 }
7851
Vladimir Marko921094a2017-01-12 18:37:06 +00007852 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7853
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007854 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007855 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007856 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7857 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7858 // they will already be null. This has the additional benefit that the declarer of a miranda
7859 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007860 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007861 --i;
Alex Light9139e002015-10-09 15:59:48 -07007862 DCHECK_LT(i, ifcount);
7863
Alex Light705ad492015-09-21 11:36:30 -07007864 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007865 if (num_methods > 0) {
7866 StackHandleScope<2> hs2(self);
7867 const bool is_super = i < super_ifcount;
7868 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007869 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7870 // conflict methods. Just set this as nullptr in those cases.
7871 Handle<mirror::PointerArray> method_array(fill_tables
7872 ? hs2.NewHandle(iftable->GetMethodArray(i))
7873 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007874
Alex Lighte64300b2015-12-15 15:02:47 -08007875 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007876 ScopedNullHandle<mirror::PointerArray> null_handle;
7877 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007878 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007879
Alex Light9139e002015-10-09 15:59:48 -07007880 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7881 // and confusing. Default methods should always look through all the superclasses
7882 // because they are the last choice of an implementation. We get around this by looking
7883 // at the super-classes iftable methods (copied into method_array previously) when we are
7884 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007885 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007886 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007887 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007888 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007889 using_virtuals = true;
7890 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7891 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007892 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007893 // For a new interface, however, we need the whole vtable in case a new
7894 // interface method is implemented in the whole superclass.
7895 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007896 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007897 input_vtable_array = vtable;
7898 input_array_length = input_vtable_array->GetLength();
7899 }
Alex Lighte64300b2015-12-15 15:02:47 -08007900
Alex Lighteb7c1442015-08-31 13:17:42 -07007901 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007902 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007903 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007904 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007905 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007906 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007907 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007908 // For each method listed in the interface's method list, find the
7909 // matching method in our class's method list. We want to favor the
7910 // subclass over the superclass, which just requires walking
7911 // back from the end of the vtable. (This only matters if the
7912 // superclass defines a private method and this class redefines
7913 // it -- otherwise it would use the same vtable slot. In .dex files
7914 // those don't end up in the virtual method table, so it shouldn't
7915 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007916 //
7917 // To find defaults we need to do the same but also go over interfaces.
7918 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007919 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007920 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007921 ArtMethod* vtable_method = using_virtuals ?
7922 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007923 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7924 ArtMethod* vtable_method_for_name_comparison =
7925 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007926 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007927 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007928 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007929 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7930 // allocations.
7931 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007932 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007933 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007934 vtable_method->PrettyMethod().c_str(),
7935 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007936 return false;
Alex Light9139e002015-10-09 15:59:48 -07007937 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007938 // We might have a newer, better, default method for this, so we just skip it. If we
7939 // are still using this we will select it again when scanning for default methods. To
7940 // obviate the need to copy the method again we will make a note that we already found
7941 // a default here.
7942 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007943 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007944 break;
7945 } else {
7946 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007947 if (LIKELY(fill_tables)) {
7948 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7949 // Place method in imt if entry is empty, place conflict otherwise.
7950 SetIMTRef(unimplemented_method,
7951 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007952 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007953 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007954 /*out*/imt_ptr);
7955 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007956 break;
7957 }
7958 }
Alex Light9139e002015-10-09 15:59:48 -07007959 }
7960 // Continue on to the next method if we are done.
7961 if (LIKELY(found_impl)) {
7962 continue;
7963 } else if (LIKELY(super_interface)) {
7964 // Don't look for a default implementation when the super-method is implemented directly
7965 // by the class.
7966 //
7967 // See if we can use the superclasses method and skip searching everything else.
7968 // Note: !found_impl && super_interface
7969 CHECK(extend_super_iftable);
7970 // If this is a super_interface method it is possible we shouldn't override it because a
7971 // superclass could have implemented it directly. We get the method the superclass used
7972 // to implement this to know if we can override it with a default method. Doing this is
7973 // safe since we know that the super_iftable is filled in so we can simply pull it from
7974 // there. We don't bother if this is not a super-classes interface since in that case we
7975 // have scanned the entire vtable anyway and would have found it.
7976 // TODO This is rather dirty but it is faster than searching through the entire vtable
7977 // every time.
7978 ArtMethod* supers_method =
7979 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7980 DCHECK(supers_method != nullptr);
7981 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007982 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007983 // The method is not overridable by a default method (i.e. it is directly implemented
7984 // in some class). Therefore move onto the next interface method.
7985 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007986 } else {
7987 // If the super-classes method is override-able by a default method we need to keep
7988 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7989 // 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 -07007990 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7991 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7992 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007993 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007994 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7995 << " and not 'nullptr' or "
7996 << supers_method->PrettyMethod()
7997 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007998 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007999 }
8000 }
8001 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008002 ArtMethod* current_method = helper.FindMethod(interface_method,
8003 interface_name_comparator,
8004 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008005 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008006 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008007 // We could not find an implementation for this method and since it is a brand new
8008 // interface we searched the entire vtable (and all default methods) for an
8009 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008010 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8011 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008012 }
8013
8014 if (current_method != nullptr) {
8015 // We found a default method implementation. Record it in the iftable and IMT.
8016 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8017 SetIMTRef(unimplemented_method,
8018 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008019 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008020 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008021 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008022 }
8023 }
Alex Light705ad492015-09-21 11:36:30 -07008024 } // For each method in interface end.
8025 } // if (num_methods > 0)
8026 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008027 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008028 if (helper.HasNewVirtuals()) {
8029 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8030 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8031 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8032
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008033 // 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 -07008034 // suspension assert.
8035 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008036
Alex Light705ad492015-09-21 11:36:30 -07008037 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008038 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008039 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008040 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008041 return false;
8042 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008043 helper.UpdateIfTable(iftable);
8044 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008045 }
Alex Light705ad492015-09-21 11:36:30 -07008046
Vladimir Marko921094a2017-01-12 18:37:06 +00008047 helper.CheckNoStaleMethodsInDexCache();
8048 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008049 } else {
8050 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008051 }
Alex Light705ad492015-09-21 11:36:30 -07008052 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008053 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008054 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008055 return true;
8056}
8057
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008058bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008059 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008060 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008061}
8062
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008063bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008064 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008065 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008066}
8067
Brian Carlstromdbc05252011-09-09 01:59:59 -07008068struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008069 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008070 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008071 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008072 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008073 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008074 // 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 -07008075 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8076 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008077 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008078 if (type1 == Primitive::kPrimNot) {
8079 // Reference always goes first.
8080 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008081 }
Vladimir Markod5777482014-11-12 17:02:02 +00008082 if (type2 == Primitive::kPrimNot) {
8083 // Reference always goes first.
8084 return false;
8085 }
8086 size_t size1 = Primitive::ComponentSize(type1);
8087 size_t size2 = Primitive::ComponentSize(type2);
8088 if (size1 != size2) {
8089 // Larger primitive types go first.
8090 return size1 > size2;
8091 }
8092 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8093 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008094 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008095 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8096 // by name and for equal names by type id index.
8097 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8098 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008099 }
8100};
8101
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008102bool ClassLinker::LinkFields(Thread* self,
8103 Handle<mirror::Class> klass,
8104 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008105 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008106 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008107 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008108 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8109 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008110
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008111 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008112 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008113 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008114 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008115 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008116 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008117 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008118 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008119 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008120 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008121 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008122 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008123
David Sehr709b0702016-10-13 09:12:37 -07008124 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008125
Brian Carlstromdbc05252011-09-09 01:59:59 -07008126 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008127 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008128 //
8129 // The overall sort order order is:
8130 // 1) All object reference fields, sorted alphabetically.
8131 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8132 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8133 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8134 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8135 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8136 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8137 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8138 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8139 //
8140 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8141 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008142 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008143 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008144 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008145 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008146 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008147 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008148 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8149 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008150
Fred Shih381e4ca2014-08-25 17:24:27 -07008151 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008152 size_t current_field = 0;
8153 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008154 FieldGaps gaps;
8155
Brian Carlstromdbc05252011-09-09 01:59:59 -07008156 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008157 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008158 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008159 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008160 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008161 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008162 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008163 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8164 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008165 MemberOffset old_offset = field_offset;
8166 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8167 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8168 }
Roland Levillain14d90572015-07-16 10:52:26 +01008169 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008170 grouped_and_sorted_fields.pop_front();
8171 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008172 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008173 field_offset = MemberOffset(field_offset.Uint32Value() +
8174 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008175 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008176 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8177 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008178 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8179 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8180 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8181 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008182 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8183 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008184 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008185
Elliott Hughesadb460d2011-10-05 17:02:34 -07008186 // 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 -07008187 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008188 // We know there are no non-reference fields in the Reference classes, and we know
8189 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008190 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008191 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008192 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008193 --num_reference_fields;
8194 }
8195
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008196 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008197 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008198 if (is_static) {
8199 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008200 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008201 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008202 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008203 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008204 if (num_reference_fields == 0 || super_class == nullptr) {
8205 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008206 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008207 if (super_class == nullptr ||
8208 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8209 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008210 }
8211 }
8212 if (kIsDebugBuild) {
8213 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8214 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008215 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008216 while (cur_super != nullptr) {
8217 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8218 cur_super = cur_super->GetSuperClass();
8219 }
8220 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008221 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008222 } else {
8223 // Check that there is at least num_reference_fields other than Object.class.
8224 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008225 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008226 }
8227 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008228 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008229 std::string temp;
8230 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8231 size_t previous_size = klass->GetObjectSize();
8232 if (previous_size != 0) {
8233 // Make sure that we didn't originally have an incorrect size.
8234 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008235 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008236 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008237 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008238 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008239
8240 if (kIsDebugBuild) {
8241 // Make sure that the fields array is ordered by name but all reference
8242 // offsets are at the beginning as far as alignment allows.
8243 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008244 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008245 : klass->GetFirstReferenceInstanceFieldOffset();
8246 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8247 num_reference_fields *
8248 sizeof(mirror::HeapReference<mirror::Object>));
8249 MemberOffset current_ref_offset = start_ref_offset;
8250 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008251 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008252 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008253 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8254 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008255 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008256 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008257 // NOTE: The field names can be the same. This is not possible in the Java language
8258 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008259 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008260 }
8261 Primitive::Type type = field->GetTypeAsPrimitiveType();
8262 bool is_primitive = type != Primitive::kPrimNot;
8263 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8264 strcmp("referent", field->GetName()) == 0) {
8265 is_primitive = true; // We lied above, so we have to expect a lie here.
8266 }
8267 MemberOffset offset = field->GetOffsetDuringLinking();
8268 if (is_primitive) {
8269 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8270 // Shuffled before references.
8271 size_t type_size = Primitive::ComponentSize(type);
8272 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8273 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8274 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8275 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8276 }
8277 } else {
8278 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8279 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8280 sizeof(mirror::HeapReference<mirror::Object>));
8281 }
8282 }
8283 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8284 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008285 return true;
8286}
8287
Vladimir Marko76649e82014-11-10 18:32:59 +00008288// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008289void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008290 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008291 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008292 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008293 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008294 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008295 // Compute reference offsets unless our superclass overflowed.
8296 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8297 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008298 if (num_reference_fields != 0u) {
8299 // All of the fields that contain object references are guaranteed be grouped in memory
8300 // starting at an appropriately aligned address after super class object data.
8301 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8302 sizeof(mirror::HeapReference<mirror::Object>));
8303 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008304 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008305 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008306 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008307 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008308 reference_offsets |= (0xffffffffu << start_bit) &
8309 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008310 }
8311 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008312 }
8313 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008314 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008315}
8316
Vladimir Marko18090d12018-06-01 16:53:12 +01008317ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8318 ObjPtr<mirror::DexCache> dex_cache) {
8319 StackHandleScope<1> hs(Thread::Current());
8320 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8321 return DoResolveString(string_idx, h_dex_cache);
8322}
8323
8324ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8325 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008326 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008327 uint32_t utf16_length;
8328 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008329 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008330 if (string != nullptr) {
8331 dex_cache->SetResolvedString(string_idx, string);
8332 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008333 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008334}
8335
Vladimir Marko18090d12018-06-01 16:53:12 +01008336ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8337 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008338 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008339 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008340 uint32_t utf16_length;
8341 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008342 ObjPtr<mirror::String> string =
8343 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008344 if (string != nullptr) {
8345 dex_cache->SetResolvedString(string_idx, string);
8346 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008347 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008348}
8349
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008350ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008351 ObjPtr<mirror::Class> referrer) {
8352 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8353}
8354
8355ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008356 ObjPtr<mirror::DexCache> dex_cache,
8357 ObjPtr<mirror::ClassLoader> class_loader) {
8358 const DexFile& dex_file = *dex_cache->GetDexFile();
8359 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8360 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8361 ObjPtr<mirror::Class> type = nullptr;
8362 if (descriptor[1] == '\0') {
8363 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8364 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008365 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008366 } else {
8367 Thread* const self = Thread::Current();
8368 DCHECK(self != nullptr);
8369 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8370 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008371 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008372 }
8373 if (type != nullptr) {
8374 if (type->IsResolved()) {
8375 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008376 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008377 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008378 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008379 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008380 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008381}
8382
Andreas Gampe4835d212018-11-21 14:55:10 -08008383template <typename T>
8384ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008385 StackHandleScope<2> hs(Thread::Current());
8386 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8387 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8388 return DoResolveType(type_idx, dex_cache, class_loader);
8389}
8390
Andreas Gampe4835d212018-11-21 14:55:10 -08008391// Instantiate the above.
8392template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8393 ArtField* referrer);
8394template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8395 ArtMethod* referrer);
8396template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8397 ObjPtr<mirror::Class> referrer);
8398
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008399ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008400 Handle<mirror::DexCache> dex_cache,
8401 Handle<mirror::ClassLoader> class_loader) {
8402 Thread* self = Thread::Current();
8403 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8404 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8405 if (resolved != nullptr) {
8406 // TODO: we used to throw here if resolved's class loader was not the
8407 // boot class loader. This was to permit different classes with the
8408 // same name to be loaded simultaneously by different loaders
8409 dex_cache->SetResolvedType(type_idx, resolved);
8410 } else {
8411 CHECK(self->IsExceptionPending())
8412 << "Expected pending exception for failed resolution of: " << descriptor;
8413 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8414 StackHandleScope<1> hs(self);
8415 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008416 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008417 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8418 self->ClearException();
8419 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8420 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008421 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008422 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008423 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008424 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008425 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008426}
8427
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008428ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8429 ObjPtr<mirror::DexCache> dex_cache,
8430 ObjPtr<mirror::ClassLoader> class_loader,
8431 uint32_t method_idx) {
8432 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8433 // functions can optimize the search if the dex_cache is the same as the DexCache
8434 // of the class, with fall-back to name and signature search otherwise.
8435 ArtMethod* resolved = nullptr;
8436 if (klass->IsInterface()) {
8437 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8438 } else {
8439 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8440 }
8441 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008442 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008443 hiddenapi::ShouldDenyAccessToMember(resolved,
8444 hiddenapi::AccessContext(class_loader, dex_cache),
8445 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008446 resolved = nullptr;
8447 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008448 if (resolved != nullptr) {
8449 // In case of jmvti, the dex file gets verified before being registered, so first
8450 // check if it's registered before checking class tables.
8451 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008452 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8453 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008454 << "DexFile referrer: " << dex_file.GetLocation()
8455 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8456 // Be a good citizen and update the dex cache to speed subsequent calls.
8457 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008458 // Disable the following invariant check as the verifier breaks it. b/73760543
8459 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8460 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8461 // << "Method: " << resolved->PrettyMethod() << ", "
8462 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8463 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008464 }
8465 return resolved;
8466}
8467
David Brazdil4525e0b2018-04-05 16:57:32 +01008468// Returns true if `method` is either null or hidden.
8469// Does not print any warnings if it is hidden.
8470static bool CheckNoSuchMethod(ArtMethod* method,
8471 ObjPtr<mirror::DexCache> dex_cache,
8472 ObjPtr<mirror::ClassLoader> class_loader)
8473 REQUIRES_SHARED(Locks::mutator_lock_) {
8474 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008475 hiddenapi::ShouldDenyAccessToMember(method,
8476 hiddenapi::AccessContext(class_loader, dex_cache),
8477 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008478}
8479
8480ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8481 ObjPtr<mirror::DexCache> dex_cache,
8482 ObjPtr<mirror::ClassLoader> class_loader,
8483 uint32_t method_idx) {
8484 if (klass->IsInterface()) {
8485 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8486 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8487 } else {
8488 // If there was an interface method with the same signature, we would have
8489 // found it in the "copied" methods. Only DCHECK that the interface method
8490 // really does not exist.
8491 if (kIsDebugBuild) {
8492 ArtMethod* method =
8493 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8494 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8495 }
8496 return nullptr;
8497 }
8498}
8499
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008500template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008501ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008502 Handle<mirror::DexCache> dex_cache,
8503 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008504 ArtMethod* referrer,
8505 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008506 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008507 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008508 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008509 PointerSize pointer_size = image_pointer_size_;
8510 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008511 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008512 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8513 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008514 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8515 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008516 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008517 return resolved;
8518 }
Vladimir Marko89011192017-12-11 13:45:05 +00008519 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008520 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008521 ObjPtr<mirror::Class> klass = nullptr;
8522 if (valid_dex_cache_method) {
8523 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8524 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008525 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008526 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008527 // We normaly should not end up here. However the verifier currently doesn't guarantee
8528 // the invariant of having the klass in the class table. b/73760543
8529 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008530 }
Vladimir Markoba118822017-06-12 15:41:56 +01008531 } else {
8532 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008533 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008534 if (klass == nullptr) {
8535 DCHECK(Thread::Current()->IsExceptionPending());
8536 return nullptr;
8537 }
8538 }
8539
8540 // Check if the invoke type matches the class type.
8541 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008542 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008543 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008544 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008545 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008546 }
Vladimir Markoba118822017-06-12 15:41:56 +01008547
8548 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008549 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008550 }
Vladimir Markoba118822017-06-12 15:41:56 +01008551
8552 // Note: We can check for IllegalAccessError only if we have a referrer.
8553 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8554 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8555 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8556 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8557 resolved,
8558 dex_cache.Get(),
8559 method_idx,
8560 type)) {
8561 DCHECK(Thread::Current()->IsExceptionPending());
8562 return nullptr;
8563 }
8564 }
8565
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008566 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008567 if (LIKELY(resolved != nullptr) &&
8568 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8569 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008570 return resolved;
8571 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008572 // If we had a method, or if we can find one with another lookup type,
8573 // it's an incompatible-class-change error.
8574 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008575 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008576 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008577 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008578 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008579 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008580 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008581 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8582 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008583 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008584 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008585 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008586 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008587 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008588}
8589
Vladimir Marko89011192017-12-11 13:45:05 +00008590ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008591 Handle<mirror::DexCache> dex_cache,
8592 Handle<mirror::ClassLoader> class_loader) {
8593 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008594 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008595 if (resolved != nullptr) {
8596 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008597 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8598 return resolved;
8599 }
8600 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008601 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008602 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008603 if (klass == nullptr) {
8604 Thread::Current()->AssertPendingException();
8605 return nullptr;
8606 }
8607 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008608 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8609 } else {
8610 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008611 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008612 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008613 hiddenapi::ShouldDenyAccessToMember(
8614 resolved,
8615 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8616 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008617 resolved = nullptr;
8618 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008619 return resolved;
8620}
8621
Vladimir Markof44d36c2017-03-14 14:18:46 +00008622ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8623 ObjPtr<mirror::DexCache> dex_cache,
8624 ObjPtr<mirror::ClassLoader> class_loader,
8625 bool is_static) {
8626 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008627 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008628 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8629 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008630 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008631 }
8632 if (klass == nullptr) {
8633 // The class has not been resolved yet, so the field is also unresolved.
8634 return nullptr;
8635 }
8636 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008637
David Brazdil1ab0fa82018-05-04 11:28:03 +01008638 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008639}
8640
Vladimir Markoe11dd502017-12-08 14:09:45 +00008641ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008642 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008643 Handle<mirror::ClassLoader> class_loader,
8644 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008645 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008646 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008647 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008648 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008649 return resolved;
8650 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008651 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008652 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008653 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008654 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008655 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008656 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008657 }
8658
David Brazdil1ab0fa82018-05-04 11:28:03 +01008659 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008660 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008661 const char* name = dex_file.GetFieldName(field_id);
8662 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008663 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008664 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008665 return resolved;
8666}
8667
Vladimir Markoe11dd502017-12-08 14:09:45 +00008668ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008669 Handle<mirror::DexCache> dex_cache,
8670 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008671 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008672 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008673 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008674 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008675 return resolved;
8676 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008677 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008678 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008679 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008680 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008681 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008682 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008683 }
8684
David Brazdil1ab0fa82018-05-04 11:28:03 +01008685 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8686 if (resolved == nullptr) {
8687 const char* name = dex_file.GetFieldName(field_id);
8688 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008689 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008690 }
8691 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008692}
8693
David Brazdil1ab0fa82018-05-04 11:28:03 +01008694ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8695 ObjPtr<mirror::DexCache> dex_cache,
8696 ObjPtr<mirror::ClassLoader> class_loader,
8697 uint32_t field_idx,
8698 bool is_static) {
8699 ArtField* resolved = nullptr;
8700 Thread* self = is_static ? Thread::Current() : nullptr;
8701 const DexFile& dex_file = *dex_cache->GetDexFile();
8702
8703 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8704 : klass->FindInstanceField(dex_cache, field_idx);
8705
8706 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008707 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008708 const char* name = dex_file.GetFieldName(field_id);
8709 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8710 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8711 : klass->FindInstanceField(name, type);
8712 }
8713
8714 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008715 hiddenapi::ShouldDenyAccessToMember(resolved,
8716 hiddenapi::AccessContext(class_loader, dex_cache),
8717 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008718 resolved = nullptr;
8719 }
8720
8721 if (resolved != nullptr) {
8722 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8723 }
8724
8725 return resolved;
8726}
8727
8728ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8729 ObjPtr<mirror::DexCache> dex_cache,
8730 ObjPtr<mirror::ClassLoader> class_loader,
8731 uint32_t field_idx) {
8732 ArtField* resolved = nullptr;
8733 Thread* self = Thread::Current();
8734 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008735 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008736
8737 const char* name = dex_file.GetFieldName(field_id);
8738 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8739 resolved = mirror::Class::FindField(self, klass, name, type);
8740
8741 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008742 hiddenapi::ShouldDenyAccessToMember(resolved,
8743 hiddenapi::AccessContext(class_loader, dex_cache),
8744 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008745 resolved = nullptr;
8746 }
8747
8748 if (resolved != nullptr) {
8749 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8750 }
8751
8752 return resolved;
8753}
8754
Vladimir Markoaf940202017-12-08 15:01:18 +00008755ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8756 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008757 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008758 Handle<mirror::DexCache> dex_cache,
8759 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008760 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008761 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008762
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008763 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008764 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008765 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008766 }
8767
Narayan Kamath25352fc2016-08-03 12:46:58 +01008768 StackHandleScope<4> hs(self);
8769
8770 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008771 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008772 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008773 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008774 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008775 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008776 DCHECK(self->IsExceptionPending());
8777 return nullptr;
8778 }
8779
8780 // Then resolve the argument types.
8781 //
8782 // TODO: Is there a better way to figure out the number of method arguments
8783 // other than by looking at the shorty ?
8784 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8785
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008786 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008787 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8788 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008789 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008790 DCHECK(self->IsExceptionPending());
8791 return nullptr;
8792 }
8793
8794 DexFileParameterIterator it(dex_file, proto_id);
8795 int32_t i = 0;
8796 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8797 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008798 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008799 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008800 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008801 DCHECK(self->IsExceptionPending());
8802 return nullptr;
8803 }
8804
8805 method_params->Set(i++, param_class.Get());
8806 }
8807
8808 DCHECK(!it.HasNext());
8809
8810 Handle<mirror::MethodType> type = hs.NewHandle(
8811 mirror::MethodType::Create(self, return_type, method_params));
8812 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8813
8814 return type.Get();
8815}
8816
Vladimir Markoaf940202017-12-08 15:01:18 +00008817ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008818 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008819 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008820 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008821 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8822 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008823 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008824}
8825
Vladimir Marko5aead702019-03-27 11:00:36 +00008826ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008827 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008828 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008829 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008830 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008831 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8832 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008833 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008834 bool is_static;
8835 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008836 switch (handle_type) {
8837 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008838 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008839 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008840 is_static = true;
8841 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008842 break;
8843 }
8844 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008845 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008846 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008847 is_static = true;
8848 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008849 break;
8850 }
8851 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008852 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008853 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008854 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008855 num_params = 2;
8856 break;
8857 }
8858 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008859 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008860 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008861 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008862 num_params = 1;
8863 break;
8864 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008865 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008866 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008867 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008868 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008869 case DexFile::MethodHandleType::kInvokeInterface:
8870 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008871 }
8872
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008873 ArtField* target_field =
8874 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8875 if (LIKELY(target_field != nullptr)) {
8876 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8877 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8878 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8879 ThrowIllegalAccessErrorField(referring_class, target_field);
8880 return nullptr;
8881 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008882 if (UNLIKELY(is_put && target_field->IsFinal())) {
8883 ThrowIllegalAccessErrorField(referring_class, target_field);
8884 return nullptr;
8885 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008886 } else {
8887 DCHECK(Thread::Current()->IsExceptionPending());
8888 return nullptr;
8889 }
8890
8891 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008892 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008893 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8894 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008895 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008896 DCHECK(self->IsExceptionPending());
8897 return nullptr;
8898 }
8899
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008900 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008901 Handle<mirror::Class> return_type;
8902 switch (handle_type) {
8903 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008904 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008905 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008906 break;
8907 }
8908 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008909 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008910 break;
8911 }
8912 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008913 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008914 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008915 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008916 break;
8917 }
8918 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008919 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008920 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008921 break;
8922 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008923 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008924 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008925 case DexFile::MethodHandleType::kInvokeConstructor:
8926 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008927 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008928 UNREACHABLE();
8929 }
8930
8931 for (int32_t i = 0; i < num_params; ++i) {
8932 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8933 DCHECK(self->IsExceptionPending());
8934 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008935 }
8936 }
8937
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008938 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008939 DCHECK(self->IsExceptionPending());
8940 return nullptr;
8941 }
8942
8943 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008944 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8945 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008946 DCHECK(self->IsExceptionPending());
8947 return nullptr;
8948 }
Orion Hodson631827d2017-04-10 14:53:47 +01008949
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008950 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8951 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8952}
8953
Vladimir Marko5aead702019-03-27 11:00:36 +00008954ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008955 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008956 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008957 ArtMethod* referrer) {
8958 DexFile::MethodHandleType handle_type =
8959 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8960 mirror::MethodHandle::Kind kind;
8961 uint32_t receiver_count = 0;
8962 ArtMethod* target_method = nullptr;
8963 switch (handle_type) {
8964 case DexFile::MethodHandleType::kStaticPut:
8965 case DexFile::MethodHandleType::kStaticGet:
8966 case DexFile::MethodHandleType::kInstancePut:
8967 case DexFile::MethodHandleType::kInstanceGet:
8968 UNREACHABLE();
8969 case DexFile::MethodHandleType::kInvokeStatic: {
8970 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8971 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008972 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8973 method_handle.field_or_method_idx_,
8974 referrer,
8975 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008976 break;
8977 }
8978 case DexFile::MethodHandleType::kInvokeInstance: {
8979 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8980 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008981 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8982 method_handle.field_or_method_idx_,
8983 referrer,
8984 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008985 break;
8986 }
8987 case DexFile::MethodHandleType::kInvokeConstructor: {
8988 // Constructors are currently implemented as a transform. They
8989 // are special cased later in this method.
8990 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8991 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008992 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8993 method_handle.field_or_method_idx_,
8994 referrer,
8995 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008996 break;
8997 }
8998 case DexFile::MethodHandleType::kInvokeDirect: {
8999 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9000 receiver_count = 1;
9001 StackHandleScope<2> hs(self);
9002 // A constant method handle with type kInvokeDirect can refer to
9003 // a method that is private or to a method in a super class. To
9004 // disambiguate the two options, we resolve the method ignoring
9005 // the invocation type to determine if the method is private. We
9006 // then resolve again specifying the intended invocation type to
9007 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009008 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009009 hs.NewHandle(referrer->GetDexCache()),
9010 hs.NewHandle(referrer->GetClassLoader()));
9011 if (UNLIKELY(target_method == nullptr)) {
9012 break;
9013 }
9014
9015 if (target_method->IsPrivate()) {
9016 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009017 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9018 method_handle.field_or_method_idx_,
9019 referrer,
9020 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009021 } else {
9022 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009023 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9024 method_handle.field_or_method_idx_,
9025 referrer,
9026 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009027 if (UNLIKELY(target_method == nullptr)) {
9028 break;
9029 }
9030 // Find the method specified in the parent in referring class
9031 // so invoke-super invokes the method in the parent of the
9032 // referrer.
9033 target_method =
9034 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9035 kRuntimePointerSize);
9036 }
9037 break;
9038 }
9039 case DexFile::MethodHandleType::kInvokeInterface: {
9040 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9041 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009042 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9043 method_handle.field_or_method_idx_,
9044 referrer,
9045 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009046 break;
9047 }
Orion Hodson631827d2017-04-10 14:53:47 +01009048 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009049
9050 if (UNLIKELY(target_method == nullptr)) {
9051 DCHECK(Thread::Current()->IsExceptionPending());
9052 return nullptr;
9053 }
9054
9055 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9056 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9057 uint32_t access_flags = target_method->GetAccessFlags();
9058 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9059 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9060 return nullptr;
9061 }
9062
9063 // Calculate the number of parameters from the method shorty. We add the
9064 // receiver count (0 or 1) and deduct one for the return value.
9065 uint32_t shorty_length;
9066 target_method->GetShorty(&shorty_length);
9067 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9068
Orion Hodsonecd58562018-09-24 11:27:33 +01009069 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009070 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009071 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9072 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9073 if (method_params.Get() == nullptr) {
9074 DCHECK(self->IsExceptionPending());
9075 return nullptr;
9076 }
9077
Orion Hodsonecd58562018-09-24 11:27:33 +01009078 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009079 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009080 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009081 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009082 // Insert receiver. Use the class identified in the method handle rather than the declaring
9083 // class of the resolved method which may be super class or default interface method
9084 // (b/115964401).
9085 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9086 // receiver_class should have been resolved when resolving the target method.
9087 DCHECK(receiver_class != nullptr);
9088 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009089 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009090
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009091 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009092 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009093 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009094 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009095 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009096 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009097 if (nullptr == klass) {
9098 DCHECK(self->IsExceptionPending());
9099 return nullptr;
9100 }
9101 method_params->Set(index++, klass);
9102 it.Next();
9103 }
9104
Orion Hodsonecd58562018-09-24 11:27:33 +01009105 Handle<mirror::Class> return_type =
9106 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009107 if (UNLIKELY(return_type.IsNull())) {
9108 DCHECK(self->IsExceptionPending());
9109 return nullptr;
9110 }
9111
9112 Handle<mirror::MethodType>
9113 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9114 if (UNLIKELY(method_type.IsNull())) {
9115 DCHECK(self->IsExceptionPending());
9116 return nullptr;
9117 }
9118
9119 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9120 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9121 Handle<mirror::MethodHandlesLookup> lookup =
9122 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9123 return lookup->FindConstructor(self, constructor_class, method_type);
9124 }
9125
9126 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9127 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9128}
9129
Vladimir Markoaf940202017-12-08 15:01:18 +00009130ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9131 uint32_t method_handle_idx,
9132 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009133 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009134 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009135 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009136 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9137 case DexFile::MethodHandleType::kStaticPut:
9138 case DexFile::MethodHandleType::kStaticGet:
9139 case DexFile::MethodHandleType::kInstancePut:
9140 case DexFile::MethodHandleType::kInstanceGet:
9141 return ResolveMethodHandleForField(self, method_handle, referrer);
9142 case DexFile::MethodHandleType::kInvokeStatic:
9143 case DexFile::MethodHandleType::kInvokeInstance:
9144 case DexFile::MethodHandleType::kInvokeConstructor:
9145 case DexFile::MethodHandleType::kInvokeDirect:
9146 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009147 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009148 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009149}
9150
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009151bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9152 return (entry_point == GetQuickResolutionStub()) ||
9153 (quick_resolution_trampoline_ == entry_point);
9154}
9155
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009156bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9157 return (entry_point == GetQuickToInterpreterBridge()) ||
9158 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9159}
9160
9161bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9162 return (entry_point == GetQuickGenericJniStub()) ||
9163 (quick_generic_jni_trampoline_ == entry_point);
9164}
9165
David Sehra49e0532017-08-25 08:05:29 -07009166bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9167 return entry_point == GetJniDlsymLookupStub();
9168}
9169
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009170const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9171 return GetQuickGenericJniStub();
9172}
9173
Mathieu Chartiere401d142015-04-22 13:56:20 -07009174void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009175 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009176 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9177 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009178 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009179 }
9180}
9181
Alex Lightdb01a092017-04-03 15:39:55 -07009182void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9183 DCHECK(method->IsObsolete());
9184 // We cannot mess with the entrypoints of native methods because they are used to determine how
9185 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9186 if (!method->IsNative()) {
9187 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9188 }
9189}
9190
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009191void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009192 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009193 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009194 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9195 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009196 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9197 os << "Dumping registered class loaders\n";
9198 size_t class_loader_index = 0;
9199 for (const ClassLoaderData& class_loader : class_loaders_) {
9200 ObjPtr<mirror::ClassLoader> loader =
9201 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9202 if (loader != nullptr) {
9203 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9204 bool saw_one_dex_file = false;
9205 for (const DexCacheData& dex_cache : dex_caches_) {
9206 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9207 if (saw_one_dex_file) {
9208 os << ":";
9209 }
9210 saw_one_dex_file = true;
9211 os << dex_cache.dex_file->GetLocation();
9212 }
9213 }
9214 os << "]";
9215 bool found_parent = false;
9216 if (loader->GetParent() != nullptr) {
9217 size_t parent_index = 0;
9218 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9219 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9220 soa.Self()->DecodeJObject(class_loader2.weak_root));
9221 if (loader2 == loader->GetParent()) {
9222 os << ", parent #" << parent_index;
9223 found_parent = true;
9224 break;
9225 }
9226 parent_index++;
9227 }
9228 if (!found_parent) {
9229 os << ", unregistered parent of type "
9230 << loader->GetParent()->GetClass()->PrettyDescriptor();
9231 }
9232 } else {
9233 os << ", no parent";
9234 }
9235 os << "\n";
9236 }
9237 }
9238 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009239}
9240
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009241class CountClassesVisitor : public ClassLoaderVisitor {
9242 public:
9243 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9244
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009245 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009246 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009247 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009248 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009249 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9250 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009251 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009252 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009253
9254 size_t num_zygote_classes;
9255 size_t num_non_zygote_classes;
9256};
9257
9258size_t ClassLinker::NumZygoteClasses() const {
9259 CountClassesVisitor visitor;
9260 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009261 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009262}
9263
9264size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009265 CountClassesVisitor visitor;
9266 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009267 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009268}
9269
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009270size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009271 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009272 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009273 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009274}
9275
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009276pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009277 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009278}
9279
9280pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009281 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009282}
9283
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009284void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009285 DCHECK(!init_done_);
9286
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009287 DCHECK(klass != nullptr);
9288 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009289
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009290 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009291 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009292 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9293 int32_t index = static_cast<int32_t>(class_root);
9294 DCHECK(class_roots->Get(index) == nullptr);
9295 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009296}
9297
Roland Levillain0e840272018-08-23 19:55:30 +01009298void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9299 ObjPtr<mirror::Class> java_lang_Class,
9300 ClassRoot primitive_array_class_root,
9301 ClassRoot primitive_class_root,
9302 const char* descriptor) {
9303 StackHandleScope<1> hs(self);
9304 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9305 AllocPrimitiveArrayClass(self, java_lang_Class)));
9306 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9307 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9308 CheckSystemClass(self, primitive_array_class, descriptor);
9309}
9310
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009311ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9312 Thread* self,
9313 const std::vector<const DexFile*>& dex_files,
9314 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009315 Handle<mirror::ClassLoader> parent_loader,
9316 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009317
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009318 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009319
Mathieu Chartierc7853442015-03-27 14:35:38 -07009320 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009321 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009322
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009323 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009324 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009325 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009326 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009327 mirror::ObjectArray<mirror::Object>::Alloc(self,
9328 dex_elements_class.Get(),
9329 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009330 Handle<mirror::Class> h_dex_element_class =
9331 hs.NewHandle(dex_elements_class->GetComponentType());
9332
Mathieu Chartierc7853442015-03-27 14:35:38 -07009333 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009334 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009335 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009336
Andreas Gampe08883de2016-11-08 13:20:52 -08009337 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009338 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009339
Andreas Gampe08883de2016-11-08 13:20:52 -08009340 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009341 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009342
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009343 // Fill the elements array.
9344 int32_t index = 0;
9345 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009346 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009347
Calin Juravle7865ac72017-06-28 11:03:12 -07009348 // CreateWellKnownClassLoader is only used by gtests and compiler.
9349 // 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 -07009350 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9351 self,
9352 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009353 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009354 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009355
Mathieu Chartier3738e982017-05-12 16:07:28 -07009356 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9357 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009358 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009359 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009360 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009361 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009362
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009363 Handle<mirror::String> h_file_name = hs2.NewHandle(
9364 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009365 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009366 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9367
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009368 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009369 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009370 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009371
9372 h_dex_elements->Set(index, h_element.Get());
9373 index++;
9374 }
9375 DCHECK_EQ(index, h_dex_elements->GetLength());
9376
9377 // Create DexPathList.
9378 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009379 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009380 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009381 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009382 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009383 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9384 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9385 // elements.
9386 {
9387 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9388 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9389 DCHECK(native_lib_dirs != nullptr);
9390 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9391 DCHECK(list_class != nullptr);
9392 {
9393 StackHandleScope<1> h_list_scope(self);
9394 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9395 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9396 DCHECK(list_init);
9397 list_class = h_list_class.Get();
9398 }
9399 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9400 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9401 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9402 // normally never null), as long as one does not try to add elements, this will still
9403 // work.
9404 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9405 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009406
Calin Juravle7865ac72017-06-28 11:03:12 -07009407 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009408 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9409 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009410 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009411 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009412 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009413 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009414 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009415 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009416
9417 // Make a pretend boot-classpath.
9418 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009419 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009420 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009421 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009422 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009423 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009424 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009425 if (parent_loader.Get() == nullptr) {
9426 ScopedObjectAccessUnchecked soa(self);
9427 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9428 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9429 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9430 } else {
9431 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9432 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009433
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009434 ArtField* shared_libraries_field =
9435 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9436 DCHECK(shared_libraries_field != nullptr);
9437 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9438
9439 return h_class_loader.Get();
9440}
9441
9442jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9443 const std::vector<const DexFile*>& dex_files,
9444 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009445 jobject parent_loader,
9446 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009447 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9448 WellKnownClasses::dalvik_system_PathClassLoader) ||
9449 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009450 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9451 self->GetJniEnv()->IsSameObject(loader_class,
9452 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009453
9454 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9455 // We could move the jobject to the callers, but all call-sites do this...
9456 ScopedObjectAccessUnchecked soa(self);
9457
9458 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009459 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009460
9461 Handle<mirror::Class> h_loader_class =
9462 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009463 Handle<mirror::ClassLoader> h_parent =
9464 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9465 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9466 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009467
9468 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9469 self,
9470 dex_files,
9471 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009472 h_parent,
9473 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009474
9475 // Make it a global ref and return.
9476 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009477 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009478 return soa.Env()->NewGlobalRef(local_ref.get());
9479}
9480
Calin Juravle7865ac72017-06-28 11:03:12 -07009481jobject ClassLinker::CreatePathClassLoader(Thread* self,
9482 const std::vector<const DexFile*>& dex_files) {
9483 return CreateWellKnownClassLoader(self,
9484 dex_files,
9485 WellKnownClasses::dalvik_system_PathClassLoader,
9486 nullptr);
9487}
9488
Andreas Gampe8ac75952015-06-02 21:01:45 -07009489void ClassLinker::DropFindArrayClassCache() {
9490 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9491 find_array_class_cache_next_victim_ = 0;
9492}
9493
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009494void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009495 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009496 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009497 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009498 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9499 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009500 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009501 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009502 }
9503 }
9504}
9505
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009506void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9507 for (const ClassLoaderData& data : class_loaders_) {
9508 LinearAlloc* alloc = data.allocator;
9509 if (alloc != nullptr && !visitor->Visit(alloc)) {
9510 break;
9511 }
9512 }
9513}
9514
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009515void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9516 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009517 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009518 Thread* const self = Thread::Current();
9519 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009520 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009521 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009522 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009523 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9524 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009525 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009526 }
9527}
9528
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009529void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009530 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009531 std::vector<ClassLoaderData> to_delete;
9532 // Do the delete outside the lock to avoid lock violation in jit code cache.
9533 {
9534 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9535 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9536 const ClassLoaderData& data = *it;
9537 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009538 ObjPtr<mirror::ClassLoader> class_loader =
9539 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009540 if (class_loader != nullptr) {
9541 ++it;
9542 } else {
9543 VLOG(class_linker) << "Freeing class loader";
9544 to_delete.push_back(data);
9545 it = class_loaders_.erase(it);
9546 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009547 }
9548 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009549 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009550 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009551 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009552 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009553}
9554
Vladimir Marko21300532017-01-24 18:06:55 +00009555class GetResolvedClassesVisitor : public ClassVisitor {
9556 public:
9557 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9558 : result_(result),
9559 ignore_boot_classes_(ignore_boot_classes),
9560 last_resolved_classes_(result->end()),
9561 last_dex_file_(nullptr),
9562 vlog_is_on_(VLOG_IS_ON(class_linker)),
9563 extra_stats_(),
9564 last_extra_stats_(extra_stats_.end()) { }
9565
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009566 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009567 if (!klass->IsProxyClass() &&
9568 !klass->IsArrayClass() &&
9569 klass->IsResolved() &&
9570 !klass->IsErroneousResolved() &&
9571 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9572 const DexFile& dex_file = klass->GetDexFile();
9573 if (&dex_file != last_dex_file_) {
9574 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009575 DexCacheResolvedClasses resolved_classes(
9576 dex_file.GetLocation(),
9577 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9578 dex_file.GetLocationChecksum(),
9579 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009580 last_resolved_classes_ = result_->find(resolved_classes);
9581 if (last_resolved_classes_ == result_->end()) {
9582 last_resolved_classes_ = result_->insert(resolved_classes).first;
9583 }
9584 }
9585 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9586 if (UNLIKELY(vlog_is_on_) && added) {
9587 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9588 if (last_extra_stats_ == extra_stats_.end() ||
9589 last_extra_stats_->first != resolved_classes) {
9590 last_extra_stats_ = extra_stats_.find(resolved_classes);
9591 if (last_extra_stats_ == extra_stats_.end()) {
9592 last_extra_stats_ =
9593 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9594 }
9595 }
9596 }
9597 }
9598 return true;
9599 }
9600
9601 void PrintStatistics() const {
9602 if (vlog_is_on_) {
9603 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9604 auto it = extra_stats_.find(std::addressof(resolved_classes));
9605 DCHECK(it != extra_stats_.end());
9606 const ExtraStats& extra_stats = it->second;
9607 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9608 << " has " << resolved_classes.GetClasses().size() << " / "
9609 << extra_stats.number_of_class_defs_ << " resolved classes";
9610 }
9611 }
9612 }
9613
9614 private:
9615 struct ExtraStats {
9616 explicit ExtraStats(uint32_t number_of_class_defs)
9617 : number_of_class_defs_(number_of_class_defs) {}
9618 uint32_t number_of_class_defs_;
9619 };
9620
9621 std::set<DexCacheResolvedClasses>* result_;
9622 bool ignore_boot_classes_;
9623 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9624 const DexFile* last_dex_file_;
9625
9626 // Statistics.
9627 bool vlog_is_on_;
9628 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9629 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9630};
9631
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009632std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009633 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009634 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009635 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009636 std::set<DexCacheResolvedClasses> ret;
9637 VLOG(class_linker) << "Collecting resolved classes";
9638 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009639 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9640 VisitClasses(&visitor);
9641 if (VLOG_IS_ON(class_linker)) {
9642 visitor.PrintStatistics();
9643 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009644 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009645 return ret;
9646}
9647
Mathieu Chartier65975772016-08-05 10:46:36 -07009648class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9649 public:
9650 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9651 : method_(method),
9652 pointer_size_(pointer_size) {}
9653
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009654 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009655 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9656 holder_ = klass;
9657 }
9658 // Return false to stop searching if holder_ is not null.
9659 return holder_ == nullptr;
9660 }
9661
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009662 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009663 const ArtMethod* const method_;
9664 const PointerSize pointer_size_;
9665};
9666
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009667ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009668 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9669 CHECK(method->IsCopied());
9670 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9671 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009672 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009673}
9674
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009675ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9676 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009677 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009678 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009679 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009680}
9681
Roland Levillain0e840272018-08-23 19:55:30 +01009682// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009683template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009684 uint32_t method_idx,
9685 Handle<mirror::DexCache> dex_cache,
9686 Handle<mirror::ClassLoader> class_loader,
9687 ArtMethod* referrer,
9688 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009689template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009690 uint32_t method_idx,
9691 Handle<mirror::DexCache> dex_cache,
9692 Handle<mirror::ClassLoader> class_loader,
9693 ArtMethod* referrer,
9694 InvokeType type);
9695
Roland Levillain0e840272018-08-23 19:55:30 +01009696// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009697template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009698 Thread* self,
9699 ObjPtr<mirror::Class> java_lang_Class,
9700 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009701template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009702 Thread* self,
9703 ObjPtr<mirror::Class> java_lang_Class,
9704 uint32_t class_size);
9705
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009706} // namespace art