blob: db79128014912ae094fb8156ddea42eda6850c59 [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);
3014 // Reserved conscrypt packages (includes sub-packages under these paths).
3015 return StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3016 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/");
3017}
3018
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003019ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3020 const char* descriptor,
3021 size_t hash,
3022 Handle<mirror::ClassLoader> class_loader,
3023 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003024 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003025 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003026 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003027
Brian Carlstromaded5f72011-10-07 17:15:04 -07003028 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003029 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003030 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003031 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003032 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003033 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003034 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003035 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003036 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003037 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003038 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003039 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003040 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003041 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003042 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003043 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003044 }
3045
Vladimir Markob9c29f62019-03-20 14:22:51 +00003046 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3047 // some runtime modules. Prevent definition of classes in app class loader that could clash
3048 // with these modules as these classes could be resolved differently during execution.
3049 if (class_loader != nullptr &&
3050 Runtime::Current()->IsAotCompiler() &&
3051 IsReservedBootClassPathDescriptor(descriptor)) {
3052 ObjPtr<mirror::Throwable> pre_allocated =
3053 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3054 self->SetException(pre_allocated);
3055 return nullptr;
3056 }
3057
Alex Lighte9f61032018-09-24 16:04:51 -07003058 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3059 // code to be executed. We put it up here so we can avoid all the allocations associated with
3060 // creating the class. This can happen with (eg) jit threads.
3061 if (!self->CanLoadClasses()) {
3062 // Make sure we don't try to load anything, potentially causing an infinite loop.
3063 ObjPtr<mirror::Throwable> pre_allocated =
3064 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3065 self->SetException(pre_allocated);
3066 return nullptr;
3067 }
3068
Andreas Gampefa4333d2017-02-14 11:10:34 -08003069 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003070 // Allocate a class with the status of not ready.
3071 // Interface object should get the right size here. Regular class will
3072 // figure out the right size later and be replaced with one of the right
3073 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003074 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003075 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003076 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003077 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003078 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003079 }
Alex Lightb0f11922017-01-23 14:25:17 -08003080 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3081 // nothing.
3082 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003083 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003084 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3085 // will only be called once.
3086 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3087 klass,
3088 class_loader,
3089 dex_file,
3090 dex_class_def,
3091 &new_dex_file,
3092 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003093 // Check to see if an exception happened during runtime callbacks. Return if so.
3094 if (self->IsExceptionPending()) {
3095 return nullptr;
3096 }
Alex Lightb0f11922017-01-23 14:25:17 -08003097 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003098 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003099 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003100 return nullptr;
3101 }
3102 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003103 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003104
Jeff Hao848f70a2014-01-15 13:49:50 -08003105 // Mark the string class by setting its access flag.
3106 if (UNLIKELY(!init_done_)) {
3107 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3108 klass->SetStringClass();
3109 }
3110 }
3111
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003112 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003113 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003114 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003115 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003116
Mathieu Chartier590fee92013-09-13 13:46:47 -07003117 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003118 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003119 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003120 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3121 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003122 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003123 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003124
Mathieu Chartierc7853442015-03-27 14:35:38 -07003125 // Load the fields and other things after we are inserted in the table. This is so that we don't
3126 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3127 // other reason is that the field roots are only visited from the class table. So we need to be
3128 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003129 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003130 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003131 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003132 // An exception occured during load, set status to erroneous while holding klass' lock in case
3133 // notification is necessary.
3134 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003135 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003136 }
3137 return nullptr;
3138 }
3139
Brian Carlstromaded5f72011-10-07 17:15:04 -07003140 // Finish loading (if necessary) by finding parents
3141 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003142 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003143 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003144 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003145 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003146 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003147 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003148 }
3149 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003150
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003151 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003152 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003153 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003154
Brian Carlstromaded5f72011-10-07 17:15:04 -07003155 // Link the class (if necessary)
3156 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003157 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003158 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003159
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003160 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003161 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003162 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003163 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003164 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003165 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003166 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003167 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003168 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003169 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003170 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003171
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003172 // Instrumentation may have updated entrypoints for all methods of all
3173 // classes. However it could not update methods of this class while we
3174 // were loading it. Now the class is resolved, we can update entrypoints
3175 // as required by instrumentation.
3176 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3177 // We must be in the kRunnable state to prevent instrumentation from
3178 // suspending all threads to update entrypoints while we are doing it
3179 // for this class.
3180 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003181 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003182 }
3183
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003184 /*
3185 * We send CLASS_PREPARE events to the debugger from here. The
3186 * definition of "preparation" is creating the static fields for a
3187 * class and initializing them to the standard default values, but not
3188 * executing any code (that comes later, during "initialization").
3189 *
3190 * We did the static preparation in LinkClass.
3191 *
3192 * The class has been prepared and resolved but possibly not yet verified
3193 * at this point.
3194 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003195 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003196
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003197 // Notify native debugger of the new class and its layout.
3198 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3199
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003200 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003201}
3202
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003203uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003204 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003205 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003206 size_t num_8 = 0;
3207 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003208 size_t num_32 = 0;
3209 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003210 ClassAccessor accessor(dex_file, dex_class_def);
3211 // We allow duplicate definitions of the same field in a class_data_item
3212 // but ignore the repeated indexes here, b/21868015.
3213 uint32_t last_field_idx = dex::kDexNoIndex;
3214 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3215 uint32_t field_idx = field.GetIndex();
3216 // Ordering enforced by DexFileVerifier.
3217 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3218 if (UNLIKELY(field_idx == last_field_idx)) {
3219 continue;
3220 }
3221 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003222 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003223 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3224 char c = descriptor[0];
3225 switch (c) {
3226 case 'L':
3227 case '[':
3228 num_ref++;
3229 break;
3230 case 'J':
3231 case 'D':
3232 num_64++;
3233 break;
3234 case 'I':
3235 case 'F':
3236 num_32++;
3237 break;
3238 case 'S':
3239 case 'C':
3240 num_16++;
3241 break;
3242 case 'B':
3243 case 'Z':
3244 num_8++;
3245 break;
3246 default:
3247 LOG(FATAL) << "Unknown descriptor: " << c;
3248 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003249 }
3250 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003251 return mirror::Class::ComputeClassSize(false,
3252 0,
3253 num_8,
3254 num_16,
3255 num_32,
3256 num_64,
3257 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003258 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003259}
3260
Alex Lightfc49fec2018-01-16 22:28:36 +00003261// Special case to get oat code without overwriting a trampoline.
3262const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003263 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003264 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003265 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003266 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003267 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3268 if (code != nullptr) {
3269 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003270 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003271 if (method->IsNative()) {
3272 // No code and native? Use generic trampoline.
3273 return GetQuickGenericJniStub();
3274 }
3275 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003276}
3277
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003278bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003279 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003280 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3281 return false;
3282 }
3283
Elliott Hughes956af0f2014-12-11 14:34:28 -08003284 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003285 return true;
3286 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003287
3288 Runtime* runtime = Runtime::Current();
3289 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3290 if (instr->InterpretOnly()) {
3291 return true;
3292 }
3293
3294 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3295 // Doing this check avoids doing compiled/interpreter transitions.
3296 return true;
3297 }
3298
Alex Light3dacdd62019-03-12 15:45:47 +00003299 if (Thread::Current()->IsForceInterpreter() ||
3300 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003301 // Force the use of interpreter when it is required by the debugger.
3302 return true;
3303 }
3304
Alex Light8f34aba2017-10-09 13:46:32 -07003305 if (Thread::Current()->IsAsyncExceptionPending()) {
3306 // Force use of interpreter to handle async-exceptions
3307 return true;
3308 }
3309
Alex Light2d441b12018-06-08 15:33:21 -07003310 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3311 const void* instr_target = instr->GetCodeForInvoke(method);
3312 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3313 return ShouldUseInterpreterEntrypoint(method, instr_target);
3314 }
3315
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003316 if (runtime->IsJavaDebuggable()) {
3317 // For simplicity, we ignore precompiled code and go to the interpreter
3318 // assuming we don't already have jitted code.
3319 // We could look at the oat file where `quick_code` is being defined,
3320 // and check whether it's been compiled debuggable, but we decided to
3321 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003322 jit::Jit* jit = Runtime::Current()->GetJit();
3323 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3324 }
3325
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003326 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003327 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003328 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003329 // since we want to JIT it (at first use) with extra stackmaps for native
3330 // debugging. We keep however all AOT code from the boot image,
3331 // since the JIT-at-first-use is blocking and would result in non-negligible
3332 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003333 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003334 }
3335
3336 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003337}
3338
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003339void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003340 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003341 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003342 if (klass->NumDirectMethods() == 0) {
3343 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003344 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003345 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003346 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003347 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003348 return; // OAT file unavailable.
3349 }
Ian Rogers19846512012-02-24 11:42:47 -08003350 }
Alex Light64ad14d2014-08-19 14:23:13 -07003351
Mathieu Chartierf8322842014-05-16 10:59:25 -07003352 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003353 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3354 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3355 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003356 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003357 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003358 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003359 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3360 klass->GetDexClassDefIndex(),
3361 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003362 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003363 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003364 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003365 if (!method->IsStatic()) {
3366 // Only update static methods.
3367 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003368 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003369 const void* quick_code = nullptr;
3370 if (has_oat_class) {
3371 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003372 quick_code = oat_method.GetQuickCode();
3373 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003374 // Check whether the method is native, in which case it's generic JNI.
3375 if (quick_code == nullptr && method->IsNative()) {
3376 quick_code = GetQuickGenericJniStub();
3377 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003378 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003379 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003380 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003381 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003382 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003383 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003384}
3385
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003386// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3387// method. Should only be called on non-invokable methods.
3388inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003389 DCHECK(method != nullptr);
3390 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003391 method->SetEntryPointFromQuickCompiledCodePtrSize(
3392 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3393 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003394}
3395
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003396static void LinkCode(ClassLinker* class_linker,
3397 ArtMethod* method,
3398 const OatFile::OatClass* oat_class,
3399 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003400 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003401 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003402 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003403 // The following code only applies to a non-compiler runtime.
3404 return;
3405 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003406 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003407 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003408 if (oat_class != nullptr) {
3409 // Every kind of method should at least get an invoke stub from the oat_method.
3410 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003411 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003412 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003413 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003414
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003415 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003416 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003417 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003418
Alex Light9139e002015-10-09 15:59:48 -07003419 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003420 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003421 return;
3422 }
Ian Rogers19846512012-02-24 11:42:47 -08003423
3424 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003425 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003426 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3427 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003428 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003429 } else if (quick_code == nullptr && method->IsNative()) {
3430 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003431 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003432 // Set entry point from compiled code if there's no code or in interpreter only mode.
3433 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003434 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003435
Ian Rogers62d6c772013-02-27 08:32:07 -08003436 if (method->IsNative()) {
3437 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003438 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003439
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003440 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003441 // We have a native method here without code. Then it should have either the generic JNI
3442 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3443 // TODO: this doesn't handle all the cases where trampolines may be installed.
3444 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003445 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3446 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003447 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003448 }
3449}
3450
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003451void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003452 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003453 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003454 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003455 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003456 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003457 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003458 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003459 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003460
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003461 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003462 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003463 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003464 klass->SetAccessFlags(access_flags);
3465 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003466 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003467 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003468
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003469 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003470 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003471}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003472
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003473LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3474 LinearAlloc* allocator,
3475 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003476 if (length == 0) {
3477 return nullptr;
3478 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003479 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3480 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3481 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003482 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003483 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003484 CHECK(ret != nullptr);
3485 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3486 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003487}
3488
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003489LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3490 LinearAlloc* allocator,
3491 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003492 if (length == 0) {
3493 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003494 }
Vladimir Marko14632852015-08-17 12:07:23 +01003495 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3496 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003497 const size_t storage_size =
3498 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003499 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003500 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003501 CHECK(ret != nullptr);
3502 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003503 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003504 }
3505 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003506}
3507
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003508LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003509 if (class_loader == nullptr) {
3510 return Runtime::Current()->GetLinearAlloc();
3511 }
3512 LinearAlloc* allocator = class_loader->GetAllocator();
3513 DCHECK(allocator != nullptr);
3514 return allocator;
3515}
3516
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003517LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003518 if (class_loader == nullptr) {
3519 return Runtime::Current()->GetLinearAlloc();
3520 }
3521 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3522 LinearAlloc* allocator = class_loader->GetAllocator();
3523 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003524 RegisterClassLoader(class_loader);
3525 allocator = class_loader->GetAllocator();
3526 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003527 }
3528 return allocator;
3529}
3530
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003531void ClassLinker::LoadClass(Thread* self,
3532 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003533 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003534 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003535 ClassAccessor accessor(dex_file,
3536 dex_class_def,
3537 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003538 if (!accessor.HasClassData()) {
3539 return;
3540 }
3541 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003542 {
3543 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3544 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003545 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003546 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003547 // We allow duplicate definitions of the same field in a class_data_item
3548 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003549 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003550 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3551 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003552 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003553 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3554 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003555 accessor.NumInstanceFields());
3556 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003557 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003558 uint32_t last_static_field_idx = 0u;
3559 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003560
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003561 // Methods
3562 bool has_oat_class = false;
3563 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3564 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3565 : OatFile::OatClass::Invalid();
3566 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3567 klass->SetMethodsPtr(
3568 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3569 accessor.NumDirectMethods(),
3570 accessor.NumVirtualMethods());
3571 size_t class_def_method_index = 0;
3572 uint32_t last_dex_method_index = dex::kDexNoIndex;
3573 size_t last_class_def_method_index = 0;
3574
3575 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3576 // methods needs to decode all of the fields.
3577 accessor.VisitFieldsAndMethods([&](
3578 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3579 uint32_t field_idx = field.GetIndex();
3580 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3581 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3582 LoadField(field, klass, &sfields->At(num_sfields));
3583 ++num_sfields;
3584 last_static_field_idx = field_idx;
3585 }
3586 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3587 uint32_t field_idx = field.GetIndex();
3588 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3589 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3590 LoadField(field, klass, &ifields->At(num_ifields));
3591 ++num_ifields;
3592 last_instance_field_idx = field_idx;
3593 }
3594 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3595 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3596 image_pointer_size_);
3597 LoadMethod(dex_file, method, klass, art_method);
3598 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3599 uint32_t it_method_index = method.GetIndex();
3600 if (last_dex_method_index == it_method_index) {
3601 // duplicate case
3602 art_method->SetMethodIndex(last_class_def_method_index);
3603 } else {
3604 art_method->SetMethodIndex(class_def_method_index);
3605 last_dex_method_index = it_method_index;
3606 last_class_def_method_index = class_def_method_index;
3607 }
3608 ++class_def_method_index;
3609 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3610 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3611 class_def_method_index - accessor.NumDirectMethods(),
3612 image_pointer_size_);
3613 LoadMethod(dex_file, method, klass, art_method);
3614 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3615 ++class_def_method_index;
3616 });
3617
3618 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003619 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003620 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3621 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3622 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003623 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3624 if (sfields != nullptr) {
3625 sfields->SetSize(num_sfields);
3626 }
3627 if (ifields != nullptr) {
3628 ifields->SetSize(num_ifields);
3629 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003630 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003631 // Set the field arrays.
3632 klass->SetSFieldsPtr(sfields);
3633 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003634 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003635 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003636 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003637 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003638 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003639 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003640}
3641
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003642void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003643 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003644 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003645 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003646 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003647 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003648
David Brazdil85865692018-10-30 17:26:20 +00003649 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3650 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003651}
3652
Mathieu Chartier268764d2016-09-13 12:09:38 -07003653void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003654 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003655 Handle<mirror::Class> klass,
3656 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003657 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003658 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003659 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003660
Mathieu Chartier268764d2016-09-13 12:09:38 -07003661 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003662 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003663 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003664 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003665
David Brazdil85865692018-10-30 17:26:20 +00003666 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3667 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003668
Ian Rogersdfb325e2013-10-30 01:00:44 -07003669 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003670 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003671 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3672 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003673 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003674 klass->SetFinalizable();
3675 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003676 std::string temp;
3677 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003678 // The Enum class declares a "final" finalize() method to prevent subclasses from
3679 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3680 // subclasses, so we exclude it here.
3681 // We also want to avoid setting the flag on Object, where we know that finalize() is
3682 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003683 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3684 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003685 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003686 }
3687 }
3688 }
3689 } else if (method_name[0] == '<') {
3690 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003691 bool is_init = (strcmp("<init>", method_name) == 0);
3692 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003693 if (UNLIKELY(!is_init && !is_clinit)) {
3694 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3695 } else {
3696 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3697 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003698 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003699 access_flags |= kAccConstructor;
3700 }
3701 }
3702 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003703 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3704 // Check if the native method is annotated with @FastNative or @CriticalNative.
3705 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3706 dex_file, dst->GetClassDef(), dex_method_idx);
3707 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003708 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003709 // Must be done after SetAccessFlags since IsAbstract depends on it.
3710 if (klass->IsInterface() && dst->IsAbstract()) {
3711 dst->CalculateAndSetImtIndex();
3712 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003713}
3714
Ian Rogers7b078e82014-09-10 14:44:24 -07003715void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003716 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003717 self,
3718 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003719 Runtime::Current()->GetLinearAlloc());
3720 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003721 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003722}
3723
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003724void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003725 ObjPtr<mirror::DexCache> dex_cache) {
3726 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003727 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003728 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003729 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003730}
3731
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003732void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003733 ObjPtr<mirror::DexCache> dex_cache,
3734 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003735 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003736 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003737 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003738 // For app images, the dex cache location may be a suffix of the dex file location since the
3739 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003740 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3741 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003742 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3743 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003744 // The following paths checks don't work on preopt when using boot dex files, where the dex
3745 // cache location is the one on device, and the dex_file's location is the one on host.
3746 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3747 CHECK_GE(dex_file_location.length(), dex_cache_length)
3748 << dex_cache_location << " " << dex_file.GetLocation();
3749 const std::string dex_file_suffix = dex_file_location.substr(
3750 dex_file_location.length() - dex_cache_length,
3751 dex_cache_length);
3752 // Example dex_cache location is SettingsProvider.apk and
3753 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3754 CHECK_EQ(dex_cache_location, dex_file_suffix);
3755 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003756 const OatFile* oat_file =
3757 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003758 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3759 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3760 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3761 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003762 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003763 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3764 DexCacheData data = *it;
3765 if (self->IsJWeakCleared(data.weak_root)) {
3766 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003767 it = dex_caches_.erase(it);
3768 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003769 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003770 it->dex_file->GetOatDexFile() != nullptr &&
3771 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003772 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003773 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003774 ++it;
3775 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003776 }
Vladimir Markob066d432018-01-03 13:14:37 +00003777 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003778 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003779 }
David Brazdila5c3a802019-03-08 14:59:41 +00003780 // Let hiddenapi assign a domain to the newly registered dex file.
3781 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3782
Vladimir Markocd556b02017-02-03 11:47:34 +00003783 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003784 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003785 DexCacheData data;
3786 data.weak_root = dex_cache_jweak;
3787 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003788 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003789 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003790 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003791 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3792 // path dex caches without an image.
3793 data.class_table->InsertStrongRoot(dex_cache);
3794 if (class_loader != nullptr) {
3795 // Since we added a strong root to the class table, do the write barrier as required for
3796 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003797 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003798 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003799 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003800}
3801
Vladimir Markocd556b02017-02-03 11:47:34 +00003802ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3803 return data.IsValid()
3804 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3805 : nullptr;
3806}
3807
3808ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3809 Thread* self,
3810 ObjPtr<mirror::DexCache> dex_cache,
3811 const DexCacheData& data,
3812 ObjPtr<mirror::ClassLoader> class_loader) {
3813 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3814 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3815 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3816 "Attempt to register dex file %s with multiple class loaders",
3817 data.dex_file->GetLocation().c_str());
3818 return nullptr;
3819 }
3820 return dex_cache;
3821}
3822
Alex Light07f06212017-06-01 14:01:43 -07003823void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3824 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003825 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003826 Thread* self = Thread::Current();
3827 StackHandleScope<2> hs(self);
3828 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3829 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3830 const DexFile* dex_file = dex_cache->GetDexFile();
3831 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3832 if (kIsDebugBuild) {
3833 DexCacheData old_data;
3834 {
3835 ReaderMutexLock mu(self, *Locks::dex_lock_);
3836 old_data = FindDexCacheDataLocked(*dex_file);
3837 }
3838 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3839 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3840 << "been registered on dex file " << dex_file->GetLocation();
3841 }
3842 ClassTable* table;
3843 {
3844 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3845 table = InsertClassTableForClassLoader(h_class_loader.Get());
3846 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003847 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3848 // a thread holding the dex lock and blocking on a condition variable regarding
3849 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003850 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003851 WriterMutexLock mu(self, *Locks::dex_lock_);
3852 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3853 table->InsertStrongRoot(h_dex_cache.Get());
3854 if (h_class_loader.Get() != nullptr) {
3855 // Since we added a strong root to the class table, do the write barrier as required for
3856 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003857 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003858 }
3859}
3860
Vladimir Markocd556b02017-02-03 11:47:34 +00003861ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3862 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003863 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003864 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003865 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003866 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003867 old_data = FindDexCacheDataLocked(dex_file);
3868 }
3869 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3870 if (old_dex_cache != nullptr) {
3871 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003872 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003873 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003874 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3875 DCHECK(linear_alloc != nullptr);
3876 ClassTable* table;
3877 {
3878 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3879 table = InsertClassTableForClassLoader(class_loader);
3880 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003881 // Don't alloc while holding the lock, since allocation may need to
3882 // suspend all threads and another thread may need the dex_lock_ to
3883 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003884 StackHandleScope<3> hs(self);
3885 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003886 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003887 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3888 self,
3889 dex_file)));
3890 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003891 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003892 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3893 // a thread holding the dex lock and blocking on a condition variable regarding
3894 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003895 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003896 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003897 old_data = FindDexCacheDataLocked(dex_file);
3898 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003899 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003900 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3901 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3902 // that the arrays are null.
3903 mirror::DexCache::InitializeDexCache(self,
3904 h_dex_cache.Get(),
3905 h_location.Get(),
3906 &dex_file,
3907 linear_alloc,
3908 image_pointer_size_);
3909 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003910 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003911 }
3912 if (old_dex_cache != nullptr) {
3913 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3914 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003915 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003916 self->ClearException();
3917 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3918 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3919 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003920 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003921 self->AssertPendingOOMException();
3922 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003923 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003924 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003925 if (h_class_loader.Get() != nullptr) {
3926 // Since we added a strong root to the class table, do the write barrier as required for
3927 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003928 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003929 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003930 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003931}
3932
Vladimir Markocd556b02017-02-03 11:47:34 +00003933bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003934 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003935 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003936}
3937
Vladimir Markocd556b02017-02-03 11:47:34 +00003938ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3939 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003940 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3941 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003942 if (dex_cache != nullptr) {
3943 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003944 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003945 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003946 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003947 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003948 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003949 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003950 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003951 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3952 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003953 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003954}
3955
Vladimir Markocd556b02017-02-03 11:47:34 +00003956ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3957 const DexFile* dex_file = dex_cache->GetDexFile();
3958 DCHECK(dex_file != nullptr);
3959 ReaderMutexLock mu(self, *Locks::dex_lock_);
3960 // Search assuming unique-ness of dex file.
3961 for (const DexCacheData& data : dex_caches_) {
3962 // Avoid decoding (and read barriers) other unrelated dex caches.
3963 if (data.dex_file == dex_file) {
3964 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3965 if (registered_dex_cache != nullptr) {
3966 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3967 return data.class_table;
3968 }
3969 }
3970 }
3971 return nullptr;
3972}
3973
3974ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3975 // Search assuming unique-ness of dex file.
3976 for (const DexCacheData& data : dex_caches_) {
3977 // Avoid decoding (and read barriers) other unrelated dex caches.
3978 if (data.dex_file == &dex_file) {
3979 return data;
3980 }
3981 }
3982 return DexCacheData();
3983}
3984
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003985ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003986 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003987 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003988 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003989 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003990 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003991 }
Ian Rogers1f539342012-10-03 21:09:42 -07003992 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003993 StackHandleScope<1> hs(self);
3994 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003995 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003996 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3997 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003998 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003999 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004000 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004001 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004002 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4003 h_class.Get(),
4004 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004005 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004006 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004007}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004008
Vladimir Marko02610552018-06-04 14:38:00 +01004009inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4010 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4011}
4012
Brian Carlstrombe977852011-07-19 14:54:54 -07004013// Create an array class (i.e. the class object for the array, not the
4014// array itself). "descriptor" looks like "[C" or "[[[[B" or
4015// "[Ljava/lang/String;".
4016//
4017// If "descriptor" refers to an array of primitives, look up the
4018// primitive type's internally-generated class object.
4019//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004020// "class_loader" is the class loader of the class that's referring to
4021// us. It's used to ensure that we're looking for the element type in
4022// the right context. It does NOT become the class loader for the
4023// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004024//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004025// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004026ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4027 const char* descriptor,
4028 size_t hash,
4029 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004030 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004031 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004032 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004033
4034 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4035 // code to be executed. We put it up here so we can avoid all the allocations associated with
4036 // creating the class. This can happen with (eg) jit threads.
4037 if (!self->CanLoadClasses()) {
4038 // Make sure we don't try to load anything, potentially causing an infinite loop.
4039 ObjPtr<mirror::Throwable> pre_allocated =
4040 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4041 self->SetException(pre_allocated);
4042 return nullptr;
4043 }
4044
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004045 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4046 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004047 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004048 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004049 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004050 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4051 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004052 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004053 DCHECK(self->IsExceptionPending());
4054 return nullptr;
4055 } else {
4056 self->ClearException();
4057 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004058 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004059 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4060 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4061 return nullptr;
4062 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004063 // See if the component type is already loaded. Array classes are
4064 // always associated with the class loader of their underlying
4065 // element type -- an array of Strings goes with the loader for
4066 // java/lang/String -- so we need to look for it there. (The
4067 // caller should have checked for the existence of the class
4068 // before calling here, but they did so with *their* class loader,
4069 // not the component type's loader.)
4070 //
4071 // If we find it, the caller adds "loader" to the class' initiating
4072 // loader list, which should prevent us from going through this again.
4073 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004074 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004075 // are the same, because our caller (FindClass) just did the
4076 // lookup. (Even if we get this wrong we still have correct behavior,
4077 // because we effectively do this lookup again when we add the new
4078 // class to the hash table --- necessary because of possible races with
4079 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004080 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004081 ObjPtr<mirror::Class> new_class =
4082 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004083 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004084 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004085 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004086 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004087
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004088 // Fill out the fields in the Class.
4089 //
4090 // It is possible to execute some methods against arrays, because
4091 // all arrays are subclasses of java_lang_Object_, so we need to set
4092 // up a vtable. We can just point at the one in java_lang_Object_.
4093 //
4094 // Array classes are simple enough that we don't need to do a full
4095 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004096 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004097 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004098 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004099 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004100 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004101 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004102 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4103 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4104 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004105 } else if (strcmp(descriptor, "[Z") == 0) {
4106 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4107 } else if (strcmp(descriptor, "[B") == 0) {
4108 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4109 } else if (strcmp(descriptor, "[C") == 0) {
4110 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4111 } else if (strcmp(descriptor, "[S") == 0) {
4112 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004113 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004114 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004115 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004116 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004117 } else if (strcmp(descriptor, "[F") == 0) {
4118 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4119 } else if (strcmp(descriptor, "[D") == 0) {
4120 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004121 }
4122 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004123 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004124 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004125 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004126 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004127 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004128 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004129 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004130 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004131 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004132 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004133 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004134 new_class->SetSuperClass(java_lang_Object);
4135 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004136 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004137 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004138 if (component_type->IsPrimitive()) {
4139 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4140 } else {
4141 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4142 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004143 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004144 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4145 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4146 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004147 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004148 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004149 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004150 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004151
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004152 // All arrays have java/lang/Cloneable and java/io/Serializable as
4153 // interfaces. We need to set that up here, so that stuff like
4154 // "instanceof" works right.
4155 //
4156 // Note: The GC could run during the call to FindSystemClass,
4157 // so we need to make sure the class object is GC-valid while we're in
4158 // there. Do this by clearing the interface list so the GC will just
4159 // think that the entries are null.
4160
4161
4162 // Use the single, global copies of "interfaces" and "iftable"
4163 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004164 {
Vladimir Marko02610552018-06-04 14:38:00 +01004165 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004166 CHECK(array_iftable != nullptr);
4167 new_class->SetIfTable(array_iftable);
4168 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004169
Elliott Hughes00626c22013-06-14 15:04:14 -07004170 // Inherit access flags from the component type.
4171 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4172 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4173 access_flags &= kAccJavaFlagsMask;
4174 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004175 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004176 access_flags |= kAccAbstract | kAccFinal;
4177 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004178 // Arrays are access-checks-clean and preverified.
4179 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004180
4181 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004182
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004183 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004184 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004185 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4186 // duplicate events in case of races. Array classes don't really follow dedicated
4187 // load and prepare, anyways.
4188 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4189 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4190
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004191 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004192 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004193 }
4194 // Another thread must have loaded the class after we
4195 // started but before we finished. Abandon what we've
4196 // done.
4197 //
4198 // (Yes, this happens.)
4199
Vladimir Markobcf17522018-06-01 13:14:32 +01004200 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004201}
4202
Vladimir Marko9186b182018-11-06 14:55:54 +00004203ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4204 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004205 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004206 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4207 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4208 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4209 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4210 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4211 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4212 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4213 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4214 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004215 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004216 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004217 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004218 return GetClassRoot(class_root, this);
4219}
4220
4221ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4222 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4223 if (UNLIKELY(result == nullptr)) {
4224 std::string printable_type(PrintableChar(type));
4225 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4226 }
4227 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004228}
4229
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004230ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4231 ObjPtr<mirror::Class> klass,
4232 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004233 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004234 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004235 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004236 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004237 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004238 source += " from ";
4239 source += dex_cache->GetLocation()->ToModifiedUtf8();
4240 }
4241 LOG(INFO) << "Loaded class " << descriptor << source;
4242 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004243 {
4244 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004245 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004246 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004247 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004248 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004249 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004250 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004251 VerifyObject(klass);
4252 class_table->InsertWithHash(klass, hash);
4253 if (class_loader != nullptr) {
4254 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004255 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004256 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004257 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004258 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004259 }
4260 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004261 if (kIsDebugBuild) {
4262 // Test that copied methods correctly can find their holder.
4263 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4264 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4265 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004266 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004267 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004268}
4269
Vladimir Marko1998cd02017-01-13 13:02:58 +00004270void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004271 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4272 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4273 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4274 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004275 }
4276}
4277
Alex Lighte64300b2015-12-15 15:02:47 -08004278// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004279void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004280 LengthPrefixedArray<ArtMethod>* new_methods) {
4281 klass->SetMethodsPtrUnchecked(new_methods,
4282 klass->NumDirectMethods(),
4283 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004284 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004285 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004286}
4287
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004288ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4289 const char* descriptor,
4290 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004291 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4292}
4293
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004294ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4295 const char* descriptor,
4296 size_t hash,
4297 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004298 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4299 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4300 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004301 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004302 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004303 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004304 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004305 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004306 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004307}
4308
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004309class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4310 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004311 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004312
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004313 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004314 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004315 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004316 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004317 if (class_table != nullptr) {
4318 class_table->FreezeSnapshot();
4319 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004320 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004321};
4322
4323void ClassLinker::MoveClassTableToPreZygote() {
4324 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004325 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004326 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004327 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004328}
4329
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004330// Look up classes by hash and descriptor and put all matching ones in the result array.
4331class LookupClassesVisitor : public ClassLoaderVisitor {
4332 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004333 LookupClassesVisitor(const char* descriptor,
4334 size_t hash,
4335 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004336 : descriptor_(descriptor),
4337 hash_(hash),
4338 result_(result) {}
4339
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004340 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004341 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004342 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004343 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004344 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4345 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004346 result_->push_back(klass);
4347 }
4348 }
4349
4350 private:
4351 const char* const descriptor_;
4352 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004353 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004354};
4355
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004356void ClassLinker::LookupClasses(const char* descriptor,
4357 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004358 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004359 Thread* const self = Thread::Current();
4360 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004361 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004362 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004363 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004364 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004365 result.push_back(klass);
4366 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004367 LookupClassesVisitor visitor(descriptor, hash, &result);
4368 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004369}
4370
Alex Lightf1f10492015-10-07 16:08:36 -07004371bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4372 Handle<mirror::Class> klass,
4373 Handle<mirror::Class> supertype) {
4374 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004375 DCHECK(klass != nullptr);
4376 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004377
Alex Lightf1f10492015-10-07 16:08:36 -07004378 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4379 VerifyClass(self, supertype);
4380 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004381
4382 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4383 // The supertype is either verified, or we soft failed at AOT time.
4384 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004385 return true;
4386 }
4387 // If we got this far then we have a hard failure.
4388 std::string error_msg =
4389 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004390 klass->PrettyDescriptor().c_str(),
4391 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004392 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004393 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004394 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004395 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004396 // Set during VerifyClass call (if at all).
4397 self->ClearException();
4398 }
4399 // Change into a verify error.
4400 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004401 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004402 self->GetException()->SetCause(cause.Get());
4403 }
4404 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4405 if (Runtime::Current()->IsAotCompiler()) {
4406 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4407 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004408 // Need to grab the lock to change status.
4409 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004410 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004411 return false;
4412}
4413
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004414verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004415 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004416 {
4417 // TODO: assert that the monitor on the Class is held
4418 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004419
Andreas Gampe884f3b82016-03-30 19:52:58 -07004420 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004421 ClassStatus old_status = klass->GetStatus();
4422 while (old_status == ClassStatus::kVerifying ||
4423 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004424 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004425 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4426 // case we may see the same status again. b/62912904. This is why the check is
4427 // greater or equal.
4428 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004429 << "Class '" << klass->PrettyClass()
4430 << "' performed an illegal verification state transition from " << old_status
4431 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004432 old_status = klass->GetStatus();
4433 }
jeffhao98eacac2011-09-14 16:11:53 -07004434
Andreas Gampe884f3b82016-03-30 19:52:58 -07004435 // The class might already be erroneous, for example at compile time if we attempted to verify
4436 // this class as a parent to another.
4437 if (klass->IsErroneous()) {
4438 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004439 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004440 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004441
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004442 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004443 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004444 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004445 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004446 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004447
4448 // For AOT, don't attempt to re-verify if we have already found we should
4449 // verify at runtime.
4450 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004451 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004452 }
jeffhao98eacac2011-09-14 16:11:53 -07004453
Vladimir Marko2c64a832018-01-04 11:31:56 +00004454 if (klass->GetStatus() == ClassStatus::kResolved) {
4455 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004456 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004457 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004458 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004459 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004460 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004461 }
4462
4463 // Skip verification if disabled.
4464 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004465 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004466 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004467 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004468 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004469 }
4470
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004471 VLOG(class_linker) << "Beginning verification for class: "
4472 << klass->PrettyDescriptor()
4473 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4474
Ian Rogers9ffb0392012-09-10 11:56:50 -07004475 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004476 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004477 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4478 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004479 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004480 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004481 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004482 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004483
Alex Lightf1f10492015-10-07 16:08:36 -07004484 // Verify all default super-interfaces.
4485 //
4486 // (1) Don't bother if the superclass has already had a soft verification failure.
4487 //
4488 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4489 // recursive initialization by themselves. This is because when an interface is initialized
4490 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4491 // but choose not to for an optimization. If the interfaces is being verified due to a class
4492 // initialization (which would need all the default interfaces to be verified) the class code
4493 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004494 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004495 && !klass->IsInterface()) { // See (2)
4496 int32_t iftable_count = klass->GetIfTableCount();
4497 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4498 // Loop through all interfaces this class has defined. It doesn't matter the order.
4499 for (int32_t i = 0; i < iftable_count; i++) {
4500 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004501 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004502 // We only care if we have default interfaces and can skip if we are already verified...
4503 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4504 continue;
4505 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4506 // We had a hard failure while verifying this interface. Just return immediately.
4507 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004508 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004509 } else if (UNLIKELY(!iface->IsVerified())) {
4510 // We softly failed to verify the iface. Stop checking and clean up.
4511 // Put the iface into the supertype handle so we know what caused us to fail.
4512 supertype.Assign(iface.Get());
4513 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004514 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004515 }
4516 }
4517
Alex Lightf1f10492015-10-07 16:08:36 -07004518 // At this point if verification failed, then supertype is the "first" supertype that failed
4519 // verification (without a specific order). If verification succeeded, then supertype is either
4520 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004521 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004522 supertype.Get() == klass->GetSuperClass() ||
4523 !supertype->IsVerified());
4524
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004525 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004526 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004527 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004528 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004529
4530 VLOG(class_linker) << "Class preverified status for class "
4531 << klass->PrettyDescriptor()
4532 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4533 << ": "
4534 << preverified;
4535
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004536 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4537 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004538 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4539 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004540
Ian Rogers62d6c772013-02-27 08:32:07 -08004541 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004542 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004543 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004544 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004545 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004546
4547 // Verification is done, grab the lock again.
4548 ObjectLock<mirror::Class> lock(self, klass);
4549
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004550 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4551 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004552 VLOG(class_linker) << "Soft verification failure in class "
4553 << klass->PrettyDescriptor()
4554 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4555 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004556 }
Ian Rogers1f539342012-10-03 21:09:42 -07004557 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004558 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004559 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004560 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004561 // Even though there were no verifier failures we need to respect whether the super-class and
4562 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004563 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004564 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004565 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004566 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4567 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004568 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004569 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004570 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004571 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004572 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004573 // Soft failures at compile time should be retried at runtime. Soft
4574 // failures at runtime will be handled by slow paths in the generated
4575 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004576 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004577 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004578 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004579 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004580 // As this is a fake verified status, make sure the methods are _not_ marked
4581 // kAccSkipAccessChecks later.
4582 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004583 }
4584 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004585 } else {
David Sehr709b0702016-10-13 09:12:37 -07004586 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004587 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4588 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004589 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004590 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004591 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004592 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004593 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004594 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004595 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004596 // method.
4597 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004598 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004599 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004600
4601 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4602 // Never skip access checks if the verification soft fail is forced.
4603 // Mark the class as having a verification attempt to avoid re-running the verifier.
4604 klass->SetVerificationAttempted();
4605 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004606 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004607 }
Andreas Gampe48498592014-09-10 19:48:05 -07004608 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004609 // Done verifying. Notify the compiler about the verification status, in case the class
4610 // was verified implicitly (eg super class of a compiled class).
4611 if (Runtime::Current()->IsAotCompiler()) {
4612 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4613 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4614 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004615 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004616}
4617
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004618verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4619 Handle<mirror::Class> klass,
4620 verifier::HardFailLogMode log_level,
4621 std::string* error_msg) {
4622 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004623 return verifier::ClassVerifier::VerifyClass(self,
4624 klass.Get(),
4625 runtime->GetCompilerCallbacks(),
4626 runtime->IsAotCompiler(),
4627 log_level,
4628 Runtime::Current()->GetTargetSdkVersion(),
4629 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004630}
4631
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004632bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004633 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004634 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004635 // If we're compiling, we can only verify the class using the oat file if
4636 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004637 // the compilation unit (app - dependencies). We will let the compiler callback
4638 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004639 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004640 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004641 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004642 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004643 return false;
4644 }
4645 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004646 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004647 return false;
4648 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004649 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004650
Andreas Gampeb40d3612018-06-26 15:49:42 -07004651 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004652 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004653 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004654 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4655 // For boot classpath classes in the case we're not using a default boot image:
4656 // we don't have the infrastructure yet to query verification data on individual
4657 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4658 // verified. This should be taken into account when measuring boot time and app
4659 // startup compare to the (current) production system where both:
4660 // 1) updatable boot classpath classes, and
4661 // 2) classes in /system referencing updatable classes
4662 // will be verified at runtime.
4663 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4664 oat_file_class_status = ClassStatus::kVerified;
4665 return true;
4666 }
4667 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004668 return false;
4669 }
4670
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004671 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004672 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004673 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004674 return true;
4675 }
4676 // If we only verified a subset of the classes at compile time, we can end up with classes that
4677 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004678 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004679 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004680 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004681 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004682 // Compile time verification failed with a soft error. Compile time verification can fail
4683 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004684 // class ... {
4685 // Foo x;
4686 // .... () {
4687 // if (...) {
4688 // v1 gets assigned a type of resolved class Foo
4689 // } else {
4690 // v1 gets assigned a type of unresolved class Bar
4691 // }
4692 // iput x = v1
4693 // } }
4694 // when we merge v1 following the if-the-else it results in Conflict
4695 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4696 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4697 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4698 // at compile time).
4699 return false;
4700 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004701 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004702 // Compile time verification failed with a hard error. This is caused by invalid instructions
4703 // in the class. These errors are unrecoverable.
4704 return false;
4705 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004706 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004707 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4708 // not loading the class.
4709 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4710 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004711 return false;
4712 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004713 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004714 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004715 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004716 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004717 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004718}
4719
Alex Light5a559862016-01-29 12:24:48 -08004720void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004721 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004722 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004723 }
4724}
4725
Alex Light5a559862016-01-29 12:24:48 -08004726void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004727 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004728 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004729 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004730 return; // native or abstract method
4731 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004732 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004733 return; // nothing to process
4734 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004735 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004736 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004737 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4738 CatchHandlerIterator iterator(handlers_ptr);
4739 for (; iterator.HasNext(); iterator.Next()) {
4740 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4741 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004742 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004743 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004744 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004745 DCHECK(Thread::Current()->IsExceptionPending());
4746 Thread::Current()->ClearException();
4747 }
4748 }
4749 }
4750 handlers_ptr = iterator.EndDataPointer();
4751 }
4752}
4753
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004754ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4755 jstring name,
4756 jobjectArray interfaces,
4757 jobject loader,
4758 jobjectArray methods,
4759 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004760 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004761
4762 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4763 // code to be executed. We put it up here so we can avoid all the allocations associated with
4764 // creating the class. This can happen with (eg) jit-threads.
4765 if (!self->CanLoadClasses()) {
4766 // Make sure we don't try to load anything, potentially causing an infinite loop.
4767 ObjPtr<mirror::Throwable> pre_allocated =
4768 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4769 self->SetException(pre_allocated);
4770 return nullptr;
4771 }
4772
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004773 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004774 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004775 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004776 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004777 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004778 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004779 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004780 DCHECK(temp_klass->GetClass() != nullptr);
4781 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004782 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4783 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004784 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4785 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4786 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4787 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004788 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004789 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004790 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004791 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004792 std::string storage;
4793 const char* descriptor = temp_klass->GetDescriptor(&storage);
4794 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004795
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004796 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004797 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004798
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004799 // Insert the class before loading the fields as the field roots
4800 // (ArtField::declaring_class_) are only visited from the class
4801 // table. There can't be any suspend points between inserting the
4802 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004803 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004804 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004805
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004806 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004807 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004808 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004809 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004810
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004811 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4812 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004813 ArtField& interfaces_sfield = sfields->At(0);
4814 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004815 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004816 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004817
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004818 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004819 ArtField& throws_sfield = sfields->At(1);
4820 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004821 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004822 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004823
Ian Rogers466bb252011-10-14 03:29:56 -07004824 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004825 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004826
Alex Lighte64300b2015-12-15 15:02:47 -08004827 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004828 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004829 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004830 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004831 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004832
4833 // Create the methods array.
4834 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4835 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004836 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4837 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004838 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004839 self->AssertPendingOOMException();
4840 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004841 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004842 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004843
4844 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004845 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004846
4847 // Create virtual method using specified prototypes.
4848 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004849 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004850 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004851 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004852 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004853 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4854 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004855 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004856
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004857 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004858 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004859 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004860 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004861 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004862
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004863 // At this point the class is loaded. Publish a ClassLoad event.
4864 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4865 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4866
4867 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004868 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004869 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004870 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004871 // Link the fields and virtual methods, creating vtable and iftables.
4872 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004873 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004874 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004875 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004876 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004877 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004878 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004879 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004880 CHECK(temp_klass->IsRetired());
4881 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004882
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004883 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004884 interfaces_sfield.SetObject<false>(
4885 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004886 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004887 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4888 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004889 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004890 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004891
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004892 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4893
Vladimir Marko305c38b2018-02-14 11:50:07 +00004894 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4895 // See also ClassLinker::EnsureInitialized().
4896 if (kBitstringSubtypeCheckEnabled) {
4897 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4898 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4899 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4900 }
4901
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004902 {
4903 // Lock on klass is released. Lock new class object.
4904 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004905 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004906 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004907 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004908
4909 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004910 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004911 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004912 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4913
Ian Rogersc2b44472011-12-14 21:17:17 -08004914 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004915 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4916 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004917 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004918 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004919
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004920 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004921 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004922 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004923 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004924 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004925
4926 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004927 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004928 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004929
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004930 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004931 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004932 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004933 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004934 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004935 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004936}
4937
Mathieu Chartiere401d142015-04-22 13:56:20 -07004938void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4939 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004940 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4941 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004942
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004943 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4944 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004945 ArtMethod* proxy_constructor =
4946 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004947 DCHECK(proxy_constructor != nullptr)
4948 << "Could not find <init> method in java.lang.reflect.Proxy";
4949
Jeff Haodb8a6642014-08-14 17:18:52 -07004950 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4951 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004952 DCHECK(out != nullptr);
4953 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004954 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004955 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004956 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004957 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4958 kAccPublic |
4959 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004960 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004961
4962 // Set the original constructor method.
4963 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004964}
4965
Mathieu Chartiere401d142015-04-22 13:56:20 -07004966void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004967 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004968 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4969 CHECK_STREQ(np->GetName(), "<init>");
4970 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004971 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004972}
4973
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004974void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004975 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004976 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004977 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004978 DCHECK(out != nullptr);
4979 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004980
Alex Lighte9dd04f2016-03-16 16:09:45 -07004981 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004982 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004983 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4984 // preference to the invocation handler.
4985 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4986 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004987 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4988 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004989 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4990
4991 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4992 // method they copy might (if it's a default method).
4993 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004994
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004995 // Set the original interface method.
4996 out->SetDataPtrSize(prototype, image_pointer_size_);
4997
Ian Rogers466bb252011-10-14 03:29:56 -07004998 // At runtime the method looks like a reference and argument saving method, clone the code
4999 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005000 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005001}
Jesse Wilson95caa792011-10-12 18:14:17 -04005002
Mathieu Chartiere401d142015-04-22 13:56:20 -07005003void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005004 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005005 CHECK(!prototype->IsFinal());
5006 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005007 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005008
5009 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5010 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005011 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005012 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005013}
5014
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005015bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005016 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005017 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005018 return true;
5019 }
5020 if (!can_init_statics) {
5021 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005022 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005023 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005024 return false;
5025 }
5026 // Check if there are encoded static values needing initialization.
5027 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005028 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005029 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005030 if (dex_class_def->static_values_off_ != 0) {
5031 return false;
5032 }
5033 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005034 // If we are a class we need to initialize all interfaces with default methods when we are
5035 // initialized. Check all of them.
5036 if (!klass->IsInterface()) {
5037 size_t num_interfaces = klass->GetIfTableCount();
5038 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005039 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005040 if (iface->HasDefaultMethods() &&
5041 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5042 return false;
5043 }
5044 }
5045 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005046 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005047 if (klass->IsInterface() || !klass->HasSuperClass()) {
5048 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005049 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005050 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005051 if (!can_init_parents && !super_class->IsInitialized()) {
5052 return false;
5053 }
5054 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005055}
5056
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005057bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5058 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005059 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5060
5061 // Are we already initialized and therefore done?
5062 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5063 // an initialized class will never change its state.
5064 if (klass->IsInitialized()) {
5065 return true;
5066 }
5067
5068 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005069 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005070 return false;
5071 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005072
Ian Rogers7b078e82014-09-10 14:44:24 -07005073 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005074 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005075 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005076 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005077
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005078 // Re-check under the lock in case another thread initialized ahead of us.
5079 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005080 return true;
5081 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005082
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005083 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005084 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005085 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005086 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005087 return false;
5088 }
5089
Vladimir Marko72ab6842017-01-20 19:32:50 +00005090 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5091 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005092
5093 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005094 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005095 if (!klass->IsVerified()) {
5096 // We failed to verify, expect either the klass to be erroneous or verification failed at
5097 // compile time.
5098 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005099 // The class is erroneous. This may be a verifier error, or another thread attempted
5100 // verification and/or initialization and failed. We can distinguish those cases by
5101 // whether an exception is already pending.
5102 if (self->IsExceptionPending()) {
5103 // Check that it's a VerifyError.
5104 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005105 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005106 } else {
5107 // Check that another thread attempted initialization.
5108 DCHECK_NE(0, klass->GetClinitThreadId());
5109 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5110 // Need to rethrow the previous failure now.
5111 ThrowEarlierClassFailure(klass.Get(), true);
5112 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005113 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005114 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005115 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005116 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005117 self->AssertNoPendingException();
5118 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005119 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005120 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005121 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005122 } else {
5123 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005124 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005125
5126 // A separate thread could have moved us all the way to initialized. A "simple" example
5127 // involves a subclass of the current class being initialized at the same time (which
5128 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005129 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005130 if (klass->IsInitialized()) {
5131 return true;
5132 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005133 }
5134
Vladimir Marko2c64a832018-01-04 11:31:56 +00005135 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005136 // initializing higher up the stack or another thread has beat us
5137 // to initializing and we need to wait. Either way, this
5138 // invocation of InitializeClass will not be responsible for
5139 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005140 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005141 // Could have got an exception during verification.
5142 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005143 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005144 return false;
5145 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005146 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005147 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005148 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005149 return true;
5150 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005151 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005152 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005153 }
5154
Jeff Haoe2e40342017-07-19 10:45:18 -07005155 // Try to get the oat class's status for this class if the oat file is present. The compiler
5156 // tries to validate superclass descriptors, and writes the result into the oat file.
5157 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5158 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5159 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005160 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005161 const Runtime* runtime = Runtime::Current();
5162 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5163 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5164 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005165 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005166 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005167 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005168 return false;
5169 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005170 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005171
Vladimir Marko2c64a832018-01-04 11:31:56 +00005172 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005173 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005174
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005175 // From here out other threads may observe that we're initializing and so changes of state
5176 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005177 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005178 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005179
5180 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005181 }
5182
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005183 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005184 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005185 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005186 if (!super_class->IsInitialized()) {
5187 CHECK(!super_class->IsInterface());
5188 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005189 StackHandleScope<1> hs(self);
5190 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005191 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005192 if (!super_initialized) {
5193 // The super class was verified ahead of entering initializing, we should only be here if
5194 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005195 // For the case of aot compiler, the super class might also be initializing but we don't
5196 // want to process circular dependencies in pre-compile.
5197 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005198 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005199 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005200 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005201 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005202 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005203 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005204 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005205 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005206 return false;
5207 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005208 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005209 }
5210
Alex Lighteb7c1442015-08-31 13:17:42 -07005211 if (!klass->IsInterface()) {
5212 // Initialize interfaces with default methods for the JLS.
5213 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005214 // Only setup the (expensive) handle scope if we actually need to.
5215 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005216 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005217 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5218 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005219 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005220 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005221 CHECK(handle_scope_iface->IsInterface());
5222 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5223 // We have already done this for this interface. Skip it.
5224 continue;
5225 }
5226 // We cannot just call initialize class directly because we need to ensure that ALL
5227 // interfaces with default methods are initialized. Non-default interface initialization
5228 // will not affect other non-default super-interfaces.
5229 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5230 handle_scope_iface,
5231 can_init_statics,
5232 can_init_parents);
5233 if (!iface_initialized) {
5234 ObjectLock<mirror::Class> lock(self, klass);
5235 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005236 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005237 return false;
5238 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005239 }
5240 }
5241 }
5242
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005243 const size_t num_static_fields = klass->NumStaticFields();
5244 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005245 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005246 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005247 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005248 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005249 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005250
5251 // Eagerly fill in static fields so that the we don't have to do as many expensive
5252 // Class::FindStaticField in ResolveField.
5253 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005254 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005255 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005256 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005257 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005258 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005259 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5260 field,
5261 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5262 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005263 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005264 } else {
5265 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005266 }
5267 }
5268
Vladimir Markoe11dd502017-12-08 14:09:45 +00005269 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5270 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005271 this,
5272 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005273 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005274
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005275 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005276 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005277 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005278 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5279 if (!value_it.HasNext()) {
5280 break;
5281 }
5282 ArtField* art_field = ResolveField(field.GetIndex(),
5283 dex_cache,
5284 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005285 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005286 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005287 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005288 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005289 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005290 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005291 if (self->IsExceptionPending()) {
5292 break;
5293 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005294 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005295 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005296 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005297 }
5298 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005299
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005300
Mathieu Chartierda595be2016-08-10 13:57:39 -07005301 if (!self->IsExceptionPending()) {
5302 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5303 if (clinit != nullptr) {
5304 CHECK(can_init_statics);
5305 JValue result;
5306 clinit->Invoke(self, nullptr, 0, &result, "V");
5307 }
5308 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005309 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005310 uint64_t t1 = NanoTime();
5311
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005312 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005313 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005314 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005315
5316 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005317 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005318 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005319 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005320 } else if (Runtime::Current()->IsTransactionAborted()) {
5321 // The exception thrown when the transaction aborted has been caught and cleared
5322 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005323 VLOG(compiler) << "Return from class initializer of "
5324 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005325 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005326 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005327 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005328 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005329 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005330 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5331 RuntimeStats* thread_stats = self->GetStats();
5332 ++global_stats->class_init_count;
5333 ++thread_stats->class_init_count;
5334 global_stats->class_init_time_ns += (t1 - t0);
5335 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005336 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005337 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005338 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005339 std::string temp;
5340 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005341 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005342 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005343 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005344 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005345 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005346 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005347 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005348}
5349
Alex Lighteb7c1442015-08-31 13:17:42 -07005350// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5351// and perform the initialization only on those interfaces that contain default methods.
5352bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5353 Handle<mirror::Class> iface,
5354 bool can_init_statics,
5355 bool can_init_parents) {
5356 CHECK(iface->IsInterface());
5357 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005358 // Only create the (expensive) handle scope if we need it.
5359 if (UNLIKELY(num_direct_ifaces > 0)) {
5360 StackHandleScope<1> hs(self);
5361 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5362 // First we initialize all of iface's super-interfaces recursively.
5363 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005364 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005365 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005366 if (!super_iface->HasBeenRecursivelyInitialized()) {
5367 // Recursive step
5368 handle_super_iface.Assign(super_iface);
5369 if (!InitializeDefaultInterfaceRecursive(self,
5370 handle_super_iface,
5371 can_init_statics,
5372 can_init_parents)) {
5373 return false;
5374 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005375 }
5376 }
5377 }
5378
5379 bool result = true;
5380 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5381 // initialize if we don't have default methods.
5382 if (iface->HasDefaultMethods()) {
5383 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5384 }
5385
5386 // Mark that this interface has undergone recursive default interface initialization so we know we
5387 // can skip it on any later class initializations. We do this even if we are not a default
5388 // interface since we can still avoid the traversal. This is purely a performance optimization.
5389 if (result) {
5390 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005391 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5392 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5393 // initialization is a performance optimization (to avoid another idempotent visit
5394 // for other implementing classes/interfaces), and can be revisited later.
5395 ObjectTryLock<mirror::Class> lock(self, iface);
5396 if (lock.Acquired()) {
5397 iface->SetRecursivelyInitialized();
5398 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005399 }
5400 return result;
5401}
5402
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005403bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5404 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005405 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005406 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005407 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005408 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005409 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005410 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005411
5412 // When we wake up, repeat the test for init-in-progress. If
5413 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005414 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005415 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005416 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005417 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005418 return false;
5419 }
5420 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005421 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005422 continue;
5423 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005424 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005425 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005426 // Compile time initialization failed.
5427 return false;
5428 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005429 if (klass->IsErroneous()) {
5430 // The caller wants an exception, but it was thrown in a
5431 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005432 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005433 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005434 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005435 return false;
5436 }
5437 if (klass->IsInitialized()) {
5438 return true;
5439 }
David Sehr709b0702016-10-13 09:12:37 -07005440 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005441 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005442 }
Ian Rogers07140832014-09-30 15:43:59 -07005443 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005444}
5445
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005446static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5447 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005448 ArtMethod* method,
5449 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005450 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005451 DCHECK(Thread::Current()->IsExceptionPending());
5452 DCHECK(!m->IsProxyMethod());
5453 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005454 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5455 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005456 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005457 std::string return_type = dex_file->PrettyType(return_type_idx);
5458 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005459 ThrowWrappedLinkageError(klass.Get(),
5460 "While checking class %s method %s signature against %s %s: "
5461 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005462 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5463 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005464 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005465 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005466 return_type.c_str(), class_loader.c_str());
5467}
5468
5469static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5470 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005471 ArtMethod* method,
5472 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005473 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005474 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005475 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005476 DCHECK(Thread::Current()->IsExceptionPending());
5477 DCHECK(!m->IsProxyMethod());
5478 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005479 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5480 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005481 ThrowWrappedLinkageError(klass.Get(),
5482 "While checking class %s method %s signature against %s %s: "
5483 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005484 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5485 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005486 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005487 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005488 index, arg_type.c_str(), class_loader.c_str());
5489}
5490
5491static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5492 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005493 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005494 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005495 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005496 ThrowLinkageError(klass.Get(),
5497 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005498 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5499 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005500 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005501 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005502 error_msg.c_str());
5503}
5504
Ian Rogersb5fb2072014-12-02 17:22:02 -08005505static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005506 Handle<mirror::Class> klass,
5507 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005508 ArtMethod* method1,
5509 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005510 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005511 {
5512 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005513 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005514 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005515 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005516 return false;
5517 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005518 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005519 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005520 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005521 return false;
5522 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005523 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005524 ThrowSignatureMismatch(klass, super_klass, method1,
5525 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005526 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005527 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005528 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005529 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005530 return false;
5531 }
5532 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005533 const dex::TypeList* types1 = method1->GetParameterTypeList();
5534 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005535 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005536 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005537 ThrowSignatureMismatch(klass, super_klass, method1,
5538 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005539 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005540 return false;
5541 }
5542 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005543 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005544 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005545 ThrowSignatureMismatch(klass, super_klass, method1,
5546 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005547 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005548 return false;
5549 }
5550 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005551 }
5552 uint32_t num_types = types1->Size();
5553 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005554 ThrowSignatureMismatch(klass, super_klass, method1,
5555 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005556 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005557 return false;
5558 }
5559 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005560 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005561 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005562 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005563 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005564 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005565 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005566 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005567 return false;
5568 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005569 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005570 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005571 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005572 if (UNLIKELY(other_param_type == nullptr)) {
5573 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005574 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005575 return false;
5576 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005577 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005578 ThrowSignatureMismatch(klass, super_klass, method1,
5579 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5580 i,
David Sehr709b0702016-10-13 09:12:37 -07005581 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005582 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005583 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005584 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005585 return false;
5586 }
5587 }
5588 return true;
5589}
5590
5591
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005592bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005593 if (klass->IsInterface()) {
5594 return true;
5595 }
Ian Rogers151f2212014-05-06 11:27:27 -07005596 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005597 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005598 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005599 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005600 if (klass->HasSuperClass() &&
5601 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005602 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005603 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005604 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5605 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5606 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005607 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5608 klass,
5609 super_klass,
5610 m,
5611 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005612 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005613 return false;
5614 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005615 }
5616 }
5617 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005618 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005619 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5620 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5621 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005622 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005623 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5624 j, image_pointer_size_);
5625 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5626 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005627 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5628 klass,
5629 super_klass,
5630 m,
5631 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005632 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005633 return false;
5634 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005635 }
5636 }
5637 }
5638 }
5639 return true;
5640}
5641
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005642bool ClassLinker::EnsureInitialized(Thread* self,
5643 Handle<mirror::Class> c,
5644 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005645 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005646 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005647
Mathieu Chartier524507a2014-08-27 15:28:28 -07005648 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005649 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005650 return true;
5651 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005652 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5653 //
5654 // Ensure the bitstring is initialized before any of the class initialization
5655 // logic occurs. Once a class initializer starts running, objects can
5656 // escape into the heap and use the subtype checking code.
5657 //
5658 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5659 // can be used as a source for the IsSubClass check, and that all ancestors
5660 // of the class are Assigned (can be used as a target for IsSubClass check)
5661 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005662 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005663 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005664 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005665 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5666 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005667 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005668 if (!success) {
5669 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005670 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005671 }
5672 } else {
5673 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005674 }
5675 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005676}
5677
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005678void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5679 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005680 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005681 for (ArtField& field : new_class->GetIFields()) {
5682 if (field.GetDeclaringClass() == temp_class) {
5683 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005684 }
5685 }
5686
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005687 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005688 for (ArtField& field : new_class->GetSFields()) {
5689 if (field.GetDeclaringClass() == temp_class) {
5690 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005691 }
5692 }
5693
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005694 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005695 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005696 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005697 if (method.GetDeclaringClass() == temp_class) {
5698 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005699 }
5700 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005701
5702 // Make sure the remembered set and mod-union tables know that we updated some of the native
5703 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005704 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005705}
5706
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005707void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005708 CHECK(class_loader->GetAllocator() == nullptr);
5709 CHECK(class_loader->GetClassTable() == nullptr);
5710 Thread* const self = Thread::Current();
5711 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005712 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005713 // Create and set the class table.
5714 data.class_table = new ClassTable;
5715 class_loader->SetClassTable(data.class_table);
5716 // Create and set the linear allocator.
5717 data.allocator = Runtime::Current()->CreateLinearAlloc();
5718 class_loader->SetAllocator(data.allocator);
5719 // Add to the list so that we know to free the data later.
5720 class_loaders_.push_back(data);
5721}
5722
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005723ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005724 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005725 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005726 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005727 ClassTable* class_table = class_loader->GetClassTable();
5728 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005729 RegisterClassLoader(class_loader);
5730 class_table = class_loader->GetClassTable();
5731 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005732 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005733 return class_table;
5734}
5735
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005736ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005737 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005738}
5739
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005740static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005741 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005742 while (klass->HasSuperClass()) {
5743 klass = klass->GetSuperClass();
5744 if (klass->ShouldHaveImt()) {
5745 return klass->GetImt(pointer_size);
5746 }
5747 }
5748 return nullptr;
5749}
5750
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005751bool ClassLinker::LinkClass(Thread* self,
5752 const char* descriptor,
5753 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005754 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005755 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005756 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005757
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005758 if (!LinkSuperClass(klass)) {
5759 return false;
5760 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005761 ArtMethod* imt_data[ImTable::kSize];
5762 // If there are any new conflicts compared to super class.
5763 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005764 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005765 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005766 return false;
5767 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005768 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005769 return false;
5770 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005771 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005772 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005773 return false;
5774 }
5775 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005776 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005777
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005778 ImTable* imt = nullptr;
5779 if (klass->ShouldHaveImt()) {
5780 // If there are any new conflicts compared to the super class we can not make a copy. There
5781 // can be cases where both will have a conflict method at the same slot without having the same
5782 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5783 // will possibly create a table that is incorrect for either of the classes.
5784 // Same IMT with new_conflict does not happen very often.
5785 if (!new_conflict) {
5786 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5787 if (super_imt != nullptr) {
5788 bool imt_equals = true;
5789 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5790 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5791 }
5792 if (imt_equals) {
5793 imt = super_imt;
5794 }
5795 }
5796 }
5797 if (imt == nullptr) {
5798 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5799 imt = reinterpret_cast<ImTable*>(
5800 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5801 if (imt == nullptr) {
5802 return false;
5803 }
5804 imt->Populate(imt_data, image_pointer_size_);
5805 }
5806 }
5807
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005808 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5809 // We don't need to retire this class as it has no embedded tables or it was created the
5810 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005811 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005812
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005813 if (klass->ShouldHaveEmbeddedVTable()) {
5814 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005815 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005816 if (klass->ShouldHaveImt()) {
5817 klass->SetImt(imt, image_pointer_size_);
5818 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005819
5820 // Update CHA info based on whether we override methods.
5821 // Have to do this before setting the class as resolved which allows
5822 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005823 if (cha_ != nullptr) {
5824 cha_->UpdateAfterLoadingOf(klass);
5825 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005826
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005827 // This will notify waiters on klass that saw the not yet resolved
5828 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005829 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005830 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005831 } else {
5832 CHECK(!klass->IsResolved());
5833 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005834 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005835 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005836 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5837 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5838 // may not see any references to the target space and clean the card for a class if another
5839 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005840 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005841 klass->SetSFieldsPtrUnchecked(nullptr);
5842 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005843 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005844 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005845 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005846 return false;
5847 }
5848
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005849 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5850 ObjectLock<mirror::Class> lock(self, h_new_class);
5851 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005852
5853 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005854 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005855 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005856 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005857 const ObjPtr<mirror::Class> existing =
5858 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005859 if (class_loader != nullptr) {
5860 // We updated the class in the class table, perform the write barrier so that the GC knows
5861 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005862 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005863 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005864 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005865 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005866 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5867 }
5868 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005869
Mingyao Yang063fc772016-08-02 11:02:54 -07005870 // Update CHA info based on whether we override methods.
5871 // Have to do this before setting the class as resolved which allows
5872 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005873 if (cha_ != nullptr) {
5874 cha_->UpdateAfterLoadingOf(h_new_class);
5875 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005876
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005877 // This will notify waiters on temp class that saw the not yet resolved class in the
5878 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005879 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005880
Vladimir Marko2c64a832018-01-04 11:31:56 +00005881 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005882 // This will notify waiters on new_class that saw the not yet resolved
5883 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005884 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005885 // Return the new class.
5886 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005887 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005888 return true;
5889}
5890
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005891bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005892 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005893 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005894 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5895 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005896 // Check that a class does not inherit from itself directly.
5897 //
5898 // TODO: This is a cheap check to detect the straightforward case
5899 // of a class extending itself (b/28685551), but we should do a
5900 // proper cycle detection on loaded classes, to detect all cases
5901 // of class circularity errors (b/28830038).
5902 if (super_class_idx == class_def.class_idx_) {
5903 ThrowClassCircularityError(klass.Get(),
5904 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005905 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005906 return false;
5907 }
5908
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005909 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005910 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005911 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005912 return false;
5913 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005914 // Verify
5915 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005916 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005917 super_class->PrettyDescriptor().c_str(),
5918 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005919 return false;
5920 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005921 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005922 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005923 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005924 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005925 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005926 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005927 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005928 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005929 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005930 DCHECK(Thread::Current()->IsExceptionPending());
5931 return false;
5932 }
5933 // Verify
5934 if (!klass->CanAccess(interface)) {
5935 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005936 ThrowIllegalAccessError(klass.Get(),
5937 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005938 interface->PrettyDescriptor().c_str(),
5939 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005940 return false;
5941 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005942 }
5943 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005944 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005945 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005946 return true;
5947}
5948
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005949bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005950 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005951 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005952 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5953 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005954 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005955 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005956 return false;
5957 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005958 return true;
5959 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005960 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005961 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005962 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005963 return false;
5964 }
5965 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005966 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005967 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5968 return false;
5969 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005970 if (super->IsFinal()) {
5971 ThrowVerifyError(klass.Get(),
5972 "Superclass %s of %s is declared final",
5973 super->PrettyDescriptor().c_str(),
5974 klass->PrettyDescriptor().c_str());
5975 return false;
5976 }
5977 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005978 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005979 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005980 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005981 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005982 return false;
5983 }
5984 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005985 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005986 super->PrettyDescriptor().c_str(),
5987 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005988 return false;
5989 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005990
Brian Carlstromf3632832014-05-20 15:36:53 -07005991 // Inherit kAccClassIsFinalizable from the superclass in case this
5992 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005993 if (super->IsFinalizable()) {
5994 klass->SetFinalizable();
5995 }
5996
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005997 // Inherit class loader flag form super class.
5998 if (super->IsClassLoaderClass()) {
5999 klass->SetClassLoaderClass();
6000 }
6001
Elliott Hughes2da50362011-10-10 16:57:08 -07006002 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006003 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006004 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006005 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006006 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006007 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006008 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006009 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006010 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006011 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006012 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006013 return false;
6014 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006015
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006016 if (kIsDebugBuild) {
6017 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006018 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006019 CHECK(super->IsResolved());
6020 super = super->GetSuperClass();
6021 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006022 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006023 return true;
6024}
6025
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006026// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006027bool ClassLinker::LinkMethods(Thread* self,
6028 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006029 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006030 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006031 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006032 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006033 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6034 // need to have default methods be in the virtuals array of each class but we don't set that up
6035 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006036 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006037 // Link virtual methods then interface methods.
6038 // We set up the interface lookup table first because we need it to determine if we need to update
6039 // any vtable entries with new default method implementations.
6040 return SetupInterfaceLookupTable(self, klass, interfaces)
6041 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006042 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006043}
6044
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006045// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6046// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6047// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006048class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006049 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006050 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006051 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006052 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6053 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006054 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006055 }
6056
6057 const char* GetName() {
6058 if (name_ == nullptr) {
6059 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6060 }
6061 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006062 }
6063
Mathieu Chartiere401d142015-04-22 13:56:20 -07006064 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006065 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006066 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006067 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006068 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006069 if (dex_file_ == other_dex_file) {
6070 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6071 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006072 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006073 uint32_t other_name_len;
6074 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6075 &other_name_len);
6076 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6077 return false;
6078 }
6079 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6080 }
6081
6082 private:
6083 // Dex file for the method to compare against.
6084 const DexFile* const dex_file_;
6085 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006086 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006087 // Lazily computed name from the dex file's strings.
6088 const char* name_;
6089 // Lazily computed name length.
6090 uint32_t name_len_;
6091};
6092
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006093class LinkVirtualHashTable {
6094 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006095 LinkVirtualHashTable(Handle<mirror::Class> klass,
6096 size_t hash_size,
6097 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006098 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006099 : klass_(klass),
6100 hash_size_(hash_size),
6101 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006102 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006103 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6104 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006105
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006106 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006107 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6108 virtual_method_index, image_pointer_size_);
6109 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006110 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006111 uint32_t index = hash % hash_size_;
6112 // Linear probe until we have an empty slot.
6113 while (hash_table_[index] != invalid_index_) {
6114 if (++index == hash_size_) {
6115 index = 0;
6116 }
6117 }
6118 hash_table_[index] = virtual_method_index;
6119 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006120
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006121 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006122 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006123 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006124 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006125 size_t index = hash % hash_size_;
6126 while (true) {
6127 const uint32_t value = hash_table_[index];
6128 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6129 // the block and can safely assume not found.
6130 if (value == invalid_index_) {
6131 break;
6132 }
6133 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006134 ArtMethod* virtual_method =
6135 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6136 if (comparator->HasSameNameAndSignature(
6137 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006138 hash_table_[index] = removed_index_;
6139 return value;
6140 }
6141 }
6142 if (++index == hash_size_) {
6143 index = 0;
6144 }
6145 }
6146 return GetNotFoundIndex();
6147 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006148
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006149 static uint32_t GetNotFoundIndex() {
6150 return invalid_index_;
6151 }
6152
6153 private:
6154 static const uint32_t invalid_index_;
6155 static const uint32_t removed_index_;
6156
6157 Handle<mirror::Class> klass_;
6158 const size_t hash_size_;
6159 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006160 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006161};
6162
6163const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6164const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6165
Stephen Hines1ddd9132017-02-08 01:51:18 -08006166bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006167 Thread* self,
6168 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006169 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006170 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006171 if (klass->IsInterface()) {
6172 // No vtable.
6173 if (!IsUint<16>(num_virtual_methods)) {
6174 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6175 return false;
6176 }
6177 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006178 // Assign each method an IMT index and set the default flag.
6179 for (size_t i = 0; i < num_virtual_methods; ++i) {
6180 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6181 m->SetMethodIndex(i);
6182 if (!m->IsAbstract()) {
6183 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6184 has_defaults = true;
6185 }
6186 }
6187 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6188 // during initialization. This is a performance optimization. We could simply traverse the
6189 // virtual_methods_ array again during initialization.
6190 if (has_defaults) {
6191 klass->SetHasDefaultMethods();
6192 }
6193 return true;
6194 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006195 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6196 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006197 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006198 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006199 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006200 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006201 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006202 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006203 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006204 return false;
6205 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006206 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006207 vtable->SetElementPtrSize(
6208 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006209 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006210 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6211 // might give us new default methods). If no new interfaces then we can skip the rest since
6212 // the class cannot override any of the super-class's methods. This is required for
6213 // correctness since without it we might not update overridden default method vtable entries
6214 // correctly.
6215 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006216 klass->SetVTable(vtable.Get());
6217 return true;
6218 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006219 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006220 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Markoc524e9e2019-03-26 10:54:50 +00006221 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006222 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006223 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6224 // might give us new default methods). See comment above.
6225 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006226 klass->SetVTable(super_vtable);
6227 return true;
6228 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006229 vtable = hs.NewHandle(
6230 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006231 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006232 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006233 return false;
6234 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006235 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006236 // How the algorithm works:
6237 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6238 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6239 // method which has not been matched to a vtable method, and j if the virtual method at the
6240 // index overrode the super virtual method at index j.
6241 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6242 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6243 // the need for the initial vtable which we later shrink back down).
6244 // 3. Add non overridden methods to the end of the vtable.
6245 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006246 // + 1 so that even if we only have new default methods we will still be able to use this hash
6247 // table (i.e. it will never have 0 size).
6248 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006249 uint32_t* hash_table_ptr;
6250 std::unique_ptr<uint32_t[]> hash_heap_storage;
6251 if (hash_table_size <= kMaxStackHash) {
6252 hash_table_ptr = reinterpret_cast<uint32_t*>(
6253 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6254 } else {
6255 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6256 hash_table_ptr = hash_heap_storage.get();
6257 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006258 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006259 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006260 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006261 DCHECK(klass->GetVirtualMethodDuringLinking(
6262 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006263 hash_table.Add(i);
6264 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006265 // 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 -07006266 // the hash table.
6267 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006268 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006269 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006270 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6271 super_method->GetAccessFlags())) {
6272 // Continue on to the next method since this one is package private and canot be overridden.
6273 // Before Android 4.1, the package-private method super_method might have been incorrectly
6274 // overridden.
6275 continue;
6276 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006277 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006278 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006279 // We remove the method so that subsequent lookups will be faster by making the hash-map
6280 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006281 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6282 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006283 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6284 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006285 if (super_method->IsFinal()) {
6286 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6287 virtual_method->PrettyMethod().c_str(),
6288 super_method->GetDeclaringClassDescriptor());
6289 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006290 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006291 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6292 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006293 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006294 // We didn't directly override this method but we might through default methods...
6295 // Check for default method update.
6296 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006297 switch (FindDefaultMethodImplementation(self,
6298 super_method,
6299 klass,
6300 /*out*/&default_method)) {
6301 case DefaultMethodSearchResult::kDefaultConflict: {
6302 // A conflict was found looking for default methods. Note this (assuming it wasn't
6303 // pre-existing) in the translations map.
6304 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6305 // Don't generate another conflict method to reduce memory use as an optimization.
6306 default_translations->insert(
6307 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6308 }
6309 break;
6310 }
6311 case DefaultMethodSearchResult::kAbstractFound: {
6312 // No conflict but method is abstract.
6313 // We note that this vtable entry must be made abstract.
6314 if (UNLIKELY(!super_method->IsAbstract())) {
6315 default_translations->insert(
6316 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6317 }
6318 break;
6319 }
6320 case DefaultMethodSearchResult::kDefaultFound: {
6321 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6322 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6323 // Found a default method implementation that is new.
6324 // TODO Refactor this add default methods to virtuals here and not in
6325 // LinkInterfaceMethods maybe.
6326 // The problem is default methods might override previously present
6327 // default-method or miranda-method vtable entries from the superclass.
6328 // Unfortunately we need these to be entries in this class's virtuals. We do not
6329 // give these entries there until LinkInterfaceMethods so we pass this map around
6330 // to let it know which vtable entries need to be updated.
6331 // Make a note that vtable entry j must be updated, store what it needs to be updated
6332 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6333 // then.
6334 default_translations->insert(
6335 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006336 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6337 << " overridden by default "
6338 << default_method->PrettyMethod()
6339 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006340 }
6341 break;
6342 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006343 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006344 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006345 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006346 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006347 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006348 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006349 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006350 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6351 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006352 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006353 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006354 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006355 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006356 local_method->SetMethodIndex(actual_count);
6357 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006358 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006359 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006360 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006361 return false;
6362 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006363 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006364 CHECK_LE(actual_count, max_count);
6365 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006366 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006367 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006368 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006369 return false;
6370 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006371 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006372 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006373 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006374 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006375 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006376 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6377 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006378 return false;
6379 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006380 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006381 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006382 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006383 return false;
6384 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006385 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006386 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6387 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006388 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006389 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006390 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006391 }
6392 return true;
6393}
6394
Alex Light9139e002015-10-09 15:59:48 -07006395// Determine if the given iface has any subinterface in the given list that declares the method
6396// specified by 'target'.
6397//
6398// Arguments
6399// - self: The thread we are running on
6400// - target: A comparator that will match any method that overrides the method we are checking for
6401// - iftable: The iftable we are searching for an overriding method on.
6402// - ifstart: The index of the interface we are checking to see if anything overrides
6403// - iface: The interface we are checking to see if anything overrides.
6404// - image_pointer_size:
6405// The image pointer size.
6406//
6407// Returns
6408// - True: There is some method that matches the target comparator defined in an interface that
6409// is a subtype of iface.
6410// - False: There is no method that matches the target comparator in any interface that is a subtype
6411// of iface.
6412static bool ContainsOverridingMethodOf(Thread* self,
6413 MethodNameAndSignatureComparator& target,
6414 Handle<mirror::IfTable> iftable,
6415 size_t ifstart,
6416 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006417 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006418 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006419 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006420 DCHECK(iface != nullptr);
6421 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006422 DCHECK_GE(ifstart, 0u);
6423 DCHECK_LT(ifstart, iftable->Count());
6424 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6425 DCHECK(iface->IsInterface());
6426
6427 size_t iftable_count = iftable->Count();
6428 StackHandleScope<1> hs(self);
6429 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6430 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6431 // Skip ifstart since our current interface obviously cannot override itself.
6432 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006433 // Iterate through every method on this interface. The order does not matter.
6434 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006435 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006436 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006437 // Check if the i'th interface is a subtype of this one.
6438 if (iface->IsAssignableFrom(current_iface.Get())) {
6439 return true;
6440 }
6441 break;
6442 }
6443 }
6444 }
6445 return false;
6446}
6447
Alex Lighteb7c1442015-08-31 13:17:42 -07006448// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006449// out_default_method and returns kDefaultFound on success. If no default method was found return
6450// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6451// default_method conflict) it will return kDefaultConflict.
6452ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6453 Thread* self,
6454 ArtMethod* target_method,
6455 Handle<mirror::Class> klass,
6456 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006457 DCHECK(self != nullptr);
6458 DCHECK(target_method != nullptr);
6459 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006460
6461 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006462
6463 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6464 // table. This lets us walk the table backwards when searching for default methods. The first one
6465 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6466 // track of it and then continue checking all other interfaces, since we need to throw an error if
6467 // we encounter conflicting default method implementations (one is not a subtype of the other).
6468 //
6469 // The order of unrelated interfaces does not matter and is not defined.
6470 size_t iftable_count = klass->GetIfTableCount();
6471 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006472 // No interfaces. We have already reset out to null so just return kAbstractFound.
6473 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006474 }
6475
Alex Light9139e002015-10-09 15:59:48 -07006476 StackHandleScope<3> hs(self);
6477 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006478 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006479 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006480 MethodNameAndSignatureComparator target_name_comparator(
6481 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6482 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006483 for (size_t k = iftable_count; k != 0; ) {
6484 --k;
6485
Alex Lighteb7c1442015-08-31 13:17:42 -07006486 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006487
6488 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006489 // Iterate through every declared method on this interface. The order does not matter.
6490 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6491 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006492 // Skip abstract methods and methods with different names.
6493 if (current_method->IsAbstract() ||
6494 !target_name_comparator.HasSameNameAndSignature(
6495 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6496 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006497 } else if (!current_method->IsPublic()) {
6498 // The verifier should have caught the non-public method for dex version 37. Just warn and
6499 // skip it since this is from before default-methods so we don't really need to care that it
6500 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006501 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6502 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006503 << "This will be a fatal error in subsequent versions of android. "
6504 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006505 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006506 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006507 // We have multiple default impls of the same method. This is a potential default conflict.
6508 // We need to check if this possibly conflicting method is either a superclass of the chosen
6509 // default implementation or is overridden by a non-default interface method. In either case
6510 // there is no conflict.
6511 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6512 !ContainsOverridingMethodOf(self,
6513 target_name_comparator,
6514 iftable,
6515 k,
6516 iface,
6517 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006518 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006519 << current_method->PrettyMethod() << " and "
6520 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6521 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006522 *out_default_method = nullptr;
6523 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006524 } else {
6525 break; // Continue checking at the next interface.
6526 }
6527 } else {
Alex Light9139e002015-10-09 15:59:48 -07006528 // chosen_iface == null
6529 if (!ContainsOverridingMethodOf(self,
6530 target_name_comparator,
6531 iftable,
6532 k,
6533 iface,
6534 image_pointer_size_)) {
6535 // Don't set this as the chosen interface if something else is overriding it (because that
6536 // other interface would be potentially chosen instead if it was default). If the other
6537 // interface was abstract then we wouldn't select this interface as chosen anyway since
6538 // the abstract method masks it.
6539 *out_default_method = current_method;
6540 chosen_iface.Assign(iface.Get());
6541 // We should now finish traversing the graph to find if we have default methods that
6542 // conflict.
6543 } else {
David Sehr709b0702016-10-13 09:12:37 -07006544 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6545 << "' was "
6546 << "skipped because it was overridden by an abstract method in a "
6547 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006548 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006549 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006550 break;
6551 }
6552 }
Alex Light9139e002015-10-09 15:59:48 -07006553 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006554 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6555 << "' selected "
6556 << "as the implementation for '" << target_method->PrettyMethod()
6557 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006558 return DefaultMethodSearchResult::kDefaultFound;
6559 } else {
6560 return DefaultMethodSearchResult::kAbstractFound;
6561 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006562}
6563
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006564ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006565 ArtMethod* conflict_method,
6566 ArtMethod* interface_method,
6567 ArtMethod* method,
6568 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006569 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006570 Runtime* const runtime = Runtime::Current();
6571 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6572 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6573
6574 // Create a new entry if the existing one is the shared conflict method.
6575 ArtMethod* new_conflict_method = new_entry
6576 ? runtime->CreateImtConflictMethod(linear_alloc)
6577 : conflict_method;
6578
6579 // Allocate a new table. Note that we will leak this table at the next conflict,
6580 // but that's a tradeoff compared to making the table fixed size.
6581 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006582 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6583 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006584 if (data == nullptr) {
6585 LOG(ERROR) << "Failed to allocate conflict table";
6586 return conflict_method;
6587 }
6588 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6589 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006590 method,
6591 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006592
6593 // Do a fence to ensure threads see the data in the table before it is assigned
6594 // to the conflict method.
6595 // Note that there is a race in the presence of multiple threads and we may leak
6596 // memory from the LinearAlloc, but that's a tradeoff compared to using
6597 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006598 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006599 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006600 return new_conflict_method;
6601}
6602
Vladimir Marko921094a2017-01-12 18:37:06 +00006603bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6604 Handle<mirror::Class> klass,
6605 Handle<mirror::IfTable> iftable) {
6606 DCHECK(!klass->IsInterface());
6607 const bool has_superclass = klass->HasSuperClass();
6608 const bool extend_super_iftable = has_superclass;
6609 const size_t ifcount = klass->GetIfTableCount();
6610 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6611 for (size_t i = 0; i < ifcount; ++i) {
6612 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6613 if (num_methods > 0) {
6614 const bool is_super = i < super_ifcount;
6615 // This is an interface implemented by a super-class. Therefore we can just copy the method
6616 // array from the superclass.
6617 const bool super_interface = is_super && extend_super_iftable;
6618 ObjPtr<mirror::PointerArray> method_array;
6619 if (super_interface) {
6620 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6621 DCHECK(if_table != nullptr);
6622 DCHECK(if_table->GetMethodArray(i) != nullptr);
6623 // If we are working on a super interface, try extending the existing method array.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00006624 method_array = ObjPtr<mirror::PointerArray>::DownCast(
6625 if_table->GetMethodArray(i)->Clone(self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006626 } else {
6627 method_array = AllocPointerArray(self, num_methods);
6628 }
6629 if (UNLIKELY(method_array == nullptr)) {
6630 self->AssertPendingOOMException();
6631 return false;
6632 }
6633 iftable->SetMethodArray(i, method_array);
6634 }
6635 }
6636 return true;
6637}
6638
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006639void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6640 ArtMethod* imt_conflict_method,
6641 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006642 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006643 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006644 // Place method in imt if entry is empty, place conflict otherwise.
6645 if (*imt_ref == unimplemented_method) {
6646 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006647 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006648 // If we are not a conflict and we have the same signature and name as the imt
6649 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006650 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6651 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006652 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006653 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006654 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006655 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006656 *imt_ref = current_method;
6657 } else {
Alex Light9139e002015-10-09 15:59:48 -07006658 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006659 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006660 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006661 } else {
6662 // Place the default conflict method. Note that there may be an existing conflict
6663 // method in the IMT, but it could be one tailored to the super class, with a
6664 // specific ImtConflictTable.
6665 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006666 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006667 }
6668}
6669
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006670void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006671 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6672 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006673 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006674 Runtime* const runtime = Runtime::Current();
6675 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6676 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006677 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006678 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006679 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006680 FillIMTFromIfTable(klass->GetIfTable(),
6681 unimplemented_method,
6682 conflict_method,
6683 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006684 /*create_conflict_tables=*/true,
6685 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006686 &new_conflict,
6687 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006688 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006689 if (!klass->ShouldHaveImt()) {
6690 return;
6691 }
6692 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6693 // we can just use the same pointer.
6694 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006695 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006696 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6697 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6698 bool same = true;
6699 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6700 ArtMethod* method = imt_data[i];
6701 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6702 if (method != super_method) {
6703 bool is_conflict_table = method->IsRuntimeMethod() &&
6704 method != unimplemented_method &&
6705 method != conflict_method;
6706 // Verify conflict contents.
6707 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6708 super_method != unimplemented_method &&
6709 super_method != conflict_method;
6710 if (!is_conflict_table || !super_conflict_table) {
6711 same = false;
6712 } else {
6713 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6714 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6715 same = same && table1->Equals(table2, image_pointer_size_);
6716 }
6717 }
6718 }
6719 if (same) {
6720 imt = super_imt;
6721 }
6722 }
6723 if (imt == nullptr) {
6724 imt = klass->GetImt(image_pointer_size_);
6725 DCHECK(imt != nullptr);
6726 imt->Populate(imt_data, image_pointer_size_);
6727 } else {
6728 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006729 }
6730}
6731
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006732ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6733 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006734 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006735 void* data = linear_alloc->Alloc(Thread::Current(),
6736 ImtConflictTable::ComputeSize(count,
6737 image_pointer_size));
6738 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6739}
6740
6741ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6742 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6743}
6744
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006745void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006746 ArtMethod* unimplemented_method,
6747 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006748 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006749 bool create_conflict_tables,
6750 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006751 /*out*/bool* new_conflict,
6752 /*out*/ArtMethod** imt) {
6753 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006754 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006755 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006756 const size_t num_virtuals = interface->NumVirtualMethods();
6757 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6758 // Virtual methods can be larger than the if table methods if there are default methods.
6759 DCHECK_GE(num_virtuals, method_array_count);
6760 if (kIsDebugBuild) {
6761 if (klass->IsInterface()) {
6762 DCHECK_EQ(method_array_count, 0u);
6763 } else {
6764 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6765 }
6766 }
6767 if (method_array_count == 0) {
6768 continue;
6769 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006770 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006771 for (size_t j = 0; j < method_array_count; ++j) {
6772 ArtMethod* implementation_method =
6773 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6774 if (ignore_copied_methods && implementation_method->IsCopied()) {
6775 continue;
6776 }
6777 DCHECK(implementation_method != nullptr);
6778 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6779 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6780 // or interface methods in the IMT here they will not create extra conflicts since we compare
6781 // names and signatures in SetIMTRef.
6782 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006783 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006784
6785 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6786 // the same implementation method, keep track of this to avoid creating a conflict table in
6787 // this case.
6788
6789 // Conflict table size for each IMT slot.
6790 ++conflict_counts[imt_index];
6791
6792 SetIMTRef(unimplemented_method,
6793 imt_conflict_method,
6794 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006795 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006796 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006797 }
6798 }
6799
6800 if (create_conflict_tables) {
6801 // Create the conflict tables.
6802 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006803 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006804 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006805 if (imt[i] == imt_conflict_method) {
6806 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6807 if (new_table != nullptr) {
6808 ArtMethod* new_conflict_method =
6809 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6810 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6811 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006812 } else {
6813 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006814 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006815 }
6816 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006817 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006818 }
6819 }
6820
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006822 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006823 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6824 // Virtual methods can be larger than the if table methods if there are default methods.
6825 if (method_array_count == 0) {
6826 continue;
6827 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006828 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006829 for (size_t j = 0; j < method_array_count; ++j) {
6830 ArtMethod* implementation_method =
6831 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6832 if (ignore_copied_methods && implementation_method->IsCopied()) {
6833 continue;
6834 }
6835 DCHECK(implementation_method != nullptr);
6836 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006837 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006838 if (!imt[imt_index]->IsRuntimeMethod() ||
6839 imt[imt_index] == unimplemented_method ||
6840 imt[imt_index] == imt_conflict_method) {
6841 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006842 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006843 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6844 const size_t num_entries = table->NumEntries(image_pointer_size_);
6845 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6846 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006847 }
6848 }
6849 }
6850}
6851
Alex Lighteb7c1442015-08-31 13:17:42 -07006852// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6853// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006854static bool NotSubinterfaceOfAny(
6855 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6856 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006857 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006858 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006859 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006860 for (ObjPtr<mirror::Class> c : classes) {
6861 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006862 return false;
6863 }
6864 }
6865 return true;
6866}
6867
6868// Fills in and flattens the interface inheritance hierarchy.
6869//
6870// By the end of this function all interfaces in the transitive closure of to_process are added to
6871// the iftable and every interface precedes all of its sub-interfaces in this list.
6872//
6873// all I, J: Interface | I <: J implies J precedes I
6874//
6875// (note A <: B means that A is a subtype of B)
6876//
6877// This returns the total number of items in the iftable. The iftable might be resized down after
6878// this call.
6879//
6880// We order this backwards so that we do not need to reorder superclass interfaces when new
6881// interfaces are added in subclass's interface tables.
6882//
6883// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6884// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6885// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6886// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006887static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006888 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006889 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006890 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006891 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006892 // This is the set of all class's already in the iftable. Used to make checking if a class has
6893 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006894 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 // The first super_ifcount elements are from the superclass. We note that they are already added.
6896 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006897 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006898 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6899 classes_in_iftable.insert(iface);
6900 }
6901 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006902 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006903 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6904 // At this point in the loop current-iface-list has the invariant that:
6905 // for every pair of interfaces I,J within it:
6906 // if index_of(I) < index_of(J) then I is not a subtype of J
6907
6908 // If we have already seen this element then all of its super-interfaces must already be in the
6909 // current-iface-list so we can skip adding it.
6910 if (!ContainsElement(classes_in_iftable, interface)) {
6911 // We haven't seen this interface so add all of its super-interfaces onto the
6912 // current-iface-list, skipping those already on it.
6913 int32_t ifcount = interface->GetIfTableCount();
6914 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006915 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006916 if (!ContainsElement(classes_in_iftable, super_interface)) {
6917 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6918 classes_in_iftable.insert(super_interface);
6919 iftable->SetInterface(filled_ifcount, super_interface);
6920 filled_ifcount++;
6921 }
6922 }
6923 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6924 // Place this interface onto the current-iface-list after all of its super-interfaces.
6925 classes_in_iftable.insert(interface);
6926 iftable->SetInterface(filled_ifcount, interface);
6927 filled_ifcount++;
6928 } else if (kIsDebugBuild) {
6929 // Check all super-interfaces are already in the list.
6930 int32_t ifcount = interface->GetIfTableCount();
6931 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006932 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006933 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006934 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6935 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006936 }
6937 }
6938 }
6939 if (kIsDebugBuild) {
6940 // Check that the iftable is ordered correctly.
6941 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006942 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006943 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006944 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006945 // !(if_a <: if_b)
6946 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006947 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6948 << ") extends "
6949 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006950 << "interface list.";
6951 }
6952 }
6953 }
6954 return filled_ifcount;
6955}
6956
6957bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6958 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6959 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006960 const bool has_superclass = klass->HasSuperClass();
6961 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006962 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006963 const size_t num_interfaces =
6964 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006965 if (num_interfaces == 0) {
6966 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006967 if (LIKELY(has_superclass)) {
6968 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6969 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006970 // Class implements no interfaces.
6971 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006972 return true;
6973 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006974 // Class implements same interfaces as parent, are any of these not marker interfaces?
6975 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006976 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006977 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006978 if (super_iftable->GetMethodArrayCount(i) > 0) {
6979 has_non_marker_interface = true;
6980 break;
6981 }
6982 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006983 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006984 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006985 klass->SetIfTable(super_iftable);
6986 return true;
6987 }
6988 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006989 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006990 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006991 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006992 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006993 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006994 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006995 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006996 if (UNLIKELY(!interface->IsInterface())) {
6997 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006998 ThrowIncompatibleClassChangeError(klass.Get(),
6999 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007000 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007001 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7002 return false;
7003 }
7004 ifcount += interface->GetIfTableCount();
7005 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007006 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007007 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007008 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007009 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007010 return false;
7011 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007012 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007013 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007014 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007015 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007016 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007017 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007018 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007019 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007020
7021 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7022 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7023 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007024 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007025
7026 size_t new_ifcount;
7027 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007028 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007029 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007030 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007031 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007032 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007033 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007034 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007035
7036 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007037 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007038
Ian Rogers7b078e82014-09-10 14:44:24 -07007039 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007040
Ian Rogersb52b01a2012-01-12 17:01:38 -08007041 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007042 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007043 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007044 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007045 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007046 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007047 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007048 return false;
7049 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007050 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007051 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007052 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007053 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007054 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007055 return true;
7056}
7057
Alex Light1f3925d2016-09-07 12:04:20 -07007058// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7059// of methods must be unique.
7060static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7061 return nullptr;
7062}
7063
7064template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007065static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007066 const ScopedArenaVector<ArtMethod*>& list,
7067 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007068 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007069 for (ArtMethod* method : list) {
7070 if (cmp.HasSameNameAndSignature(method)) {
7071 return method;
7072 }
7073 }
Alex Light1f3925d2016-09-07 12:04:20 -07007074 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007075}
7076
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007077namespace {
7078
Alex Light1f3925d2016-09-07 12:04:20 -07007079// Check that all vtable entries are present in this class's virtuals or are the same as a
7080// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007081void CheckClassOwnsVTableEntries(Thread* self,
7082 Handle<mirror::Class> klass,
7083 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007084 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007085 StackHandleScope<2> hs(self);
7086 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007087 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007088 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007089 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007090 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7091 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7092 CHECK(m != nullptr);
7093
Alex Lighta41a30782017-03-29 11:33:19 -07007094 if (m->GetMethodIndexDuringLinking() != i) {
7095 LOG(WARNING) << m->PrettyMethod()
7096 << " has an unexpected method index for its spot in the vtable for class"
7097 << klass->PrettyClass();
7098 }
Alex Lighte64300b2015-12-15 15:02:47 -08007099 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7100 auto is_same_method = [m] (const ArtMethod& meth) {
7101 return &meth == m;
7102 };
Alex Light3f980532017-03-17 15:10:32 -07007103 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7104 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7105 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7106 << klass->PrettyClass() << " or any of its superclasses!";
7107 }
Alex Lighte64300b2015-12-15 15:02:47 -08007108 }
7109}
7110
Alex Light1f3925d2016-09-07 12:04:20 -07007111// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7112// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007113template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007114void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007115 REQUIRES_SHARED(Locks::mutator_lock_) {
7116 StackHandleScope<1> hs(self);
7117 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7118 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007119
7120 // Observations:
7121 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7122 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7123 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7124 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7125 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7126 // * The single-pass algorithm will trade memory for speed, but that is OK.
7127
7128 CHECK_GT(num_entries, 0);
7129
7130 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7131 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7132 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7133 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7134 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7135 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7136 << m2->PrettyMethod() << " (0x" << std::hex
7137 << reinterpret_cast<uintptr_t>(m2) << ")";
7138 };
7139 struct BaseHashType {
7140 static size_t HashCombine(size_t seed, size_t val) {
7141 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7142 }
7143 };
7144
7145 // Check assuming all entries come from the same dex file.
7146 {
7147 // Find the first interesting method and its dex file.
7148 int32_t start = 0;
7149 for (; start < num_entries; ++start) {
7150 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7151 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7152 // maybe).
7153 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7154 vtable_entry->GetAccessFlags())) {
7155 continue;
7156 }
7157 break;
7158 }
7159 if (start == num_entries) {
7160 return;
7161 }
7162 const DexFile* dex_file =
7163 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7164 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7165
7166 // Helper function to avoid logging if we have to run the cross-file checks.
7167 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7168 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7169 using PairType = std::pair<uint32_t, uint16_t>;
7170 struct PairHash : BaseHashType {
7171 size_t operator()(const PairType& key) const {
7172 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7173 }
7174 };
7175 std::unordered_map<PairType, int32_t, PairHash> seen;
7176 seen.reserve(2 * num_entries);
7177 bool need_slow_path = false;
7178 bool found_dup = false;
7179 for (int i = start; i < num_entries; ++i) {
7180 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7181 // wrt/ kPointerSize.
7182 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7183 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7184 vtable_entry->GetAccessFlags())) {
7185 continue;
7186 }
7187 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7188 if (dex_file != m->GetDexFile()) {
7189 need_slow_path = true;
7190 break;
7191 }
7192 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7193 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7194 auto it = seen.find(pair);
7195 if (it != seen.end()) {
7196 found_dup = true;
7197 if (log_warn) {
7198 log_fn(it->second, i);
7199 }
7200 } else {
7201 seen.emplace(pair, i);
7202 }
7203 }
7204 return std::make_pair(need_slow_path, found_dup);
7205 };
7206 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7207 if (!result.first) {
7208 if (result.second) {
7209 check_fn(/* log_warn= */ true);
7210 }
7211 return;
7212 }
7213 }
7214
7215 // Need to check across dex files.
7216 struct Entry {
7217 size_t cached_hash = 0;
7218 const char* name = nullptr;
7219 Signature signature = Signature::NoSignature();
7220 uint32_t name_len = 0;
7221
7222 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7223 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7224 signature(dex_file->GetMethodSignature(mid)) {
7225 }
7226
7227 bool operator==(const Entry& other) const {
7228 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7229 return false;
7230 }
7231 return signature == other.signature;
7232 }
7233 };
7234 struct EntryHash {
7235 size_t operator()(const Entry& key) const {
7236 return key.cached_hash;
7237 }
7238 };
7239 std::unordered_map<Entry, int32_t, EntryHash> map;
7240 for (int32_t i = 0; i < num_entries; ++i) {
7241 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7242 // wrt/ kPointerSize.
7243 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7244 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7245 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007246 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7247 vtable_entry->GetAccessFlags())) {
7248 continue;
7249 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007250 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7251 const DexFile* dex_file = m->GetDexFile();
7252 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7253
7254 Entry e(dex_file, mid);
7255
7256 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7257 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7258 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7259 sig_hash);
7260
7261 auto it = map.find(e);
7262 if (it != map.end()) {
7263 log_fn(it->second, i);
7264 } else {
7265 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007266 }
7267 }
7268}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007269
7270void CheckVTableHasNoDuplicates(Thread* self,
7271 Handle<mirror::Class> klass,
7272 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007273 REQUIRES_SHARED(Locks::mutator_lock_) {
7274 switch (pointer_size) {
7275 case PointerSize::k64:
7276 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7277 break;
7278 case PointerSize::k32:
7279 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7280 break;
7281 }
7282}
Alex Light1f3925d2016-09-07 12:04:20 -07007283
7284static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7285 REQUIRES_SHARED(Locks::mutator_lock_) {
7286 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7287 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7288}
7289
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007290} // namespace
7291
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007292void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7293 ArtMethod* unimplemented_method,
7294 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007295 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007296 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007297 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007298 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007299 if (super_class->ShouldHaveImt()) {
7300 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7301 for (size_t i = 0; i < ImTable::kSize; ++i) {
7302 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007303 }
7304 } else {
7305 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007306 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007307 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007308 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007309 FillIMTFromIfTable(if_table,
7310 unimplemented_method,
7311 imt_conflict_method,
7312 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007313 /*create_conflict_tables=*/false,
7314 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007315 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007316 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007317 }
7318 }
7319}
7320
Vladimir Marko921094a2017-01-12 18:37:06 +00007321class ClassLinker::LinkInterfaceMethodsHelper {
7322 public:
7323 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7324 Handle<mirror::Class> klass,
7325 Thread* self,
7326 Runtime* runtime)
7327 : class_linker_(class_linker),
7328 klass_(klass),
7329 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7330 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7331 self_(self),
7332 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7333 allocator_(&stack_),
7334 default_conflict_methods_(allocator_.Adapter()),
7335 overriding_default_conflict_methods_(allocator_.Adapter()),
7336 miranda_methods_(allocator_.Adapter()),
7337 default_methods_(allocator_.Adapter()),
7338 overriding_default_methods_(allocator_.Adapter()),
7339 move_table_(allocator_.Adapter()) {
7340 }
7341
7342 ArtMethod* FindMethod(ArtMethod* interface_method,
7343 MethodNameAndSignatureComparator& interface_name_comparator,
7344 ArtMethod* vtable_impl)
7345 REQUIRES_SHARED(Locks::mutator_lock_);
7346
7347 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7348 MethodNameAndSignatureComparator& interface_name_comparator)
7349 REQUIRES_SHARED(Locks::mutator_lock_);
7350
7351 bool HasNewVirtuals() const {
7352 return !(miranda_methods_.empty() &&
7353 default_methods_.empty() &&
7354 overriding_default_methods_.empty() &&
7355 overriding_default_conflict_methods_.empty() &&
7356 default_conflict_methods_.empty());
7357 }
7358
7359 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7360
7361 ObjPtr<mirror::PointerArray> UpdateVtable(
7362 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7363 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7364
7365 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7366
7367 void UpdateIMT(ArtMethod** out_imt);
7368
7369 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7370 if (kIsDebugBuild) {
7371 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7372 // Check that there are no stale methods are in the dex cache array.
7373 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7374 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007375 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7376 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007377 CHECK(move_table_.find(m) == move_table_.end() ||
7378 // The original versions of copied methods will still be present so allow those too.
7379 // Note that if the first check passes this might fail to GetDeclaringClass().
7380 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7381 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7382 [m] (ArtMethod& meth) {
7383 return &meth == m;
7384 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7385 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7386 }
7387 }
7388 }
7389
7390 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7391 LengthPrefixedArray<ArtMethod>* methods) {
7392 if (kIsDebugBuild) {
7393 CHECK(methods != nullptr);
7394 // Put some random garbage in old methods to help find stale pointers.
7395 if (methods != old_methods && old_methods != nullptr) {
7396 // Need to make sure the GC is not running since it could be scanning the methods we are
7397 // about to overwrite.
7398 ScopedThreadStateChange tsc(self_, kSuspended);
7399 gc::ScopedGCCriticalSection gcs(self_,
7400 gc::kGcCauseClassLinker,
7401 gc::kCollectorTypeClassLinker);
7402 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7403 method_size_,
7404 method_alignment_);
7405 memset(old_methods, 0xFEu, old_size);
7406 }
7407 }
7408 }
7409
7410 private:
7411 size_t NumberOfNewVirtuals() const {
7412 return miranda_methods_.size() +
7413 default_methods_.size() +
7414 overriding_default_conflict_methods_.size() +
7415 overriding_default_methods_.size() +
7416 default_conflict_methods_.size();
7417 }
7418
7419 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7420 return !klass_->IsInterface();
7421 }
7422
7423 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7424 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7425 << "Interfaces should only have default-conflict methods appended to them.";
7426 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7427 << miranda_methods_.size()
7428 << " default_methods=" << default_methods_.size()
7429 << " overriding_default_methods=" << overriding_default_methods_.size()
7430 << " default_conflict_methods=" << default_conflict_methods_.size()
7431 << " overriding_default_conflict_methods="
7432 << overriding_default_conflict_methods_.size();
7433 }
7434
7435 ClassLinker* class_linker_;
7436 Handle<mirror::Class> klass_;
7437 size_t method_alignment_;
7438 size_t method_size_;
7439 Thread* const self_;
7440
7441 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7442 // the virtual methods array.
7443 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7444 // during cross compilation.
7445 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7446 ArenaStack stack_;
7447 ScopedArenaAllocator allocator_;
7448
7449 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7450 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7451 ScopedArenaVector<ArtMethod*> miranda_methods_;
7452 ScopedArenaVector<ArtMethod*> default_methods_;
7453 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7454
7455 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7456};
7457
7458ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7459 ArtMethod* interface_method,
7460 MethodNameAndSignatureComparator& interface_name_comparator,
7461 ArtMethod* vtable_impl) {
7462 ArtMethod* current_method = nullptr;
7463 switch (class_linker_->FindDefaultMethodImplementation(self_,
7464 interface_method,
7465 klass_,
7466 /*out*/&current_method)) {
7467 case DefaultMethodSearchResult::kDefaultConflict: {
7468 // Default method conflict.
7469 DCHECK(current_method == nullptr);
7470 ArtMethod* default_conflict_method = nullptr;
7471 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7472 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7473 default_conflict_method = vtable_impl;
7474 } else {
7475 // See if we already have a conflict method for this method.
7476 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7477 interface_name_comparator,
7478 default_conflict_methods_,
7479 overriding_default_conflict_methods_);
7480 if (LIKELY(preexisting_conflict != nullptr)) {
7481 // We already have another conflict we can reuse.
7482 default_conflict_method = preexisting_conflict;
7483 } else {
7484 // Note that we do this even if we are an interface since we need to create this and
7485 // cannot reuse another classes.
7486 // Create a new conflict method for this to use.
7487 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7488 new(default_conflict_method) ArtMethod(interface_method,
7489 class_linker_->GetImagePointerSize());
7490 if (vtable_impl == nullptr) {
7491 // Save the conflict method. We need to add it to the vtable.
7492 default_conflict_methods_.push_back(default_conflict_method);
7493 } else {
7494 // Save the conflict method but it is already in the vtable.
7495 overriding_default_conflict_methods_.push_back(default_conflict_method);
7496 }
7497 }
7498 }
7499 current_method = default_conflict_method;
7500 break;
7501 } // case kDefaultConflict
7502 case DefaultMethodSearchResult::kDefaultFound: {
7503 DCHECK(current_method != nullptr);
7504 // Found a default method.
7505 if (vtable_impl != nullptr &&
7506 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7507 // We found a default method but it was the same one we already have from our
7508 // superclass. Don't bother adding it to our vtable again.
7509 current_method = vtable_impl;
7510 } else if (LIKELY(FillTables())) {
7511 // Interfaces don't need to copy default methods since they don't have vtables.
7512 // Only record this default method if it is new to save space.
7513 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7514 // would make lookup for interface super much faster. (We would only need to scan
7515 // the iftable to find if there is a NSME or AME.)
7516 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7517 default_methods_,
7518 overriding_default_methods_);
7519 if (old == nullptr) {
7520 // We found a default method implementation and there were no conflicts.
7521 if (vtable_impl == nullptr) {
7522 // Save the default method. We need to add it to the vtable.
7523 default_methods_.push_back(current_method);
7524 } else {
7525 // Save the default method but it is already in the vtable.
7526 overriding_default_methods_.push_back(current_method);
7527 }
7528 } else {
7529 CHECK(old == current_method) << "Multiple default implementations selected!";
7530 }
7531 }
7532 break;
7533 } // case kDefaultFound
7534 case DefaultMethodSearchResult::kAbstractFound: {
7535 DCHECK(current_method == nullptr);
7536 // Abstract method masks all defaults.
7537 if (vtable_impl != nullptr &&
7538 vtable_impl->IsAbstract() &&
7539 !vtable_impl->IsDefaultConflicting()) {
7540 // We need to make this an abstract method but the version in the vtable already is so
7541 // don't do anything.
7542 current_method = vtable_impl;
7543 }
7544 break;
7545 } // case kAbstractFound
7546 }
7547 return current_method;
7548}
7549
7550ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7551 ArtMethod* interface_method,
7552 MethodNameAndSignatureComparator& interface_name_comparator) {
7553 // Find out if there is already a miranda method we can use.
7554 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7555 miranda_methods_);
7556 if (miranda_method == nullptr) {
7557 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7558 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7559 CHECK(miranda_method != nullptr);
7560 // Point the interface table at a phantom slot.
7561 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7562 miranda_methods_.push_back(miranda_method);
7563 }
7564 return miranda_method;
7565}
7566
7567void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7568 LogNewVirtuals();
7569
7570 const size_t old_method_count = klass_->NumMethods();
7571 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7572 DCHECK_NE(old_method_count, new_method_count);
7573
7574 // Attempt to realloc to save RAM if possible.
7575 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7576 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7577 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7578 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7579 // CopyFrom has internal read barriers.
7580 //
7581 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7582 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7583 method_size_,
7584 method_alignment_);
7585 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7586 method_size_,
7587 method_alignment_);
7588 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7589 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007590 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007591 self_, old_methods, old_methods_ptr_size, new_size));
7592 CHECK(methods != nullptr); // Native allocation failure aborts.
7593
7594 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7595 if (methods != old_methods) {
7596 // Maps from heap allocated miranda method to linear alloc miranda method.
7597 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7598 // Copy over the old methods.
7599 for (auto& m : klass_->GetMethods(pointer_size)) {
7600 move_table_.emplace(&m, &*out);
7601 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7602 // barriers when it copies.
7603 out->CopyFrom(&m, pointer_size);
7604 ++out;
7605 }
7606 }
7607 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7608 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7609 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007610 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7611 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007612 ArtMethod& new_method = *out;
7613 new_method.CopyFrom(mir_method, pointer_size);
7614 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7615 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7616 << "Miranda method should be abstract!";
7617 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007618 // Update the entry in the method array, as the array will be used for future lookups,
7619 // where thread suspension is allowed.
7620 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7621 // would not see them.
7622 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007623 ++out;
7624 }
7625 // We need to copy the default methods into our own method table since the runtime requires that
7626 // every method on a class's vtable be in that respective class's virtual method table.
7627 // NOTE This means that two classes might have the same implementation of a method from the same
7628 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7629 // default method found on a class with one found on the declaring interface directly and must
7630 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007631 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7632 &overriding_default_methods_}) {
7633 for (size_t i = 0; i < methods_vec->size(); ++i) {
7634 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007635 ArtMethod& new_method = *out;
7636 new_method.CopyFrom(def_method, pointer_size);
7637 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7638 // verified yet it shouldn't have methods that are skipping access checks.
7639 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7640 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007641 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007642 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7643 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7644 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7645 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007646 // Update the entry in the method array, as the array will be used for future lookups,
7647 // where thread suspension is allowed.
7648 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7649 // would not see them.
7650 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007651 ++out;
7652 }
7653 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007654 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7655 &overriding_default_conflict_methods_}) {
7656 for (size_t i = 0; i < methods_vec->size(); ++i) {
7657 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007658 ArtMethod& new_method = *out;
7659 new_method.CopyFrom(conf_method, pointer_size);
7660 // This is a type of default method (there are default method impls, just a conflict) so
7661 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7662 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7663 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007664 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7665 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007666 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007667 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007668 constexpr uint32_t kMaskFlags =
7669 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007670 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7671 DCHECK(new_method.IsDefaultConflicting());
7672 // The actual method might or might not be marked abstract since we just copied it from a
7673 // (possibly default) interface method. We need to set it entry point to be the bridge so
7674 // that the compiler will not invoke the implementation of whatever method we copied from.
7675 EnsureThrowsInvocationError(class_linker_, &new_method);
7676 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007677 // Update the entry in the method array, as the array will be used for future lookups,
7678 // where thread suspension is allowed.
7679 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7680 // would not see them.
7681 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007682 ++out;
7683 }
7684 }
7685 methods->SetSize(new_method_count);
7686 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7687}
7688
7689ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7690 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7691 ObjPtr<mirror::PointerArray> old_vtable) {
7692 // Update the vtable to the new method structures. We can skip this for interfaces since they
7693 // do not have vtables.
7694 const size_t old_vtable_count = old_vtable->GetLength();
7695 const size_t new_vtable_count = old_vtable_count +
7696 miranda_methods_.size() +
7697 default_methods_.size() +
7698 default_conflict_methods_.size();
7699
7700 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007701 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007702 if (UNLIKELY(vtable == nullptr)) {
7703 self_->AssertPendingOOMException();
7704 return nullptr;
7705 }
7706
7707 size_t vtable_pos = old_vtable_count;
7708 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7709 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7710 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7711 default_conflict_methods_,
7712 miranda_methods_}) {
7713 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007714 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007715 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7716 // fields are references into the dex file the method was defined in. Since the ArtMethod
7717 // does not store that information it uses declaring_class_->dex_cache_.
7718 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7719 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7720 ++vtable_pos;
7721 }
7722 }
7723 DCHECK_EQ(vtable_pos, new_vtable_count);
7724
7725 // Update old vtable methods. We use the default_translations map to figure out what each
7726 // vtable entry should be updated to, if they need to be at all.
7727 for (size_t i = 0; i < old_vtable_count; ++i) {
7728 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7729 // Try and find what we need to change this method to.
7730 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007731 if (translation_it != default_translations.end()) {
7732 if (translation_it->second.IsInConflict()) {
7733 // Find which conflict method we are to use for this method.
7734 MethodNameAndSignatureComparator old_method_comparator(
7735 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7736 // We only need to look through overriding_default_conflict_methods since this is an
7737 // overridden method we are fixing up here.
7738 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7739 old_method_comparator, overriding_default_conflict_methods_);
7740 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7741 translated_method = new_conflict_method;
7742 } else if (translation_it->second.IsAbstract()) {
7743 // Find which miranda method we are to use for this method.
7744 MethodNameAndSignatureComparator old_method_comparator(
7745 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7746 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7747 miranda_methods_);
7748 DCHECK(miranda_method != nullptr);
7749 translated_method = miranda_method;
7750 } else {
7751 // Normal default method (changed from an older default or abstract interface method).
7752 DCHECK(translation_it->second.IsTranslation());
7753 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007754 auto it = move_table_.find(translated_method);
7755 DCHECK(it != move_table_.end());
7756 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007757 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007758 } else {
7759 auto it = move_table_.find(translated_method);
7760 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007761 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007762
7763 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007764 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007765 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007766 if (kIsDebugBuild) {
7767 auto* methods = klass_->GetMethodsPtr();
7768 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007769 reinterpret_cast<uintptr_t>(translated_method));
7770 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007771 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7772 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007773 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007774 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007775 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007776 }
7777 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007778 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007779 return vtable;
7780}
7781
7782void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7783 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7784 const size_t ifcount = klass_->GetIfTableCount();
7785 // Go fix up all the stale iftable pointers.
7786 for (size_t i = 0; i < ifcount; ++i) {
7787 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007788 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7789 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007790 DCHECK(m != nullptr) << klass_->PrettyClass();
7791 auto it = move_table_.find(m);
7792 if (it != move_table_.end()) {
7793 auto* new_m = it->second;
7794 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7795 method_array->SetElementPtrSize(j, new_m, pointer_size);
7796 }
7797 }
7798 }
7799}
7800
7801void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7802 // Fix up IMT next.
7803 for (size_t i = 0; i < ImTable::kSize; ++i) {
7804 auto it = move_table_.find(out_imt[i]);
7805 if (it != move_table_.end()) {
7806 out_imt[i] = it->second;
7807 }
7808 }
7809}
7810
Alex Light705ad492015-09-21 11:36:30 -07007811// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007812bool ClassLinker::LinkInterfaceMethods(
7813 Thread* self,
7814 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007815 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007816 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007817 ArtMethod** out_imt) {
7818 StackHandleScope<3> hs(self);
7819 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007820
7821 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007822 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007823 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007824 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007825 const size_t ifcount = klass->GetIfTableCount();
7826
Vladimir Marko921094a2017-01-12 18:37:06 +00007827 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007828
7829 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7830 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007831 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007832 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007833 const bool extend_super_iftable = has_superclass;
7834 if (has_superclass && fill_tables) {
7835 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007836 unimplemented_method,
7837 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007838 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007839 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007840 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007841 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7842 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007843 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007844 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7845 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007846 }
7847 }
7848
Vladimir Marko921094a2017-01-12 18:37:06 +00007849 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7850
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007851 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007852 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007853 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7854 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7855 // they will already be null. This has the additional benefit that the declarer of a miranda
7856 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007857 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007858 --i;
Alex Light9139e002015-10-09 15:59:48 -07007859 DCHECK_LT(i, ifcount);
7860
Alex Light705ad492015-09-21 11:36:30 -07007861 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007862 if (num_methods > 0) {
7863 StackHandleScope<2> hs2(self);
7864 const bool is_super = i < super_ifcount;
7865 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007866 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7867 // conflict methods. Just set this as nullptr in those cases.
7868 Handle<mirror::PointerArray> method_array(fill_tables
7869 ? hs2.NewHandle(iftable->GetMethodArray(i))
7870 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007871
Alex Lighte64300b2015-12-15 15:02:47 -08007872 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007873 ScopedNullHandle<mirror::PointerArray> null_handle;
7874 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007875 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007876
Alex Light9139e002015-10-09 15:59:48 -07007877 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7878 // and confusing. Default methods should always look through all the superclasses
7879 // because they are the last choice of an implementation. We get around this by looking
7880 // at the super-classes iftable methods (copied into method_array previously) when we are
7881 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007882 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007883 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007884 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007885 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007886 using_virtuals = true;
7887 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7888 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007889 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007890 // For a new interface, however, we need the whole vtable in case a new
7891 // interface method is implemented in the whole superclass.
7892 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007893 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007894 input_vtable_array = vtable;
7895 input_array_length = input_vtable_array->GetLength();
7896 }
Alex Lighte64300b2015-12-15 15:02:47 -08007897
Alex Lighteb7c1442015-08-31 13:17:42 -07007898 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007899 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007900 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007901 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007902 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007903 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007904 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007905 // For each method listed in the interface's method list, find the
7906 // matching method in our class's method list. We want to favor the
7907 // subclass over the superclass, which just requires walking
7908 // back from the end of the vtable. (This only matters if the
7909 // superclass defines a private method and this class redefines
7910 // it -- otherwise it would use the same vtable slot. In .dex files
7911 // those don't end up in the virtual method table, so it shouldn't
7912 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007913 //
7914 // To find defaults we need to do the same but also go over interfaces.
7915 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007916 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007917 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007918 ArtMethod* vtable_method = using_virtuals ?
7919 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007920 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7921 ArtMethod* vtable_method_for_name_comparison =
7922 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007923 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007924 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007925 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007926 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7927 // allocations.
7928 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007929 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007930 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007931 vtable_method->PrettyMethod().c_str(),
7932 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007933 return false;
Alex Light9139e002015-10-09 15:59:48 -07007934 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007935 // We might have a newer, better, default method for this, so we just skip it. If we
7936 // are still using this we will select it again when scanning for default methods. To
7937 // obviate the need to copy the method again we will make a note that we already found
7938 // a default here.
7939 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007940 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007941 break;
7942 } else {
7943 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007944 if (LIKELY(fill_tables)) {
7945 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7946 // Place method in imt if entry is empty, place conflict otherwise.
7947 SetIMTRef(unimplemented_method,
7948 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007949 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007950 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007951 /*out*/imt_ptr);
7952 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007953 break;
7954 }
7955 }
Alex Light9139e002015-10-09 15:59:48 -07007956 }
7957 // Continue on to the next method if we are done.
7958 if (LIKELY(found_impl)) {
7959 continue;
7960 } else if (LIKELY(super_interface)) {
7961 // Don't look for a default implementation when the super-method is implemented directly
7962 // by the class.
7963 //
7964 // See if we can use the superclasses method and skip searching everything else.
7965 // Note: !found_impl && super_interface
7966 CHECK(extend_super_iftable);
7967 // If this is a super_interface method it is possible we shouldn't override it because a
7968 // superclass could have implemented it directly. We get the method the superclass used
7969 // to implement this to know if we can override it with a default method. Doing this is
7970 // safe since we know that the super_iftable is filled in so we can simply pull it from
7971 // there. We don't bother if this is not a super-classes interface since in that case we
7972 // have scanned the entire vtable anyway and would have found it.
7973 // TODO This is rather dirty but it is faster than searching through the entire vtable
7974 // every time.
7975 ArtMethod* supers_method =
7976 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7977 DCHECK(supers_method != nullptr);
7978 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007979 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007980 // The method is not overridable by a default method (i.e. it is directly implemented
7981 // in some class). Therefore move onto the next interface method.
7982 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007983 } else {
7984 // If the super-classes method is override-able by a default method we need to keep
7985 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7986 // 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 -07007987 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7988 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7989 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007990 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007991 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7992 << " and not 'nullptr' or "
7993 << supers_method->PrettyMethod()
7994 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007995 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007996 }
7997 }
7998 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007999 ArtMethod* current_method = helper.FindMethod(interface_method,
8000 interface_name_comparator,
8001 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008002 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008003 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008004 // We could not find an implementation for this method and since it is a brand new
8005 // interface we searched the entire vtable (and all default methods) for an
8006 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008007 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8008 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008009 }
8010
8011 if (current_method != nullptr) {
8012 // We found a default method implementation. Record it in the iftable and IMT.
8013 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8014 SetIMTRef(unimplemented_method,
8015 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008016 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008017 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008018 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008019 }
8020 }
Alex Light705ad492015-09-21 11:36:30 -07008021 } // For each method in interface end.
8022 } // if (num_methods > 0)
8023 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008024 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008025 if (helper.HasNewVirtuals()) {
8026 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8027 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8028 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8029
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008030 // 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 -07008031 // suspension assert.
8032 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008033
Alex Light705ad492015-09-21 11:36:30 -07008034 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008035 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008036 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008037 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008038 return false;
8039 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008040 helper.UpdateIfTable(iftable);
8041 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008042 }
Alex Light705ad492015-09-21 11:36:30 -07008043
Vladimir Marko921094a2017-01-12 18:37:06 +00008044 helper.CheckNoStaleMethodsInDexCache();
8045 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008046 } else {
8047 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008048 }
Alex Light705ad492015-09-21 11:36:30 -07008049 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008050 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008051 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008052 return true;
8053}
8054
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008055bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008056 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008057 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008058}
8059
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008060bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008061 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008062 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008063}
8064
Brian Carlstromdbc05252011-09-09 01:59:59 -07008065struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008066 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008067 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008068 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008069 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008070 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008071 // 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 -07008072 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8073 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008074 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008075 if (type1 == Primitive::kPrimNot) {
8076 // Reference always goes first.
8077 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008078 }
Vladimir Markod5777482014-11-12 17:02:02 +00008079 if (type2 == Primitive::kPrimNot) {
8080 // Reference always goes first.
8081 return false;
8082 }
8083 size_t size1 = Primitive::ComponentSize(type1);
8084 size_t size2 = Primitive::ComponentSize(type2);
8085 if (size1 != size2) {
8086 // Larger primitive types go first.
8087 return size1 > size2;
8088 }
8089 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8090 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008091 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008092 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8093 // by name and for equal names by type id index.
8094 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8095 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008096 }
8097};
8098
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008099bool ClassLinker::LinkFields(Thread* self,
8100 Handle<mirror::Class> klass,
8101 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008102 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008103 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008104 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008105 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8106 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008107
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008108 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008109 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008110 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008111 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008112 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008113 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008114 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008115 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008116 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008117 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008118 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008119 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008120
David Sehr709b0702016-10-13 09:12:37 -07008121 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008122
Brian Carlstromdbc05252011-09-09 01:59:59 -07008123 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008124 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008125 //
8126 // The overall sort order order is:
8127 // 1) All object reference fields, sorted alphabetically.
8128 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8129 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8130 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8131 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8132 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8133 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8134 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8135 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8136 //
8137 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8138 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008139 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008140 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008141 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008142 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008143 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008144 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008145 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8146 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008147
Fred Shih381e4ca2014-08-25 17:24:27 -07008148 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008149 size_t current_field = 0;
8150 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008151 FieldGaps gaps;
8152
Brian Carlstromdbc05252011-09-09 01:59:59 -07008153 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008154 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008155 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008156 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008157 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008158 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008159 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008160 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8161 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008162 MemberOffset old_offset = field_offset;
8163 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8164 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8165 }
Roland Levillain14d90572015-07-16 10:52:26 +01008166 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008167 grouped_and_sorted_fields.pop_front();
8168 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008169 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008170 field_offset = MemberOffset(field_offset.Uint32Value() +
8171 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008172 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008173 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8174 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008175 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8176 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8177 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8178 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008179 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8180 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008181 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008182
Elliott Hughesadb460d2011-10-05 17:02:34 -07008183 // 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 -07008184 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008185 // We know there are no non-reference fields in the Reference classes, and we know
8186 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008187 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008188 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008189 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008190 --num_reference_fields;
8191 }
8192
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008193 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008194 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008195 if (is_static) {
8196 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008197 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008198 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008199 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008200 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008201 if (num_reference_fields == 0 || super_class == nullptr) {
8202 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008203 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008204 if (super_class == nullptr ||
8205 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8206 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008207 }
8208 }
8209 if (kIsDebugBuild) {
8210 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8211 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008212 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008213 while (cur_super != nullptr) {
8214 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8215 cur_super = cur_super->GetSuperClass();
8216 }
8217 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008218 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008219 } else {
8220 // Check that there is at least num_reference_fields other than Object.class.
8221 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008222 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008223 }
8224 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008225 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008226 std::string temp;
8227 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8228 size_t previous_size = klass->GetObjectSize();
8229 if (previous_size != 0) {
8230 // Make sure that we didn't originally have an incorrect size.
8231 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008232 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008233 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008234 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008235 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008236
8237 if (kIsDebugBuild) {
8238 // Make sure that the fields array is ordered by name but all reference
8239 // offsets are at the beginning as far as alignment allows.
8240 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008241 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008242 : klass->GetFirstReferenceInstanceFieldOffset();
8243 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8244 num_reference_fields *
8245 sizeof(mirror::HeapReference<mirror::Object>));
8246 MemberOffset current_ref_offset = start_ref_offset;
8247 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008248 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008249 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008250 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8251 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008252 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008253 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008254 // NOTE: The field names can be the same. This is not possible in the Java language
8255 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008256 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008257 }
8258 Primitive::Type type = field->GetTypeAsPrimitiveType();
8259 bool is_primitive = type != Primitive::kPrimNot;
8260 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8261 strcmp("referent", field->GetName()) == 0) {
8262 is_primitive = true; // We lied above, so we have to expect a lie here.
8263 }
8264 MemberOffset offset = field->GetOffsetDuringLinking();
8265 if (is_primitive) {
8266 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8267 // Shuffled before references.
8268 size_t type_size = Primitive::ComponentSize(type);
8269 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8270 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8271 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8272 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8273 }
8274 } else {
8275 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8276 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8277 sizeof(mirror::HeapReference<mirror::Object>));
8278 }
8279 }
8280 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8281 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008282 return true;
8283}
8284
Vladimir Marko76649e82014-11-10 18:32:59 +00008285// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008286void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008287 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008288 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008289 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008290 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008291 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008292 // Compute reference offsets unless our superclass overflowed.
8293 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8294 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008295 if (num_reference_fields != 0u) {
8296 // All of the fields that contain object references are guaranteed be grouped in memory
8297 // starting at an appropriately aligned address after super class object data.
8298 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8299 sizeof(mirror::HeapReference<mirror::Object>));
8300 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008301 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008302 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008303 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008304 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008305 reference_offsets |= (0xffffffffu << start_bit) &
8306 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008307 }
8308 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008309 }
8310 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008311 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008312}
8313
Vladimir Marko18090d12018-06-01 16:53:12 +01008314ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8315 ObjPtr<mirror::DexCache> dex_cache) {
8316 StackHandleScope<1> hs(Thread::Current());
8317 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8318 return DoResolveString(string_idx, h_dex_cache);
8319}
8320
8321ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8322 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008323 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008324 uint32_t utf16_length;
8325 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008326 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008327 if (string != nullptr) {
8328 dex_cache->SetResolvedString(string_idx, string);
8329 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008330 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008331}
8332
Vladimir Marko18090d12018-06-01 16:53:12 +01008333ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8334 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008335 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008336 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008337 uint32_t utf16_length;
8338 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008339 ObjPtr<mirror::String> string =
8340 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008341 if (string != nullptr) {
8342 dex_cache->SetResolvedString(string_idx, string);
8343 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008344 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008345}
8346
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008347ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008348 ObjPtr<mirror::Class> referrer) {
8349 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8350}
8351
8352ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008353 ObjPtr<mirror::DexCache> dex_cache,
8354 ObjPtr<mirror::ClassLoader> class_loader) {
8355 const DexFile& dex_file = *dex_cache->GetDexFile();
8356 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8357 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8358 ObjPtr<mirror::Class> type = nullptr;
8359 if (descriptor[1] == '\0') {
8360 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8361 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008362 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008363 } else {
8364 Thread* const self = Thread::Current();
8365 DCHECK(self != nullptr);
8366 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8367 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008368 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008369 }
8370 if (type != nullptr) {
8371 if (type->IsResolved()) {
8372 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008373 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008374 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008375 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008376 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008377 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008378}
8379
Andreas Gampe4835d212018-11-21 14:55:10 -08008380template <typename T>
8381ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008382 StackHandleScope<2> hs(Thread::Current());
8383 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8384 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8385 return DoResolveType(type_idx, dex_cache, class_loader);
8386}
8387
Andreas Gampe4835d212018-11-21 14:55:10 -08008388// Instantiate the above.
8389template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8390 ArtField* referrer);
8391template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8392 ArtMethod* referrer);
8393template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8394 ObjPtr<mirror::Class> referrer);
8395
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008396ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008397 Handle<mirror::DexCache> dex_cache,
8398 Handle<mirror::ClassLoader> class_loader) {
8399 Thread* self = Thread::Current();
8400 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8401 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8402 if (resolved != nullptr) {
8403 // TODO: we used to throw here if resolved's class loader was not the
8404 // boot class loader. This was to permit different classes with the
8405 // same name to be loaded simultaneously by different loaders
8406 dex_cache->SetResolvedType(type_idx, resolved);
8407 } else {
8408 CHECK(self->IsExceptionPending())
8409 << "Expected pending exception for failed resolution of: " << descriptor;
8410 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8411 StackHandleScope<1> hs(self);
8412 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008413 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008414 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8415 self->ClearException();
8416 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8417 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008418 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008419 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008420 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008421 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008422 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008423}
8424
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008425ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8426 ObjPtr<mirror::DexCache> dex_cache,
8427 ObjPtr<mirror::ClassLoader> class_loader,
8428 uint32_t method_idx) {
8429 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8430 // functions can optimize the search if the dex_cache is the same as the DexCache
8431 // of the class, with fall-back to name and signature search otherwise.
8432 ArtMethod* resolved = nullptr;
8433 if (klass->IsInterface()) {
8434 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8435 } else {
8436 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8437 }
8438 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008439 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008440 hiddenapi::ShouldDenyAccessToMember(resolved,
8441 hiddenapi::AccessContext(class_loader, dex_cache),
8442 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008443 resolved = nullptr;
8444 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008445 if (resolved != nullptr) {
8446 // In case of jmvti, the dex file gets verified before being registered, so first
8447 // check if it's registered before checking class tables.
8448 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008449 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8450 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008451 << "DexFile referrer: " << dex_file.GetLocation()
8452 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8453 // Be a good citizen and update the dex cache to speed subsequent calls.
8454 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008455 // Disable the following invariant check as the verifier breaks it. b/73760543
8456 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8457 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8458 // << "Method: " << resolved->PrettyMethod() << ", "
8459 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8460 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008461 }
8462 return resolved;
8463}
8464
David Brazdil4525e0b2018-04-05 16:57:32 +01008465// Returns true if `method` is either null or hidden.
8466// Does not print any warnings if it is hidden.
8467static bool CheckNoSuchMethod(ArtMethod* method,
8468 ObjPtr<mirror::DexCache> dex_cache,
8469 ObjPtr<mirror::ClassLoader> class_loader)
8470 REQUIRES_SHARED(Locks::mutator_lock_) {
8471 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008472 hiddenapi::ShouldDenyAccessToMember(method,
8473 hiddenapi::AccessContext(class_loader, dex_cache),
8474 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008475}
8476
8477ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8478 ObjPtr<mirror::DexCache> dex_cache,
8479 ObjPtr<mirror::ClassLoader> class_loader,
8480 uint32_t method_idx) {
8481 if (klass->IsInterface()) {
8482 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8483 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8484 } else {
8485 // If there was an interface method with the same signature, we would have
8486 // found it in the "copied" methods. Only DCHECK that the interface method
8487 // really does not exist.
8488 if (kIsDebugBuild) {
8489 ArtMethod* method =
8490 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8491 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8492 }
8493 return nullptr;
8494 }
8495}
8496
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008497template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008498ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008499 Handle<mirror::DexCache> dex_cache,
8500 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008501 ArtMethod* referrer,
8502 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008503 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008504 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008505 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008506 PointerSize pointer_size = image_pointer_size_;
8507 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008508 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008509 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8510 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008511 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8512 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008513 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008514 return resolved;
8515 }
Vladimir Marko89011192017-12-11 13:45:05 +00008516 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008517 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008518 ObjPtr<mirror::Class> klass = nullptr;
8519 if (valid_dex_cache_method) {
8520 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8521 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008522 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008523 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008524 // We normaly should not end up here. However the verifier currently doesn't guarantee
8525 // the invariant of having the klass in the class table. b/73760543
8526 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008527 }
Vladimir Markoba118822017-06-12 15:41:56 +01008528 } else {
8529 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008530 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008531 if (klass == nullptr) {
8532 DCHECK(Thread::Current()->IsExceptionPending());
8533 return nullptr;
8534 }
8535 }
8536
8537 // Check if the invoke type matches the class type.
8538 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008539 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008540 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008541 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008542 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008543 }
Vladimir Markoba118822017-06-12 15:41:56 +01008544
8545 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008546 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008547 }
Vladimir Markoba118822017-06-12 15:41:56 +01008548
8549 // Note: We can check for IllegalAccessError only if we have a referrer.
8550 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8551 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8552 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8553 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8554 resolved,
8555 dex_cache.Get(),
8556 method_idx,
8557 type)) {
8558 DCHECK(Thread::Current()->IsExceptionPending());
8559 return nullptr;
8560 }
8561 }
8562
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008563 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008564 if (LIKELY(resolved != nullptr) &&
8565 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8566 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008567 return resolved;
8568 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008569 // If we had a method, or if we can find one with another lookup type,
8570 // it's an incompatible-class-change error.
8571 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008572 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008573 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008574 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008575 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008576 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008577 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008578 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8579 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008580 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008581 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008582 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008583 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008584 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008585}
8586
Vladimir Marko89011192017-12-11 13:45:05 +00008587ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008588 Handle<mirror::DexCache> dex_cache,
8589 Handle<mirror::ClassLoader> class_loader) {
8590 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008591 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008592 if (resolved != nullptr) {
8593 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008594 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8595 return resolved;
8596 }
8597 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008598 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008599 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008600 if (klass == nullptr) {
8601 Thread::Current()->AssertPendingException();
8602 return nullptr;
8603 }
8604 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008605 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8606 } else {
8607 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008608 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008609 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008610 hiddenapi::ShouldDenyAccessToMember(
8611 resolved,
8612 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8613 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008614 resolved = nullptr;
8615 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008616 return resolved;
8617}
8618
Vladimir Markof44d36c2017-03-14 14:18:46 +00008619ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8620 ObjPtr<mirror::DexCache> dex_cache,
8621 ObjPtr<mirror::ClassLoader> class_loader,
8622 bool is_static) {
8623 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008624 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008625 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8626 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008627 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008628 }
8629 if (klass == nullptr) {
8630 // The class has not been resolved yet, so the field is also unresolved.
8631 return nullptr;
8632 }
8633 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008634
David Brazdil1ab0fa82018-05-04 11:28:03 +01008635 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008636}
8637
Vladimir Markoe11dd502017-12-08 14:09:45 +00008638ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008639 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008640 Handle<mirror::ClassLoader> class_loader,
8641 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008642 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008643 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008644 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008645 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008646 return resolved;
8647 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008648 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008649 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008650 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008651 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008652 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008653 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008654 }
8655
David Brazdil1ab0fa82018-05-04 11:28:03 +01008656 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008657 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008658 const char* name = dex_file.GetFieldName(field_id);
8659 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008660 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008661 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008662 return resolved;
8663}
8664
Vladimir Markoe11dd502017-12-08 14:09:45 +00008665ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008666 Handle<mirror::DexCache> dex_cache,
8667 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008668 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008669 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008670 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008671 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008672 return resolved;
8673 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008674 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008675 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008676 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008677 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008678 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008679 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008680 }
8681
David Brazdil1ab0fa82018-05-04 11:28:03 +01008682 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8683 if (resolved == nullptr) {
8684 const char* name = dex_file.GetFieldName(field_id);
8685 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008686 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008687 }
8688 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008689}
8690
David Brazdil1ab0fa82018-05-04 11:28:03 +01008691ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8692 ObjPtr<mirror::DexCache> dex_cache,
8693 ObjPtr<mirror::ClassLoader> class_loader,
8694 uint32_t field_idx,
8695 bool is_static) {
8696 ArtField* resolved = nullptr;
8697 Thread* self = is_static ? Thread::Current() : nullptr;
8698 const DexFile& dex_file = *dex_cache->GetDexFile();
8699
8700 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8701 : klass->FindInstanceField(dex_cache, field_idx);
8702
8703 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008704 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008705 const char* name = dex_file.GetFieldName(field_id);
8706 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8707 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8708 : klass->FindInstanceField(name, type);
8709 }
8710
8711 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008712 hiddenapi::ShouldDenyAccessToMember(resolved,
8713 hiddenapi::AccessContext(class_loader, dex_cache),
8714 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008715 resolved = nullptr;
8716 }
8717
8718 if (resolved != nullptr) {
8719 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8720 }
8721
8722 return resolved;
8723}
8724
8725ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8726 ObjPtr<mirror::DexCache> dex_cache,
8727 ObjPtr<mirror::ClassLoader> class_loader,
8728 uint32_t field_idx) {
8729 ArtField* resolved = nullptr;
8730 Thread* self = Thread::Current();
8731 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008732 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008733
8734 const char* name = dex_file.GetFieldName(field_id);
8735 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8736 resolved = mirror::Class::FindField(self, klass, name, type);
8737
8738 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008739 hiddenapi::ShouldDenyAccessToMember(resolved,
8740 hiddenapi::AccessContext(class_loader, dex_cache),
8741 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008742 resolved = nullptr;
8743 }
8744
8745 if (resolved != nullptr) {
8746 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8747 }
8748
8749 return resolved;
8750}
8751
Vladimir Markoaf940202017-12-08 15:01:18 +00008752ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8753 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008754 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008755 Handle<mirror::DexCache> dex_cache,
8756 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008757 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008758 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008759
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008760 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008761 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008762 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008763 }
8764
Narayan Kamath25352fc2016-08-03 12:46:58 +01008765 StackHandleScope<4> hs(self);
8766
8767 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008768 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008769 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008770 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008771 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008772 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008773 DCHECK(self->IsExceptionPending());
8774 return nullptr;
8775 }
8776
8777 // Then resolve the argument types.
8778 //
8779 // TODO: Is there a better way to figure out the number of method arguments
8780 // other than by looking at the shorty ?
8781 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8782
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008783 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008784 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8785 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008786 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008787 DCHECK(self->IsExceptionPending());
8788 return nullptr;
8789 }
8790
8791 DexFileParameterIterator it(dex_file, proto_id);
8792 int32_t i = 0;
8793 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8794 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008795 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008796 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008797 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008798 DCHECK(self->IsExceptionPending());
8799 return nullptr;
8800 }
8801
8802 method_params->Set(i++, param_class.Get());
8803 }
8804
8805 DCHECK(!it.HasNext());
8806
8807 Handle<mirror::MethodType> type = hs.NewHandle(
8808 mirror::MethodType::Create(self, return_type, method_params));
8809 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8810
8811 return type.Get();
8812}
8813
Vladimir Markoaf940202017-12-08 15:01:18 +00008814ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008815 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008816 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008817 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008818 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8819 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008820 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008821}
8822
Vladimir Marko5aead702019-03-27 11:00:36 +00008823ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008824 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008825 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008826 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008827 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008828 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8829 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008830 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008831 bool is_static;
8832 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008833 switch (handle_type) {
8834 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008835 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008836 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008837 is_static = true;
8838 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008839 break;
8840 }
8841 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008842 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008843 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008844 is_static = true;
8845 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008846 break;
8847 }
8848 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008849 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008850 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008851 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008852 num_params = 2;
8853 break;
8854 }
8855 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008856 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008857 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008858 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008859 num_params = 1;
8860 break;
8861 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008862 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008863 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008864 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008865 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008866 case DexFile::MethodHandleType::kInvokeInterface:
8867 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008868 }
8869
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008870 ArtField* target_field =
8871 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8872 if (LIKELY(target_field != nullptr)) {
8873 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8874 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8875 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8876 ThrowIllegalAccessErrorField(referring_class, target_field);
8877 return nullptr;
8878 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008879 if (UNLIKELY(is_put && target_field->IsFinal())) {
8880 ThrowIllegalAccessErrorField(referring_class, target_field);
8881 return nullptr;
8882 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008883 } else {
8884 DCHECK(Thread::Current()->IsExceptionPending());
8885 return nullptr;
8886 }
8887
8888 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008889 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008890 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8891 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008892 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008893 DCHECK(self->IsExceptionPending());
8894 return nullptr;
8895 }
8896
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008897 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008898 Handle<mirror::Class> return_type;
8899 switch (handle_type) {
8900 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008901 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008902 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008903 break;
8904 }
8905 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008906 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008907 break;
8908 }
8909 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008910 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008911 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008912 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008913 break;
8914 }
8915 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008916 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008917 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008918 break;
8919 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008920 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008921 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008922 case DexFile::MethodHandleType::kInvokeConstructor:
8923 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008924 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008925 UNREACHABLE();
8926 }
8927
8928 for (int32_t i = 0; i < num_params; ++i) {
8929 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8930 DCHECK(self->IsExceptionPending());
8931 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008932 }
8933 }
8934
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008935 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008936 DCHECK(self->IsExceptionPending());
8937 return nullptr;
8938 }
8939
8940 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008941 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8942 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008943 DCHECK(self->IsExceptionPending());
8944 return nullptr;
8945 }
Orion Hodson631827d2017-04-10 14:53:47 +01008946
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008947 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8948 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8949}
8950
Vladimir Marko5aead702019-03-27 11:00:36 +00008951ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008952 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008953 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008954 ArtMethod* referrer) {
8955 DexFile::MethodHandleType handle_type =
8956 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8957 mirror::MethodHandle::Kind kind;
8958 uint32_t receiver_count = 0;
8959 ArtMethod* target_method = nullptr;
8960 switch (handle_type) {
8961 case DexFile::MethodHandleType::kStaticPut:
8962 case DexFile::MethodHandleType::kStaticGet:
8963 case DexFile::MethodHandleType::kInstancePut:
8964 case DexFile::MethodHandleType::kInstanceGet:
8965 UNREACHABLE();
8966 case DexFile::MethodHandleType::kInvokeStatic: {
8967 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8968 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008969 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8970 method_handle.field_or_method_idx_,
8971 referrer,
8972 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008973 break;
8974 }
8975 case DexFile::MethodHandleType::kInvokeInstance: {
8976 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8977 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008978 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8979 method_handle.field_or_method_idx_,
8980 referrer,
8981 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008982 break;
8983 }
8984 case DexFile::MethodHandleType::kInvokeConstructor: {
8985 // Constructors are currently implemented as a transform. They
8986 // are special cased later in this method.
8987 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8988 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008989 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8990 method_handle.field_or_method_idx_,
8991 referrer,
8992 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008993 break;
8994 }
8995 case DexFile::MethodHandleType::kInvokeDirect: {
8996 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8997 receiver_count = 1;
8998 StackHandleScope<2> hs(self);
8999 // A constant method handle with type kInvokeDirect can refer to
9000 // a method that is private or to a method in a super class. To
9001 // disambiguate the two options, we resolve the method ignoring
9002 // the invocation type to determine if the method is private. We
9003 // then resolve again specifying the intended invocation type to
9004 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009005 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009006 hs.NewHandle(referrer->GetDexCache()),
9007 hs.NewHandle(referrer->GetClassLoader()));
9008 if (UNLIKELY(target_method == nullptr)) {
9009 break;
9010 }
9011
9012 if (target_method->IsPrivate()) {
9013 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009014 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9015 method_handle.field_or_method_idx_,
9016 referrer,
9017 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009018 } else {
9019 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009020 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9021 method_handle.field_or_method_idx_,
9022 referrer,
9023 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009024 if (UNLIKELY(target_method == nullptr)) {
9025 break;
9026 }
9027 // Find the method specified in the parent in referring class
9028 // so invoke-super invokes the method in the parent of the
9029 // referrer.
9030 target_method =
9031 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9032 kRuntimePointerSize);
9033 }
9034 break;
9035 }
9036 case DexFile::MethodHandleType::kInvokeInterface: {
9037 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9038 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009039 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9040 method_handle.field_or_method_idx_,
9041 referrer,
9042 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009043 break;
9044 }
Orion Hodson631827d2017-04-10 14:53:47 +01009045 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009046
9047 if (UNLIKELY(target_method == nullptr)) {
9048 DCHECK(Thread::Current()->IsExceptionPending());
9049 return nullptr;
9050 }
9051
9052 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9053 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9054 uint32_t access_flags = target_method->GetAccessFlags();
9055 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9056 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9057 return nullptr;
9058 }
9059
9060 // Calculate the number of parameters from the method shorty. We add the
9061 // receiver count (0 or 1) and deduct one for the return value.
9062 uint32_t shorty_length;
9063 target_method->GetShorty(&shorty_length);
9064 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9065
Orion Hodsonecd58562018-09-24 11:27:33 +01009066 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009067 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009068 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9069 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9070 if (method_params.Get() == nullptr) {
9071 DCHECK(self->IsExceptionPending());
9072 return nullptr;
9073 }
9074
Orion Hodsonecd58562018-09-24 11:27:33 +01009075 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009076 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009077 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009078 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009079 // Insert receiver. Use the class identified in the method handle rather than the declaring
9080 // class of the resolved method which may be super class or default interface method
9081 // (b/115964401).
9082 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9083 // receiver_class should have been resolved when resolving the target method.
9084 DCHECK(receiver_class != nullptr);
9085 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009086 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009087
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009088 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009089 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009090 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009091 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009092 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009093 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009094 if (nullptr == klass) {
9095 DCHECK(self->IsExceptionPending());
9096 return nullptr;
9097 }
9098 method_params->Set(index++, klass);
9099 it.Next();
9100 }
9101
Orion Hodsonecd58562018-09-24 11:27:33 +01009102 Handle<mirror::Class> return_type =
9103 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009104 if (UNLIKELY(return_type.IsNull())) {
9105 DCHECK(self->IsExceptionPending());
9106 return nullptr;
9107 }
9108
9109 Handle<mirror::MethodType>
9110 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9111 if (UNLIKELY(method_type.IsNull())) {
9112 DCHECK(self->IsExceptionPending());
9113 return nullptr;
9114 }
9115
9116 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9117 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9118 Handle<mirror::MethodHandlesLookup> lookup =
9119 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9120 return lookup->FindConstructor(self, constructor_class, method_type);
9121 }
9122
9123 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9124 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9125}
9126
Vladimir Markoaf940202017-12-08 15:01:18 +00009127ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9128 uint32_t method_handle_idx,
9129 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009130 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009131 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009132 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009133 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9134 case DexFile::MethodHandleType::kStaticPut:
9135 case DexFile::MethodHandleType::kStaticGet:
9136 case DexFile::MethodHandleType::kInstancePut:
9137 case DexFile::MethodHandleType::kInstanceGet:
9138 return ResolveMethodHandleForField(self, method_handle, referrer);
9139 case DexFile::MethodHandleType::kInvokeStatic:
9140 case DexFile::MethodHandleType::kInvokeInstance:
9141 case DexFile::MethodHandleType::kInvokeConstructor:
9142 case DexFile::MethodHandleType::kInvokeDirect:
9143 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009144 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009145 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009146}
9147
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009148bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9149 return (entry_point == GetQuickResolutionStub()) ||
9150 (quick_resolution_trampoline_ == entry_point);
9151}
9152
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009153bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9154 return (entry_point == GetQuickToInterpreterBridge()) ||
9155 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9156}
9157
9158bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9159 return (entry_point == GetQuickGenericJniStub()) ||
9160 (quick_generic_jni_trampoline_ == entry_point);
9161}
9162
David Sehra49e0532017-08-25 08:05:29 -07009163bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9164 return entry_point == GetJniDlsymLookupStub();
9165}
9166
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009167const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9168 return GetQuickGenericJniStub();
9169}
9170
Mathieu Chartiere401d142015-04-22 13:56:20 -07009171void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009172 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009173 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9174 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009175 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009176 }
9177}
9178
Alex Lightdb01a092017-04-03 15:39:55 -07009179void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9180 DCHECK(method->IsObsolete());
9181 // We cannot mess with the entrypoints of native methods because they are used to determine how
9182 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9183 if (!method->IsNative()) {
9184 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9185 }
9186}
9187
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009188void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009189 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009190 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009191 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9192 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009193 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9194 os << "Dumping registered class loaders\n";
9195 size_t class_loader_index = 0;
9196 for (const ClassLoaderData& class_loader : class_loaders_) {
9197 ObjPtr<mirror::ClassLoader> loader =
9198 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9199 if (loader != nullptr) {
9200 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9201 bool saw_one_dex_file = false;
9202 for (const DexCacheData& dex_cache : dex_caches_) {
9203 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9204 if (saw_one_dex_file) {
9205 os << ":";
9206 }
9207 saw_one_dex_file = true;
9208 os << dex_cache.dex_file->GetLocation();
9209 }
9210 }
9211 os << "]";
9212 bool found_parent = false;
9213 if (loader->GetParent() != nullptr) {
9214 size_t parent_index = 0;
9215 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9216 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9217 soa.Self()->DecodeJObject(class_loader2.weak_root));
9218 if (loader2 == loader->GetParent()) {
9219 os << ", parent #" << parent_index;
9220 found_parent = true;
9221 break;
9222 }
9223 parent_index++;
9224 }
9225 if (!found_parent) {
9226 os << ", unregistered parent of type "
9227 << loader->GetParent()->GetClass()->PrettyDescriptor();
9228 }
9229 } else {
9230 os << ", no parent";
9231 }
9232 os << "\n";
9233 }
9234 }
9235 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009236}
9237
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009238class CountClassesVisitor : public ClassLoaderVisitor {
9239 public:
9240 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9241
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009242 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009243 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009244 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009245 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009246 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9247 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009248 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009249 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009250
9251 size_t num_zygote_classes;
9252 size_t num_non_zygote_classes;
9253};
9254
9255size_t ClassLinker::NumZygoteClasses() const {
9256 CountClassesVisitor visitor;
9257 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009258 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009259}
9260
9261size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009262 CountClassesVisitor visitor;
9263 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009264 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009265}
9266
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009267size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009268 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009269 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009270 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009271}
9272
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009273pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009274 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009275}
9276
9277pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009278 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009279}
9280
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009281void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009282 DCHECK(!init_done_);
9283
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009284 DCHECK(klass != nullptr);
9285 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009286
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009287 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009288 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009289 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9290 int32_t index = static_cast<int32_t>(class_root);
9291 DCHECK(class_roots->Get(index) == nullptr);
9292 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009293}
9294
Roland Levillain0e840272018-08-23 19:55:30 +01009295void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9296 ObjPtr<mirror::Class> java_lang_Class,
9297 ClassRoot primitive_array_class_root,
9298 ClassRoot primitive_class_root,
9299 const char* descriptor) {
9300 StackHandleScope<1> hs(self);
9301 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9302 AllocPrimitiveArrayClass(self, java_lang_Class)));
9303 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9304 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9305 CheckSystemClass(self, primitive_array_class, descriptor);
9306}
9307
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009308ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9309 Thread* self,
9310 const std::vector<const DexFile*>& dex_files,
9311 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009312 Handle<mirror::ClassLoader> parent_loader,
9313 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009314
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009315 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009316
Mathieu Chartierc7853442015-03-27 14:35:38 -07009317 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009318 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009319
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009320 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009321 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009322 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009323 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009324 mirror::ObjectArray<mirror::Object>::Alloc(self,
9325 dex_elements_class.Get(),
9326 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009327 Handle<mirror::Class> h_dex_element_class =
9328 hs.NewHandle(dex_elements_class->GetComponentType());
9329
Mathieu Chartierc7853442015-03-27 14:35:38 -07009330 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009331 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009332 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009333
Andreas Gampe08883de2016-11-08 13:20:52 -08009334 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009335 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009336
Andreas Gampe08883de2016-11-08 13:20:52 -08009337 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009338 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009339
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009340 // Fill the elements array.
9341 int32_t index = 0;
9342 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009343 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009344
Calin Juravle7865ac72017-06-28 11:03:12 -07009345 // CreateWellKnownClassLoader is only used by gtests and compiler.
9346 // 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 -07009347 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9348 self,
9349 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009350 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009351 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009352
Mathieu Chartier3738e982017-05-12 16:07:28 -07009353 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9354 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009355 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009356 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009357 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009358 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009359
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009360 Handle<mirror::String> h_file_name = hs2.NewHandle(
9361 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009362 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009363 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9364
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009365 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009366 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009367 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009368
9369 h_dex_elements->Set(index, h_element.Get());
9370 index++;
9371 }
9372 DCHECK_EQ(index, h_dex_elements->GetLength());
9373
9374 // Create DexPathList.
9375 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009376 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009377 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009378 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009379 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009380 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9381 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9382 // elements.
9383 {
9384 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9385 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9386 DCHECK(native_lib_dirs != nullptr);
9387 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9388 DCHECK(list_class != nullptr);
9389 {
9390 StackHandleScope<1> h_list_scope(self);
9391 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9392 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9393 DCHECK(list_init);
9394 list_class = h_list_class.Get();
9395 }
9396 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9397 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9398 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9399 // normally never null), as long as one does not try to add elements, this will still
9400 // work.
9401 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9402 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009403
Calin Juravle7865ac72017-06-28 11:03:12 -07009404 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009405 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9406 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009407 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009408 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009409 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009410 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009411 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009412 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009413
9414 // Make a pretend boot-classpath.
9415 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009416 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009417 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009418 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009419 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009420 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009421 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009422 if (parent_loader.Get() == nullptr) {
9423 ScopedObjectAccessUnchecked soa(self);
9424 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9425 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9426 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9427 } else {
9428 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9429 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009430
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009431 ArtField* shared_libraries_field =
9432 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9433 DCHECK(shared_libraries_field != nullptr);
9434 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9435
9436 return h_class_loader.Get();
9437}
9438
9439jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9440 const std::vector<const DexFile*>& dex_files,
9441 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009442 jobject parent_loader,
9443 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009444 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9445 WellKnownClasses::dalvik_system_PathClassLoader) ||
9446 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009447 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9448 self->GetJniEnv()->IsSameObject(loader_class,
9449 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009450
9451 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9452 // We could move the jobject to the callers, but all call-sites do this...
9453 ScopedObjectAccessUnchecked soa(self);
9454
9455 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009456 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009457
9458 Handle<mirror::Class> h_loader_class =
9459 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009460 Handle<mirror::ClassLoader> h_parent =
9461 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9462 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9463 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009464
9465 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9466 self,
9467 dex_files,
9468 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009469 h_parent,
9470 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009471
9472 // Make it a global ref and return.
9473 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009474 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009475 return soa.Env()->NewGlobalRef(local_ref.get());
9476}
9477
Calin Juravle7865ac72017-06-28 11:03:12 -07009478jobject ClassLinker::CreatePathClassLoader(Thread* self,
9479 const std::vector<const DexFile*>& dex_files) {
9480 return CreateWellKnownClassLoader(self,
9481 dex_files,
9482 WellKnownClasses::dalvik_system_PathClassLoader,
9483 nullptr);
9484}
9485
Andreas Gampe8ac75952015-06-02 21:01:45 -07009486void ClassLinker::DropFindArrayClassCache() {
9487 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9488 find_array_class_cache_next_victim_ = 0;
9489}
9490
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009491void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009492 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009493 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009494 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009495 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9496 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009497 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009498 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009499 }
9500 }
9501}
9502
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009503void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9504 for (const ClassLoaderData& data : class_loaders_) {
9505 LinearAlloc* alloc = data.allocator;
9506 if (alloc != nullptr && !visitor->Visit(alloc)) {
9507 break;
9508 }
9509 }
9510}
9511
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009512void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9513 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009514 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009515 Thread* const self = Thread::Current();
9516 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009517 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009518 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009519 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009520 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9521 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009522 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009523 }
9524}
9525
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009526void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009527 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009528 std::vector<ClassLoaderData> to_delete;
9529 // Do the delete outside the lock to avoid lock violation in jit code cache.
9530 {
9531 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9532 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9533 const ClassLoaderData& data = *it;
9534 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009535 ObjPtr<mirror::ClassLoader> class_loader =
9536 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009537 if (class_loader != nullptr) {
9538 ++it;
9539 } else {
9540 VLOG(class_linker) << "Freeing class loader";
9541 to_delete.push_back(data);
9542 it = class_loaders_.erase(it);
9543 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009544 }
9545 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009546 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009547 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009548 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009549 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009550}
9551
Vladimir Marko21300532017-01-24 18:06:55 +00009552class GetResolvedClassesVisitor : public ClassVisitor {
9553 public:
9554 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9555 : result_(result),
9556 ignore_boot_classes_(ignore_boot_classes),
9557 last_resolved_classes_(result->end()),
9558 last_dex_file_(nullptr),
9559 vlog_is_on_(VLOG_IS_ON(class_linker)),
9560 extra_stats_(),
9561 last_extra_stats_(extra_stats_.end()) { }
9562
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009563 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009564 if (!klass->IsProxyClass() &&
9565 !klass->IsArrayClass() &&
9566 klass->IsResolved() &&
9567 !klass->IsErroneousResolved() &&
9568 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9569 const DexFile& dex_file = klass->GetDexFile();
9570 if (&dex_file != last_dex_file_) {
9571 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009572 DexCacheResolvedClasses resolved_classes(
9573 dex_file.GetLocation(),
9574 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9575 dex_file.GetLocationChecksum(),
9576 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009577 last_resolved_classes_ = result_->find(resolved_classes);
9578 if (last_resolved_classes_ == result_->end()) {
9579 last_resolved_classes_ = result_->insert(resolved_classes).first;
9580 }
9581 }
9582 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9583 if (UNLIKELY(vlog_is_on_) && added) {
9584 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9585 if (last_extra_stats_ == extra_stats_.end() ||
9586 last_extra_stats_->first != resolved_classes) {
9587 last_extra_stats_ = extra_stats_.find(resolved_classes);
9588 if (last_extra_stats_ == extra_stats_.end()) {
9589 last_extra_stats_ =
9590 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9591 }
9592 }
9593 }
9594 }
9595 return true;
9596 }
9597
9598 void PrintStatistics() const {
9599 if (vlog_is_on_) {
9600 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9601 auto it = extra_stats_.find(std::addressof(resolved_classes));
9602 DCHECK(it != extra_stats_.end());
9603 const ExtraStats& extra_stats = it->second;
9604 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9605 << " has " << resolved_classes.GetClasses().size() << " / "
9606 << extra_stats.number_of_class_defs_ << " resolved classes";
9607 }
9608 }
9609 }
9610
9611 private:
9612 struct ExtraStats {
9613 explicit ExtraStats(uint32_t number_of_class_defs)
9614 : number_of_class_defs_(number_of_class_defs) {}
9615 uint32_t number_of_class_defs_;
9616 };
9617
9618 std::set<DexCacheResolvedClasses>* result_;
9619 bool ignore_boot_classes_;
9620 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9621 const DexFile* last_dex_file_;
9622
9623 // Statistics.
9624 bool vlog_is_on_;
9625 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9626 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9627};
9628
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009629std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009630 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009631 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009632 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009633 std::set<DexCacheResolvedClasses> ret;
9634 VLOG(class_linker) << "Collecting resolved classes";
9635 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009636 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9637 VisitClasses(&visitor);
9638 if (VLOG_IS_ON(class_linker)) {
9639 visitor.PrintStatistics();
9640 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009641 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009642 return ret;
9643}
9644
Mathieu Chartier65975772016-08-05 10:46:36 -07009645class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9646 public:
9647 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9648 : method_(method),
9649 pointer_size_(pointer_size) {}
9650
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009651 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009652 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9653 holder_ = klass;
9654 }
9655 // Return false to stop searching if holder_ is not null.
9656 return holder_ == nullptr;
9657 }
9658
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009659 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009660 const ArtMethod* const method_;
9661 const PointerSize pointer_size_;
9662};
9663
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009664ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009665 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9666 CHECK(method->IsCopied());
9667 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9668 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009669 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009670}
9671
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009672ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9673 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009674 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009675 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009676 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009677}
9678
Roland Levillain0e840272018-08-23 19:55:30 +01009679// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009680template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009681 uint32_t method_idx,
9682 Handle<mirror::DexCache> dex_cache,
9683 Handle<mirror::ClassLoader> class_loader,
9684 ArtMethod* referrer,
9685 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009686template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009687 uint32_t method_idx,
9688 Handle<mirror::DexCache> dex_cache,
9689 Handle<mirror::ClassLoader> class_loader,
9690 ArtMethod* referrer,
9691 InvokeType type);
9692
Roland Levillain0e840272018-08-23 19:55:30 +01009693// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009694template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009695 Thread* self,
9696 ObjPtr<mirror::Class> java_lang_Class,
9697 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009698template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009699 Thread* self,
9700 ObjPtr<mirror::Class> java_lang_Class,
9701 uint32_t class_size);
9702
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009703} // namespace art