blob: c8db3105c4f8a0bf562856805c6c65606baa1b81 [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 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001080 // Assert that if absolute boot classpath locations were provided, they were
1081 // assigned to the loaded dex files.
1082 if (kIsDebugBuild && IsAbsoluteLocation(boot_class_path_locations[i])) {
1083 for (const auto& dex_file : dex_files) {
1084 DCHECK_EQ(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1085 boot_class_path_locations[i]);
1086 }
1087 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001088 // Append opened dex files at the end.
1089 boot_dex_files_.insert(boot_dex_files_.end(),
1090 std::make_move_iterator(dex_files.begin()),
1091 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001092 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001093 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1094 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1095 }
Ian Rogers98379392014-02-24 16:53:16 -08001096 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001097
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001098 VLOG(startup) << __FUNCTION__ << " exiting";
1099 return true;
1100}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001101
Vladimir Marko4433c432018-12-04 14:57:47 +00001102void ClassLinker::AddExtraBootDexFiles(
1103 Thread* self,
1104 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1105 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1106 AppendToBootClassPath(self, *dex_file);
1107 boot_dex_files_.push_back(std::move(dex_file));
1108 }
1109}
1110
Jeff Hao5872d7c2016-04-27 11:07:41 -07001111bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001112 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001113 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001114 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1115 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116}
1117
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001118static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1119 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001120 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001121 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001122 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001123 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001124 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 DCHECK(dex_file_field != nullptr);
1126 DCHECK(dex_file_name_field != nullptr);
1127 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001128 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001129 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001130 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001131 // Null dex file means it was probably a jar with no dex files, return a null string.
1132 *out_name = nullptr;
1133 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001134 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001135 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001136 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001137 *out_name = name_object->AsString();
1138 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001139 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001140 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001141}
1142
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001143static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1144 ObjPtr<mirror::ClassLoader> class_loader,
1145 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1146 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001147 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001148 StackHandleScope<1> hs(soa.Self());
1149 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001150 // Get element names. Sets error to true on failure.
1151 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1152 REQUIRES_SHARED(Locks::mutator_lock_) {
1153 if (element == nullptr) {
1154 *error_msg = "Null dex element";
1155 *error = true; // Null element is a critical error.
1156 return false; // Had an error, stop the visit.
1157 }
1158 ObjPtr<mirror::String> name;
1159 if (!GetDexPathListElementName(element, &name)) {
1160 *error_msg = "Invalid dex path list element";
1161 *error = true; // Invalid element, make it a critical error.
1162 return false; // Stop the visit.
1163 }
1164 if (name != nullptr) {
1165 dex_files->push_front(name);
1166 }
1167 return true; // Continue with the next Element.
1168 };
1169 bool error = VisitClassLoaderDexElements(soa,
1170 handle,
1171 add_element_names,
1172 /*defaultReturn=*/ false);
1173 return !error;
1174}
1175
1176static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1177 ObjPtr<mirror::ClassLoader> image_class_loader,
1178 ObjPtr<mirror::ClassLoader> class_loader,
1179 std::string* error_msg)
1180 REQUIRES_SHARED(Locks::mutator_lock_) {
1181 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1182 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1183 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001184 return false;
1185 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001186 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1187 *error_msg = "Hierarchies don't match";
1188 return false;
1189 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1190 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1191 image_class_loader->PrettyTypeOf().c_str(),
1192 class_loader->PrettyTypeOf().c_str());
1193 return false;
1194 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1195 class_loader->GetClass()) {
1196 *error_msg = StringPrintf("Unknown class loader type %s",
1197 class_loader->PrettyTypeOf().c_str());
1198 // Unsupported class loader.
1199 return false;
1200 }
1201 return true;
1202}
1203
1204static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1205 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1206 std::string* error_msg)
1207 REQUIRES_SHARED(Locks::mutator_lock_) {
1208 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1209 std::equal(image_dex_files.begin(),
1210 image_dex_files.end(),
1211 loader_dex_files.begin(),
1212 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1213 REQUIRES_SHARED(Locks::mutator_lock_) {
1214 return lhs->Equals(rhs);
1215 });
1216 if (!equal) {
1217 VLOG(image) << "Image dex files " << image_dex_files.size();
1218 for (ObjPtr<mirror::String> name : image_dex_files) {
1219 VLOG(image) << name->ToModifiedUtf8();
1220 }
1221 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1222 for (ObjPtr<mirror::String> name : loader_dex_files) {
1223 VLOG(image) << name->ToModifiedUtf8();
1224 }
1225 *error_msg = "Mismatch in dex files";
1226 }
1227 return equal;
1228}
1229
1230static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1231 ObjPtr<mirror::ClassLoader> image_class_loader,
1232 ObjPtr<mirror::ClassLoader> class_loader,
1233 bool check_dex_file_names,
1234 std::string* error_msg)
1235 REQUIRES_SHARED(Locks::mutator_lock_) {
1236 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1237 return false;
1238 }
1239
1240 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1241 // No need to check further.
1242 return true;
1243 }
1244
1245 if (check_dex_file_names) {
1246 std::list<ObjPtr<mirror::String>> image_dex_files;
1247 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001248 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001249 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001250
1251 std::list<ObjPtr<mirror::String>> loader_dex_files;
1252 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1253 return false;
1254 }
1255
1256 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1257 return false;
1258 }
1259 }
1260
1261 ArtField* field =
1262 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1263 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1264 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1265 if (shared_libraries_image_loader == nullptr) {
1266 if (shared_libraries_loader != nullptr) {
1267 *error_msg = "Mismatch in shared libraries";
1268 return false;
1269 }
1270 } else if (shared_libraries_loader == nullptr) {
1271 *error_msg = "Mismatch in shared libraries";
1272 return false;
1273 } else {
1274 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1275 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1276 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1277 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1278 if (array1->GetLength() != array2->GetLength()) {
1279 *error_msg = "Mismatch in number of shared libraries";
1280 return false;
1281 }
1282
1283 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1284 // Do a full comparison of the class loaders, including comparing their dex files.
1285 if (!CompareClassLoaders(soa,
1286 array1->Get(i),
1287 array2->Get(i),
1288 /*check_dex_file_names=*/ true,
1289 error_msg)) {
1290 return false;
1291 }
1292 }
1293 }
1294
1295 // Do a full comparison of the class loaders, including comparing their dex files.
1296 if (!CompareClassLoaders(soa,
1297 image_class_loader->GetParent(),
1298 class_loader->GetParent(),
1299 /*check_dex_file_names=*/ true,
1300 error_msg)) {
1301 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001302 }
1303 return true;
1304}
1305
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001306class CHAOnDeleteUpdateClassVisitor {
1307 public:
1308 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1309 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1310 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1311 self_(Thread::Current()) {}
1312
1313 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1314 // This class is going to be unloaded. Tell CHA about it.
1315 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1316 return true;
1317 }
1318 private:
1319 const LinearAlloc* allocator_;
1320 const ClassHierarchyAnalysis* cha_;
1321 const PointerSize pointer_size_;
1322 const Thread* self_;
1323};
1324
Chris Wailes0c61be42018-09-26 17:27:34 -07001325/*
1326 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001327 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001328 */
1329class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001330 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001331 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001332 space_(space),
1333 intern_table_(*Runtime::Current()->GetInternTable()) {}
1334
Chris Wailes0c61be42018-09-26 17:27:34 -07001335 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001336 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001337 if (referred_obj != nullptr &&
1338 space_.HasAddress(referred_obj.Ptr()) &&
1339 referred_obj->IsString()) {
1340 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001341
1342 if (kIsDebugBuild) {
1343 // Saved to temporary variables to aid in debugging.
1344 ObjPtr<mirror::String> strong_lookup_result =
1345 intern_table_.LookupStrong(Thread::Current(), referred_str);
1346 ObjPtr<mirror::String> weak_lookup_result =
1347 intern_table_.LookupWeak(Thread::Current(), referred_str);
1348
1349 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1350 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001351 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001352 }
1353
Chris Wailes0c61be42018-09-26 17:27:34 -07001354 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001355 mirror::CompressedReference<mirror::Object>* root) const
1356 REQUIRES_SHARED(Locks::mutator_lock_) {
1357 if (!root->IsNull()) {
1358 VisitRoot(root);
1359 }
1360 }
1361
Chris Wailes0c61be42018-09-26 17:27:34 -07001362 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001363 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001364 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001365 }
1366
1367 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001368 void operator()(ObjPtr<mirror::Object> obj,
1369 MemberOffset offset,
1370 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001371 REQUIRES_SHARED(Locks::mutator_lock_) {
1372 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1373 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1374 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1375 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001376 ObjPtr<mirror::Object> referred_obj =
1377 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1378
1379 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001380 }
1381 }
1382
1383 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1384 ObjPtr<mirror::Reference> ref) const
1385 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001386 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001387 }
1388
Chris Wailes0c61be42018-09-26 17:27:34 -07001389 const gc::space::ImageSpace& space_;
1390 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001391};
1392
Chris Wailes0c61be42018-09-26 17:27:34 -07001393/*
1394 * This function verifies that string references in the AppImage have been
1395 * properly interned. To be considered properly interned a reference must
1396 * point to the same version of the string that the intern table does.
1397 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001398void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001399 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1400 const ImageHeader& image_header = space.GetImageHeader();
1401 const uint8_t* target_base = space.GetMemMap()->Begin();
1402 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001403
1404 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1405 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001406
1407 VerifyStringInterningVisitor visitor(space);
1408 bitmap->VisitMarkedRange(objects_begin,
1409 objects_end,
1410 [&space, &visitor](mirror::Object* obj)
1411 REQUIRES_SHARED(Locks::mutator_lock_) {
1412 if (space.HasAddress(obj)) {
1413 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001414 obj->VisitReferences</* kVisitNativeRoots= */ true,
1415 kVerifyNone,
1416 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001417 } else {
1418 // Don't visit native roots for non-dex-cache as they can't contain
1419 // native references to strings. This is verified during compilation
1420 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001421 obj->VisitReferences</* kVisitNativeRoots= */ false,
1422 kVerifyNone,
1423 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001424 }
1425 }
1426 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001427}
1428
Andreas Gampe2af99022017-04-25 08:32:59 -07001429// new_class_set is the set of classes that were read from the class table section in the image.
1430// If there was no class table section, it is null.
1431// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001432class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001433 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001434 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001435 ClassLinker* class_linker,
1436 gc::space::ImageSpace* space,
1437 Handle<mirror::ClassLoader> class_loader,
1438 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001439 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001440 REQUIRES(!Locks::dex_lock_)
1441 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001442
Chris Wailesfbeef462018-10-19 14:16:35 -07001443 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001444 REQUIRES_SHARED(Locks::mutator_lock_);
1445
1446 static void UpdateInternStrings(
1447 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001448 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001449 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1450 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001451};
1452
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001453void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001454 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001455 gc::space::ImageSpace* space,
1456 Handle<mirror::ClassLoader> class_loader,
1457 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001458 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001459 REQUIRES(!Locks::dex_lock_)
1460 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001461 ScopedTrace app_image_timing("AppImage:Updating");
1462
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001463 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001464 Runtime* const runtime = Runtime::Current();
1465 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001466 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001467 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001468 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001469 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001470 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001471 const size_t num_dex_caches = dex_caches->GetLength();
1472 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001473 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001474 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001475 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001476 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001477 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1478 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001479 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001480
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001481 if (!load_app_image_startup_cache) {
1482 dex_cache->ClearPreResolvedStrings();
1483 }
1484
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001485 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001486 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001487 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001488 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001489 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001490 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001491 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001492
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001493 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001494 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001495 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001496 DCHECK(it != new_class_set->end());
1497 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001498 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001499
Vladimir Marko1a1de672016-10-13 12:53:15 +01001500 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001501 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001502 DCHECK(it2 != new_class_set->end());
1503 DCHECK_EQ(it2->Read(), super_class);
1504 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001505
Vladimir Marko1a1de672016-10-13 12:53:15 +01001506 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1507 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001508 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1509 if (!class_linker->IsQuickResolutionStub(code) &&
1510 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001511 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001512 !m.IsNative()) {
1513 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001514 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001515 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001516
Vladimir Marko1a1de672016-10-13 12:53:15 +01001517 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1518 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001519 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1520 if (!class_linker->IsQuickResolutionStub(code) &&
1521 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001522 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001523 !m.IsNative()) {
1524 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001525 }
1526 }
1527 }
1528 }
1529 }
1530 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001531 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001532
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001533 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001534 HandleAppImageStrings(space);
1535
1536 if (kIsDebugBuild) {
1537 VerifyStringInterning(*space);
1538 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001539 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001540
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001541 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001542 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001543 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001544 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1545 header.VisitPackedArtMethods([&](ArtMethod& method)
1546 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1547 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1548 if (klass != nullptr) {
1549 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1550 }
1551 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001552 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001553}
1554
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001555void AppImageLoadingHelper::UpdateInternStrings(
1556 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001557 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001558 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1559 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001560 const ImageSection& sro_section =
1561 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1562 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001563 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001564
1565 VLOG(image)
1566 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1567 << num_string_offsets;
1568
Chris Wailesfbeef462018-10-19 14:16:35 -07001569 const auto* sro_base =
1570 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001571
1572 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001573 uint32_t base_offset = sro_base[offset_index].first;
1574
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001575 if (HasDexCacheStringNativeRefTag(base_offset)) {
1576 base_offset = ClearDexCacheNativeRefTags(base_offset);
1577 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001578
1579 ObjPtr<mirror::DexCache> dex_cache =
1580 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1581 uint32_t string_index = sro_base[offset_index].second;
1582
1583 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1584 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001585 DCHECK(referred_string != nullptr);
1586
Chris Wailesfbeef462018-10-19 14:16:35 -07001587 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001588 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001589 // This doesn't use SetResolvedString to maintain consistency with how
1590 // we load the string. The index from the source string must be
1591 // re-used due to the circular nature of the cache. Because we are not
1592 // using a helper function we need to mark the GC card manually.
1593 WriteBarrier::ForEveryFieldWrite(dex_cache);
1594 dex_cache->GetStrings()[string_index].store(
1595 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001596 } else if (!use_preresolved_strings) {
1597 dex_cache->GetStrings()[string_index].store(
1598 mirror::StringDexCachePair(intern_table->InternStrong(referred_string), source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001599 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001600 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001601 if (use_preresolved_strings) {
1602 base_offset = ClearDexCacheNativeRefTags(base_offset);
1603 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001604
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001605 ObjPtr<mirror::DexCache> dex_cache =
1606 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1607 uint32_t string_index = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001608
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001609 ObjPtr<mirror::String> referred_string =
1610 dex_cache->GetPreResolvedStrings()[string_index].Read();
1611 DCHECK(referred_string != nullptr);
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001612
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001613 auto it = intern_remap.find(referred_string.Ptr());
1614 if (it != intern_remap.end()) {
1615 // Because we are not using a helper function we need to mark the GC card manually.
1616 WriteBarrier::ForEveryFieldWrite(dex_cache);
1617 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1618 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001619 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001620 } else {
1621 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001622 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001623 DCHECK_ALIGNED(raw_member_offset, 2);
1624
1625 ObjPtr<mirror::Object> obj_ptr =
1626 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1627 MemberOffset member_offset(raw_member_offset);
1628 ObjPtr<mirror::String> referred_string =
1629 obj_ptr->GetFieldObject<mirror::String,
1630 kVerifyNone,
1631 kWithoutReadBarrier,
1632 /* kIsVolatile= */ false>(member_offset);
1633 DCHECK(referred_string != nullptr);
1634
1635 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001636 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001637 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1638 /* kCheckTransaction= */ false,
1639 kVerifyNone,
1640 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001641 } else if (!use_preresolved_strings) {
1642 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1643 /* kCheckTransaction= */ false,
1644 kVerifyNone,
1645 /* kIsVolatile= */ false>(
1646 member_offset,
1647 intern_table->InternStrong(referred_string));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001648 }
1649 }
1650 }
1651}
1652
Chris Wailesfbeef462018-10-19 14:16:35 -07001653void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001654 // Iterate over the string reference offsets stored in the image and intern
1655 // the strings they point to.
1656 ScopedTrace timing("AppImage:InternString");
1657
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001658 Runtime* const runtime = Runtime::Current();
1659 InternTable* const intern_table = runtime->GetInternTable();
1660
1661 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001662
1663 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1664 // for faster lookup.
1665 // TODO: Optimize with a bitmap or bloom filter
1666 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001667 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001668 REQUIRES_SHARED(Locks::mutator_lock_)
1669 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001670 const size_t non_boot_image_strings = intern_table->CountInterns(
1671 /*visit_boot_images=*/false,
1672 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001673 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001674 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1675 // Visit the smaller of the two sets to compute the intersection.
1676 if (interns.size() < non_boot_image_strings) {
1677 for (auto it = interns.begin(); it != interns.end(); ) {
1678 ObjPtr<mirror::String> string = it->Read();
1679 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1680 if (existing == nullptr) {
1681 existing = intern_table->LookupStrongLocked(string);
1682 }
1683 if (existing != nullptr) {
1684 intern_remap.Put(string.Ptr(), existing.Ptr());
1685 it = interns.erase(it);
1686 } else {
1687 ++it;
1688 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001689 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001690 } else {
1691 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1692 REQUIRES_SHARED(Locks::mutator_lock_)
1693 REQUIRES(Locks::intern_table_lock_) {
1694 auto it = interns.find(root);
1695 if (it != interns.end()) {
1696 ObjPtr<mirror::String> existing = root.Read();
1697 intern_remap.Put(it->Read(), existing.Ptr());
1698 it = interns.erase(it);
1699 }
1700 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1701 }
1702 // Sanity check to ensure correctness.
1703 if (kIsDebugBuild) {
1704 for (GcRoot<mirror::String>& root : interns) {
1705 ObjPtr<mirror::String> string = root.Read();
1706 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1707 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001708 }
1709 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001710 };
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001711
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001712 bool update_intern_strings;
1713 if (load_startup_cache) {
Mathieu Chartiere23b3882019-02-14 07:35:43 -08001714 VLOG(image) << "AppImage:load_startup_cache";
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001715 // Only add the intern table if we are using the startup cache. Otherwise,
1716 // UpdateInternStrings adds the strings to the intern table.
1717 intern_table->AddImageStringsToTable(space, func);
1718 update_intern_strings = kIsDebugBuild || !intern_remap.empty();
1719 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
1720 } else {
1721 update_intern_strings = true;
1722 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001723
1724 // For debug builds, always run the code below to get coverage.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001725 if (update_intern_strings) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001726 // Slow path case is when there are conflicting intern strings to fix up.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001727 UpdateInternStrings(space, /*use_preresolved_strings=*/ load_startup_cache, intern_remap);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001728 }
1729}
1730
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001731static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1732 const char* location,
1733 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001734 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001735 DCHECK(error_msg != nullptr);
1736 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001737 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001738 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001739 return std::unique_ptr<const DexFile>();
1740 }
1741 std::string inner_error_msg;
1742 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1743 if (dex_file == nullptr) {
1744 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1745 location,
1746 oat_file->GetLocation().c_str(),
1747 inner_error_msg.c_str());
1748 return std::unique_ptr<const DexFile>();
1749 }
1750
1751 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1752 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1753 location,
1754 dex_file->GetLocationChecksum(),
1755 oat_dex_file->GetDexFileLocationChecksum());
1756 return std::unique_ptr<const DexFile>();
1757 }
1758 return dex_file;
1759}
1760
1761bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1762 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1763 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001764 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001765 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001766 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001767 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001768 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001769 dex_caches_object->AsObjectArray<mirror::DexCache>();
1770 const OatFile* oat_file = space->GetOatFile();
Vladimir Marko4617d582019-03-28 13:48:31 +00001771 for (int32_t i = 0, length = dex_caches->GetLength(); i != length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001772 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001773 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1774 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1775 dex_file_location.c_str(),
1776 error_msg);
1777 if (dex_file == nullptr) {
1778 return false;
1779 }
1780 dex_cache->SetDexFile(dex_file.get());
1781 out_dex_files->push_back(std::move(dex_file));
1782 }
1783 return true;
1784}
1785
Andreas Gampe0793bec2016-12-01 11:37:33 -08001786// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1787// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001788class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001789 public:
1790 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1791 REQUIRES_SHARED(Locks::mutator_lock_) {
1792 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001793 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1794 DCHECK(obj != nullptr);
1795 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1796 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1797 if (obj->IsClass()) {
1798 auto klass = obj->AsClass();
1799 for (ArtField& field : klass->GetIFields()) {
1800 CHECK_EQ(field.GetDeclaringClass(), klass);
1801 }
1802 for (ArtField& field : klass->GetSFields()) {
1803 CHECK_EQ(field.GetDeclaringClass(), klass);
1804 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001805 const PointerSize pointer_size = isc.pointer_size_;
1806 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001807 isc.SanityCheckArtMethod(&m, klass);
1808 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001809 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001810 if (vtable != nullptr) {
1811 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1812 }
1813 if (klass->ShouldHaveImt()) {
1814 ImTable* imt = klass->GetImt(pointer_size);
1815 for (size_t i = 0; i < ImTable::kSize; ++i) {
1816 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1817 }
1818 }
1819 if (klass->ShouldHaveEmbeddedVTable()) {
1820 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1821 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1822 }
1823 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001824 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001825 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1826 if (iftable->GetMethodArrayCount(i) > 0) {
1827 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1828 }
1829 }
1830 }
1831 };
1832 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001833 }
1834
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001835 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1836 ClassLinker* class_linker,
1837 mirror::MethodDexCacheType* arr,
1838 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001839 REQUIRES_SHARED(Locks::mutator_lock_) {
1840 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001841 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001842 }
1843
Andreas Gampe0793bec2016-12-01 11:37:33 -08001844 private:
1845 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1846 : spaces_(heap->GetBootImageSpaces()),
1847 pointer_size_(class_linker->GetImagePointerSize()) {
1848 space_begin_.reserve(spaces_.size());
1849 method_sections_.reserve(spaces_.size());
1850 runtime_method_sections_.reserve(spaces_.size());
1851 for (gc::space::ImageSpace* space : spaces_) {
1852 space_begin_.push_back(space->Begin());
1853 auto& header = space->GetImageHeader();
1854 method_sections_.push_back(&header.GetMethodsSection());
1855 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1856 }
1857 }
1858
1859 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1860 REQUIRES_SHARED(Locks::mutator_lock_) {
1861 if (m->IsRuntimeMethod()) {
1862 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1863 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1864 } else if (m->IsCopied()) {
1865 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1866 } else if (expected_class != nullptr) {
1867 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1868 }
1869 if (!spaces_.empty()) {
1870 bool contains = false;
1871 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1872 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1873 contains = method_sections_[i]->Contains(offset) ||
1874 runtime_method_sections_[i]->Contains(offset);
1875 }
1876 CHECK(contains) << m << " not found";
1877 }
1878 }
1879
1880 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1881 ObjPtr<mirror::Class> expected_class)
1882 REQUIRES_SHARED(Locks::mutator_lock_) {
1883 CHECK(arr != nullptr);
1884 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1885 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1886 // expected_class == null means we are a dex cache.
1887 if (expected_class != nullptr) {
1888 CHECK(method != nullptr);
1889 }
1890 if (method != nullptr) {
1891 SanityCheckArtMethod(method, expected_class);
1892 }
1893 }
1894 }
1895
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001896 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001897 REQUIRES_SHARED(Locks::mutator_lock_) {
1898 CHECK_EQ(arr != nullptr, size != 0u);
1899 if (arr != nullptr) {
1900 bool contains = false;
1901 for (auto space : spaces_) {
1902 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001903 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001904 contains = true;
1905 break;
1906 }
1907 }
1908 CHECK(contains);
1909 }
1910 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001911 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1912 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001913 // expected_class == null means we are a dex cache.
1914 if (method != nullptr) {
1915 SanityCheckArtMethod(method, nullptr);
1916 }
1917 }
1918 }
1919
1920 const std::vector<gc::space::ImageSpace*>& spaces_;
1921 const PointerSize pointer_size_;
1922
1923 // Cached sections from the spaces.
1924 std::vector<const uint8_t*> space_begin_;
1925 std::vector<const ImageSection*> method_sections_;
1926 std::vector<const ImageSection*> runtime_method_sections_;
1927};
1928
Andreas Gampebe7af222017-07-25 09:57:28 -07001929static void VerifyAppImage(const ImageHeader& header,
1930 const Handle<mirror::ClassLoader>& class_loader,
1931 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1932 ClassTable* class_table, gc::space::ImageSpace* space)
1933 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001934 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1935 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1936 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1937 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1938 << mirror::Class::PrettyClass(klass);
1939 }
1940 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001941 {
1942 // Verify that all direct interfaces of classes in the class table are also resolved.
1943 std::vector<ObjPtr<mirror::Class>> classes;
1944 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1945 REQUIRES_SHARED(Locks::mutator_lock_) {
1946 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1947 classes.push_back(klass);
1948 }
1949 return true;
1950 };
1951 class_table->Visit(verify_direct_interfaces_in_table);
1952 Thread* self = Thread::Current();
1953 for (ObjPtr<mirror::Class> klass : classes) {
1954 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1955 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1956 << klass->PrettyDescriptor() << " iface #" << i;
1957 }
1958 }
1959 }
1960 // Check that all non-primitive classes in dex caches are also in the class table.
1961 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1962 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1963 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1964 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1965 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1966 if (klass != nullptr && !klass->IsPrimitive()) {
1967 CHECK(class_table->Contains(klass))
1968 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1969 }
1970 }
1971 }
1972}
1973
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001974bool ClassLinker::AddImageSpace(
1975 gc::space::ImageSpace* space,
1976 Handle<mirror::ClassLoader> class_loader,
1977 jobjectArray dex_elements,
1978 const char* dex_location,
1979 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1980 std::string* error_msg) {
1981 DCHECK(out_dex_files != nullptr);
1982 DCHECK(error_msg != nullptr);
1983 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001984 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001985 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001986 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001987 DCHECK(dex_caches_object != nullptr);
1988 Runtime* const runtime = Runtime::Current();
1989 gc::Heap* const heap = runtime->GetHeap();
1990 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001991 // Check that the image is what we are expecting.
1992 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1993 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1994 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1995 image_pointer_size_);
1996 return false;
1997 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001998 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1999 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2000 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2001 expected_image_roots,
2002 header.GetImageRoots()->GetLength());
2003 return false;
2004 }
2005 StackHandleScope<3> hs(self);
2006 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2007 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2008 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2009 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002010 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002011 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2012 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002013 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002014 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 *error_msg = StringPrintf("Expected %d class roots but got %d",
2016 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002017 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002018 return false;
2019 }
2020 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002021 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2022 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2023 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002024 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2025 return false;
2026 }
2027 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002028 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002029 if (oat_file->GetOatHeader().GetDexFileCount() !=
2030 static_cast<uint32_t>(dex_caches->GetLength())) {
2031 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2032 "image";
2033 return false;
2034 }
2035
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002036 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002037 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
David Brazdil3e8aae02019-03-26 18:48:02 +00002038 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
2039 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002040 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2041 dex_file_location.c_str(),
2042 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002043 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002044 return false;
2045 }
2046
2047 if (app_image) {
2048 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2049 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002050 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002051 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002052 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002053 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002054 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002055 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002056 }
2057 }
2058 } else {
2059 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002060 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2061 this,
2062 dex_cache->GetResolvedMethods(),
2063 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002064 }
2065 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002066 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002067 }
2068 out_dex_files->push_back(std::move(dex_file));
2069 }
2070
2071 if (app_image) {
2072 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002073 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002074 // Check that the class loader resolves the same way as the ones in the image.
2075 // Image class loader [A][B][C][image dex files]
2076 // Class loader = [???][dex_elements][image dex files]
2077 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002078 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002079 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2080 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2081 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002082 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2083 *error_msg = "Unexpected BootClassLoader in app image";
2084 return false;
2085 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002086 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2087 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2088 // special case the comparison of dex files of the two class loaders, but then do full
2089 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002090 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002091 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002092 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2093 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2094 if (element != nullptr) {
2095 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002096 ObjPtr<mirror::String> name;
2097 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2098 loader_dex_file_names.push_back(name);
2099 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002100 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002101 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002102 std::string temp_error_msg;
2103 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2104 bool success = GetDexFileNames(
2105 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2106 if (success) {
2107 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2108 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2109 static_cast<size_t>(dex_caches->GetLength()));
2110 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2111 image_dex_file_names.resize(image_count);
2112 success = success && CompareDexFiles(image_dex_file_names,
2113 loader_dex_file_names,
2114 &temp_error_msg);
2115 success = success && CompareClassLoaders(soa,
2116 image_class_loader.Get(),
2117 class_loader.Get(),
2118 /*check_dex_file_names=*/ false,
2119 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002120 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002121 if (!success) {
2122 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2123 temp_error_msg.c_str());
2124 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002125 }
2126 }
2127
2128 if (kSanityCheckObjects) {
2129 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002130 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002131 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2132 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2133 if (field != nullptr) {
2134 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2135 }
2136 }
2137 }
2138 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002139 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002140 }
2141 }
2142
2143 // Set entry point to interpreter if in InterpretOnly mode.
2144 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002145 // Set image methods' entry point to interpreter.
2146 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2147 if (!method.IsRuntimeMethod()) {
2148 DCHECK(method.GetDeclaringClass() != nullptr);
2149 if (!method.IsNative() && !method.IsResolutionMethod()) {
2150 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2151 image_pointer_size_);
2152 }
2153 }
2154 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002155 }
2156
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002157 ClassTable* class_table = nullptr;
2158 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002159 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002160 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002161 }
2162 // If we have a class table section, read it and use it for verification in
2163 // UpdateAppImageClassLoadersAndDexCaches.
2164 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002165 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002166 const bool added_class_table = class_table_section.Size() > 0u;
2167 if (added_class_table) {
2168 const uint64_t start_time2 = NanoTime();
2169 size_t read_count = 0;
2170 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2171 /*make copy*/false,
2172 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002173 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002174 }
2175 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002176 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002177
2178 {
2179 ScopedTrace trace("AppImage:UpdateClassLoaders");
2180 // Update class loader and resolved strings. If added_class_table is false, the resolved
2181 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002182 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002183 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002184 // Note: We probably don't need the read barrier unless we copy the app image objects into
2185 // the region space.
2186 ObjPtr<mirror::Class> klass(root.Read());
2187 // Do not update class loader for boot image classes where the app image
2188 // class loader is only the initiating loader but not the defining loader.
2189 // Avoid read barrier since we are comparing against null.
2190 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2191 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2192 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002193 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002194 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002195
Vladimir Marko305c38b2018-02-14 11:50:07 +00002196 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002197 // Every class in the app image has initially SubtypeCheckInfo in the
2198 // Uninitialized state.
2199 //
2200 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2201 // after class initialization is complete. The app image ClassStatus as-is
2202 // are almost all ClassStatus::Initialized, and being in the
2203 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2204 //
2205 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2206 //
2207 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002208 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002209 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2210 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002211 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002212 }
2213 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002214 }
2215 if (!oat_file->GetBssGcRoots().empty()) {
2216 // Insert oat file to class table for visiting .bss GC roots.
2217 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002218 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002219
Mathieu Chartier69731002016-03-02 16:08:31 -08002220 if (added_class_table) {
2221 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2222 class_table->AddClassSet(std::move(temp_set));
2223 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002224
Mathieu Chartier69731002016-03-02 16:08:31 -08002225 if (kIsDebugBuild && app_image) {
2226 // This verification needs to happen after the classes have been added to the class loader.
2227 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002228 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002229 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002230 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002231
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002232 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002233 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002234}
2235
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002236bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002237 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2238 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002239}
2240
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002241void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002242 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2243 // enabling tracing requires the mutator lock, there are no race conditions here.
2244 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002245 Thread* const self = Thread::Current();
2246 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002247 if (kUseReadBarrier) {
2248 // We do not track new roots for CC.
2249 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2250 kVisitRootFlagClearRootLog |
2251 kVisitRootFlagStartLoggingNewRoots |
2252 kVisitRootFlagStopLoggingNewRoots));
2253 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002254 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002255 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2256 // There is 3 GC cases to handle:
2257 // Non moving concurrent:
2258 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002259 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002260 //
2261 // Moving non-concurrent:
2262 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2263 // To prevent missing roots, this case needs to ensure that there is no
2264 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2265 // class which is in the class table.
2266 //
2267 // Moving concurrent:
2268 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2269 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002270 //
2271 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2272 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2273 // these objects.
2274 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002275 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002276 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002277 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002278 for (const ClassLoaderData& data : class_loaders_) {
2279 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2280 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2281 }
2282 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002283 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002284 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002285 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002286 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002287 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002288 // Concurrent moving GC marked new roots through the to-space invariant.
2289 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002290 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002291 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2292 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2293 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2294 if (old_ref != nullptr) {
2295 DCHECK(old_ref->IsClass());
2296 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2297 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2298 // Concurrent moving GC marked new roots through the to-space invariant.
2299 CHECK_EQ(new_ref, old_ref);
2300 }
2301 }
2302 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002303 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002304 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002305 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002306 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002307 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002308 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002309 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002310 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002311 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002312 }
2313 // We deliberately ignore the class roots in the image since we
2314 // handle image roots by using the MS/CMS rescanning of dirty cards.
2315}
2316
Brian Carlstroma663ea52011-08-19 23:33:41 -07002317// Keep in sync with InitCallback. Anything we visit, we need to
2318// reinit references to when reinitializing a ClassLinker from a
2319// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002320void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002321 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002322 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002323 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2324 // unloading if we are marking roots.
2325 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002326}
2327
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002328class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2329 public:
2330 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2331 : visitor_(visitor),
2332 done_(false) {}
2333
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002334 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002335 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002336 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002337 if (!done_ && class_table != nullptr) {
2338 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2339 if (!class_table->Visit(visitor)) {
2340 // If the visitor ClassTable returns false it means that we don't need to continue.
2341 done_ = true;
2342 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002343 }
2344 }
2345
2346 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002347 // Class visitor that limits the class visits from a ClassTable to the classes with
2348 // the provided defining class loader. This filter is used to avoid multiple visits
2349 // of the same class which can be recorded for multiple initiating class loaders.
2350 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2351 public:
2352 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2353 ClassVisitor* visitor)
2354 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2355
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002356 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002357 if (klass->GetClassLoader() != defining_class_loader_) {
2358 return true;
2359 }
2360 return (*visitor_)(klass);
2361 }
2362
Vladimir Marko0984e482019-03-27 16:41:41 +00002363 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002364 ClassVisitor* const visitor_;
2365 };
2366
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002367 ClassVisitor* const visitor_;
2368 // If done is true then we don't need to do any more visiting.
2369 bool done_;
2370};
2371
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002372void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002373 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002374 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2375 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002376 }
2377}
2378
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002379void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002380 Thread* const self = Thread::Current();
2381 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2382 // Not safe to have thread suspension when we are holding a lock.
2383 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002384 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002385 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002386 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002387 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002388 }
2389}
2390
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002391class GetClassesInToVector : public ClassVisitor {
2392 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002393 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002394 classes_.push_back(klass);
2395 return true;
2396 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002397 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002398};
2399
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002400class GetClassInToObjectArray : public ClassVisitor {
2401 public:
2402 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2403 : arr_(arr), index_(0) {}
2404
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002405 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002406 ++index_;
2407 if (index_ <= arr_->GetLength()) {
2408 arr_->Set(index_ - 1, klass);
2409 return true;
2410 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002411 return false;
2412 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002413
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002414 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002415 return index_ <= arr_->GetLength();
2416 }
2417
2418 private:
2419 mirror::ObjectArray<mirror::Class>* const arr_;
2420 int32_t index_;
2421};
2422
2423void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002424 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2425 // is avoiding duplicates.
2426 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002427 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002428 GetClassesInToVector accumulator;
2429 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002430 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002431 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002432 return;
2433 }
2434 }
2435 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002436 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002437 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002438 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002439 // We size the array assuming classes won't be added to the class table during the visit.
2440 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002441 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002442 size_t class_table_size;
2443 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002444 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002445 // Add 100 in case new classes get loaded when we are filling in the object array.
2446 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002447 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002448 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002449 classes.Assign(
2450 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002451 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002452 GetClassInToObjectArray accumulator(classes.Get());
2453 VisitClasses(&accumulator);
2454 if (accumulator.Succeeded()) {
2455 break;
2456 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002457 }
2458 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2459 // If the class table shrank during creation of the clases array we expect null elements. If
2460 // the class table grew then the loop repeats. If classes are created after the loop has
2461 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002462 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002463 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002464 return;
2465 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002466 }
2467 }
2468}
2469
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002470ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002471 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002472 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002473 // CHA unloading analysis is not needed. No negative consequences are expected because
2474 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002475 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002476 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002477 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002478}
2479
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002480void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002481 Runtime* const runtime = Runtime::Current();
2482 JavaVMExt* const vm = runtime->GetJavaVM();
2483 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002484 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002485 if (runtime->GetJit() != nullptr) {
2486 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2487 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002488 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002489 code_cache->RemoveMethodsIn(self, *data.allocator);
2490 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002491 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002492 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002493 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002494 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002495 // Cleanup references to single implementation ArtMethods that will be deleted.
2496 if (cleanup_cha) {
2497 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2498 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2499 }
2500
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002501 delete data.allocator;
2502 delete data.class_table;
2503}
2504
Vladimir Markobcf17522018-06-01 13:14:32 +01002505ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2506 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002507 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002508 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2509 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002510}
2511
Vladimir Markobcf17522018-06-01 13:14:32 +01002512ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2513 Thread* self,
2514 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002515 StackHandleScope<1> hs(self);
2516 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002517 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002518 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002519 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002520 self->AssertPendingOOMException();
2521 return nullptr;
2522 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002523 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002524 if (location == nullptr) {
2525 self->AssertPendingOOMException();
2526 return nullptr;
2527 }
2528 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002529 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002530}
2531
Vladimir Markobcf17522018-06-01 13:14:32 +01002532ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2533 const DexFile& dex_file,
2534 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002535 ObjPtr<mirror::String> location = nullptr;
2536 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002537 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002538 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002539 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002540 mirror::DexCache::InitializeDexCache(self,
2541 dex_cache,
2542 location,
2543 &dex_file,
2544 linear_alloc,
2545 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002546 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002547 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002548}
2549
Roland Levillain0e840272018-08-23 19:55:30 +01002550template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002551ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2552 ObjPtr<mirror::Class> java_lang_Class,
2553 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002554 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002555 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002556 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002557 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002558 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2559 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002560 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002561 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002562 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002563 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002564 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002565}
2566
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002567ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002568 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002569}
2570
Roland Levillain0e840272018-08-23 19:55:30 +01002571ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2572 ObjPtr<mirror::Class> java_lang_Class) {
2573 // We make this class non-movable for the unlikely case where it were to be
2574 // moved by a sticky-bit (minor) collection when using the Generational
2575 // Concurrent Copying (CC) collector, potentially creating a stale reference
2576 // in the `klass_` field of one of its instances allocated in the Large-Object
2577 // Space (LOS) -- see the comment about the dirty card scanning logic in
2578 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002579 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002580 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2581}
2582
Vladimir Markobcf17522018-06-01 13:14:32 +01002583ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002584 Thread* self,
2585 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002586 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002587 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002588}
2589
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002590ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2591 const char* descriptor,
2592 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002593 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002594 if (kIsDebugBuild) {
2595 StackHandleScope<1> hs(self);
2596 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2597 Thread::PoisonObjectPointersIfDebug();
2598 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002599
2600 // For temporary classes we must wait for them to be retired.
2601 if (init_done_ && klass->IsTemp()) {
2602 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002603 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002604 ThrowEarlierClassFailure(klass);
2605 return nullptr;
2606 }
2607 StackHandleScope<1> hs(self);
2608 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2609 ObjectLock<mirror::Class> lock(self, h_class);
2610 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002611 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002612 lock.WaitIgnoringInterrupts();
2613 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002614 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002615 ThrowEarlierClassFailure(h_class.Get());
2616 return nullptr;
2617 }
2618 CHECK(h_class->IsRetired());
2619 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002620 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002621 }
2622
Brian Carlstromaded5f72011-10-07 17:15:04 -07002623 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002624 size_t index = 0;
2625 // Maximum number of yield iterations until we start sleeping.
2626 static const size_t kNumYieldIterations = 1000;
2627 // How long each sleep is in us.
2628 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002629 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002630 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002631 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002632 {
2633 ObjectTryLock<mirror::Class> lock(self, h_class);
2634 // Can not use a monitor wait here since it may block when returning and deadlock if another
2635 // thread has locked klass.
2636 if (lock.Acquired()) {
2637 // Check for circular dependencies between classes, the lock is required for SetStatus.
2638 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2639 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002640 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002641 return nullptr;
2642 }
2643 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002645 {
2646 // Handle wrapper deals with klass moving.
2647 ScopedThreadSuspension sts(self, kSuspended);
2648 if (index < kNumYieldIterations) {
2649 sched_yield();
2650 } else {
2651 usleep(kSleepDurationUS);
2652 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002653 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002654 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002655 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002656
Vladimir Marko72ab6842017-01-20 19:32:50 +00002657 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002658 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002659 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002660 }
2661 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002662 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002663 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002664 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002665}
2666
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002667using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002668
2669// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002670ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002671 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002672 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002673 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002674 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002675 return ClassPathEntry(dex_file, dex_class_def);
2676 }
2677 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002678 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002679}
2680
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002681bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2682 Thread* self,
2683 const char* descriptor,
2684 size_t hash,
2685 Handle<mirror::ClassLoader> class_loader,
2686 /*out*/ ObjPtr<mirror::Class>* result) {
2687 ArtField* field =
2688 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2689 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2690 if (raw_shared_libraries == nullptr) {
2691 return true;
2692 }
2693
2694 StackHandleScope<2> hs(self);
2695 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2696 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2697 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2698 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2699 temp_loader.Assign(shared_libraries->Get(i));
2700 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2701 return false; // One of the shared libraries is not supported.
2702 }
2703 if (*result != nullptr) {
2704 return true; // Found the class up the chain.
2705 }
2706 }
2707 return true;
2708}
2709
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002710bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2711 Thread* self,
2712 const char* descriptor,
2713 size_t hash,
2714 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002715 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002716 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002717 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002718 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002719 return true;
2720 }
2721
David Brazdil05909d82018-12-06 16:25:16 +00002722 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002723 // For regular path or dex class loader the search order is:
2724 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002725 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002726 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002727
Calin Juravlecdd49122017-07-05 20:09:53 -07002728 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2729 StackHandleScope<1> hs(self);
2730 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2731 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2732 return false; // One of the parents is not supported.
2733 }
2734 if (*result != nullptr) {
2735 return true; // Found the class up the chain.
2736 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002737
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002738 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2739 return false; // One of the shared library loader is not supported.
2740 }
2741 if (*result != nullptr) {
2742 return true; // Found the class in a shared library.
2743 }
2744
Calin Juravlecdd49122017-07-05 20:09:53 -07002745 // Search the current class loader classpath.
2746 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002747 return true;
2748 }
2749
Calin Juravlecdd49122017-07-05 20:09:53 -07002750 if (IsDelegateLastClassLoader(soa, class_loader)) {
2751 // For delegate last, the search order is:
2752 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002753 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002754 // - class loader dex files
2755 // - parent
2756 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2757 if (*result != nullptr) {
2758 return true; // The class is part of the boot class path.
2759 }
2760
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002761 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2762 return false; // One of the shared library loader is not supported.
2763 }
2764 if (*result != nullptr) {
2765 return true; // Found the class in a shared library.
2766 }
2767
Calin Juravlecdd49122017-07-05 20:09:53 -07002768 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2769 if (*result != nullptr) {
2770 return true; // Found the class in the current class loader
2771 }
2772
2773 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2774 StackHandleScope<1> hs(self);
2775 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2776 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2777 }
2778
2779 // Unsupported class loader.
2780 *result = nullptr;
2781 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002782}
2783
2784// Finds the class in the boot class loader.
2785// If the class is found the method returns the resolved class. Otherwise it returns null.
2786ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2787 const char* descriptor,
2788 size_t hash) {
2789 ObjPtr<mirror::Class> result = nullptr;
2790 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2791 if (pair.second != nullptr) {
2792 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2793 if (klass != nullptr) {
2794 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002795 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002796 result = DefineClass(self,
2797 descriptor,
2798 hash,
2799 ScopedNullHandle<mirror::ClassLoader>(),
2800 *pair.first,
2801 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002802 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002803 if (result == nullptr) {
2804 CHECK(self->IsExceptionPending()) << descriptor;
2805 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002806 }
2807 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002808 return result;
2809}
Andreas Gampef865ea92015-04-13 22:14:19 -07002810
Calin Juravle415dc3d2017-06-28 11:03:12 -07002811ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2812 ScopedObjectAccessAlreadyRunnable& soa,
2813 const char* descriptor,
2814 size_t hash,
2815 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002816 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2817 IsInMemoryDexClassLoader(soa, class_loader) ||
2818 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002819 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002820
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002821 ObjPtr<mirror::Class> ret;
2822 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002823 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002824 if (dex_class_def != nullptr) {
2825 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2826 descriptor,
2827 hash,
2828 class_loader,
2829 *cp_dex_file,
2830 *dex_class_def);
2831 if (klass == nullptr) {
2832 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2833 soa.Self()->ClearException();
2834 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002835 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002836 ret = klass;
2837 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002838 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002839 return true; // Continue with the next DexFile.
2840 };
2841
2842 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2843 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002844}
2845
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002846ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2847 const char* descriptor,
2848 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002849 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002850 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002851 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002852 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002853 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002854 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2855 // for primitive classes that aren't backed by dex files.
2856 return FindPrimitiveClass(descriptor[0]);
2857 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002858 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002859 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002860 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002861 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002862 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002863 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002864 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002865 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002866 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002867 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002868 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002869 return DefineClass(self,
2870 descriptor,
2871 hash,
2872 ScopedNullHandle<mirror::ClassLoader>(),
2873 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002874 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002875 } else {
2876 // The boot class loader is searched ahead of the application class loader, failures are
2877 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2878 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002879 ObjPtr<mirror::Throwable> pre_allocated =
2880 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002881 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002882 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002883 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002884 }
2885 ObjPtr<mirror::Class> result_ptr;
2886 bool descriptor_equals;
2887 if (descriptor[0] == '[') {
2888 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2889 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2890 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2891 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002892 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002893 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002894 bool known_hierarchy =
2895 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2896 if (result_ptr != nullptr) {
2897 // The chain was understood and we found the class. We still need to add the class to
2898 // the class table to protect from racy programs that can try and redefine the path list
2899 // which would change the Class<?> returned for subsequent evaluation of const-class.
2900 DCHECK(known_hierarchy);
2901 DCHECK(result_ptr->DescriptorEquals(descriptor));
2902 descriptor_equals = true;
2903 } else {
2904 // Either the chain wasn't understood or the class wasn't found.
2905 //
2906 // If the chain was understood but we did not find the class, let the Java-side
2907 // rediscover all this and throw the exception with the right stack trace. Note that
2908 // the Java-side could still succeed for racy programs if another thread is actively
2909 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002910
Alex Light185a4612018-10-04 15:54:25 -07002911 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002912 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002913 // Oops, we can't call into java so we can't run actual class-loader code.
2914 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002915 ObjPtr<mirror::Throwable> pre_allocated =
2916 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2917 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002918 return nullptr;
2919 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002920
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002921 // Inlined DescriptorToDot(descriptor) with extra validation.
2922 //
2923 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2924 // the DescriptorEquals() check below and give a confusing error message. For example,
2925 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2926 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2927 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2928 size_t descriptor_length = strlen(descriptor);
2929 if (UNLIKELY(descriptor[0] != 'L') ||
2930 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2931 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2932 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2933 return nullptr;
2934 }
2935 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2936 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2937
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002938 ScopedLocalRef<jobject> class_loader_object(
2939 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002940 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2941 {
2942 ScopedThreadStateChange tsc(self, kNative);
2943 ScopedLocalRef<jobject> class_name_object(
2944 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2945 if (class_name_object.get() == nullptr) {
2946 DCHECK(self->IsExceptionPending()); // OOME.
2947 return nullptr;
2948 }
2949 CHECK(class_loader_object.get() != nullptr);
2950 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2951 WellKnownClasses::java_lang_ClassLoader_loadClass,
2952 class_name_object.get()));
2953 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002954 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002955 // broken loader - throw NPE to be compatible with Dalvik
2956 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2957 class_name_string.c_str()).c_str());
2958 return nullptr;
2959 }
2960 result_ptr = soa.Decode<mirror::Class>(result.get());
2961 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002962 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002963 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002964 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002965
2966 if (self->IsExceptionPending()) {
2967 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2968 // However, to comply with the RI behavior, first check if another thread succeeded.
2969 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2970 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2971 self->ClearException();
2972 return EnsureResolved(self, descriptor, result_ptr);
2973 }
2974 return nullptr;
2975 }
2976
2977 // Try to insert the class to the class table, checking for mismatch.
2978 ObjPtr<mirror::Class> old;
2979 {
2980 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2981 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2982 old = class_table->Lookup(descriptor, hash);
2983 if (old == nullptr) {
2984 old = result_ptr; // For the comparison below, after releasing the lock.
2985 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002986 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002987 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002988 } // else throw below, after releasing the lock.
2989 }
2990 }
2991 if (UNLIKELY(old != result_ptr)) {
2992 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2993 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002994 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002995 const char* loader_class_name =
2996 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2997 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2998 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2999 << DescriptorToDot(descriptor) << "\").";
3000 return EnsureResolved(self, descriptor, old);
3001 }
3002 if (UNLIKELY(!descriptor_equals)) {
3003 std::string result_storage;
3004 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3005 std::string loader_storage;
3006 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3007 ThrowNoClassDefFoundError(
3008 "Initiating class loader of type %s returned class %s instead of %s.",
3009 DescriptorToDot(loader_class_name).c_str(),
3010 DescriptorToDot(result_name).c_str(),
3011 DescriptorToDot(descriptor).c_str());
3012 return nullptr;
3013 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003014 // Success.
3015 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003016}
3017
Vladimir Markob9c29f62019-03-20 14:22:51 +00003018static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3019 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003020 return
3021 // Reserved conscrypt packages (includes sub-packages under these paths).
3022 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3023 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3024 // Reserved updatable-media package (includes sub-packages under this path).
3025 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003026}
3027
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003028ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3029 const char* descriptor,
3030 size_t hash,
3031 Handle<mirror::ClassLoader> class_loader,
3032 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003033 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003034 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003035 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003036
Brian Carlstromaded5f72011-10-07 17:15:04 -07003037 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003038 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003039 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003040 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003041 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003042 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003043 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003044 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003045 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003046 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003047 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003048 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003049 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003050 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003051 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003052 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053 }
3054
Vladimir Markob9c29f62019-03-20 14:22:51 +00003055 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3056 // some runtime modules. Prevent definition of classes in app class loader that could clash
3057 // with these modules as these classes could be resolved differently during execution.
3058 if (class_loader != nullptr &&
3059 Runtime::Current()->IsAotCompiler() &&
3060 IsReservedBootClassPathDescriptor(descriptor)) {
3061 ObjPtr<mirror::Throwable> pre_allocated =
3062 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3063 self->SetException(pre_allocated);
3064 return nullptr;
3065 }
3066
Alex Lighte9f61032018-09-24 16:04:51 -07003067 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3068 // code to be executed. We put it up here so we can avoid all the allocations associated with
3069 // creating the class. This can happen with (eg) jit threads.
3070 if (!self->CanLoadClasses()) {
3071 // Make sure we don't try to load anything, potentially causing an infinite loop.
3072 ObjPtr<mirror::Throwable> pre_allocated =
3073 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3074 self->SetException(pre_allocated);
3075 return nullptr;
3076 }
3077
Andreas Gampefa4333d2017-02-14 11:10:34 -08003078 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003079 // Allocate a class with the status of not ready.
3080 // Interface object should get the right size here. Regular class will
3081 // figure out the right size later and be replaced with one of the right
3082 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003083 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003084 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003085 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003086 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003087 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003088 }
Alex Lightb0f11922017-01-23 14:25:17 -08003089 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3090 // nothing.
3091 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003092 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003093 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3094 // will only be called once.
3095 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3096 klass,
3097 class_loader,
3098 dex_file,
3099 dex_class_def,
3100 &new_dex_file,
3101 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003102 // Check to see if an exception happened during runtime callbacks. Return if so.
3103 if (self->IsExceptionPending()) {
3104 return nullptr;
3105 }
Alex Lightb0f11922017-01-23 14:25:17 -08003106 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003107 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003108 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003109 return nullptr;
3110 }
3111 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003112 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003113
Jeff Hao848f70a2014-01-15 13:49:50 -08003114 // Mark the string class by setting its access flag.
3115 if (UNLIKELY(!init_done_)) {
3116 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3117 klass->SetStringClass();
3118 }
3119 }
3120
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003121 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003122 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003123 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003124 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003125
Mathieu Chartier590fee92013-09-13 13:46:47 -07003126 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003127 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003128 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003129 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3130 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003131 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003132 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003133
Mathieu Chartierc7853442015-03-27 14:35:38 -07003134 // Load the fields and other things after we are inserted in the table. This is so that we don't
3135 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3136 // other reason is that the field roots are only visited from the class table. So we need to be
3137 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003138 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003139 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003140 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003141 // An exception occured during load, set status to erroneous while holding klass' lock in case
3142 // notification is necessary.
3143 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003144 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003145 }
3146 return nullptr;
3147 }
3148
Brian Carlstromaded5f72011-10-07 17:15:04 -07003149 // Finish loading (if necessary) by finding parents
3150 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003151 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003152 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003153 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003154 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003155 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003156 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003157 }
3158 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003159
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003160 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003161 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003162 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003163
Brian Carlstromaded5f72011-10-07 17:15:04 -07003164 // Link the class (if necessary)
3165 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003166 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003167 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003168
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003169 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003170 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003171 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003172 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003173 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003174 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003175 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003176 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003177 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003178 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003179 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003180
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003181 // Instrumentation may have updated entrypoints for all methods of all
3182 // classes. However it could not update methods of this class while we
3183 // were loading it. Now the class is resolved, we can update entrypoints
3184 // as required by instrumentation.
3185 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3186 // We must be in the kRunnable state to prevent instrumentation from
3187 // suspending all threads to update entrypoints while we are doing it
3188 // for this class.
3189 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003190 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003191 }
3192
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003193 /*
3194 * We send CLASS_PREPARE events to the debugger from here. The
3195 * definition of "preparation" is creating the static fields for a
3196 * class and initializing them to the standard default values, but not
3197 * executing any code (that comes later, during "initialization").
3198 *
3199 * We did the static preparation in LinkClass.
3200 *
3201 * The class has been prepared and resolved but possibly not yet verified
3202 * at this point.
3203 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003204 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003205
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003206 // Notify native debugger of the new class and its layout.
3207 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3208
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003209 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003210}
3211
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003212uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003213 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003214 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003215 size_t num_8 = 0;
3216 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003217 size_t num_32 = 0;
3218 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003219 ClassAccessor accessor(dex_file, dex_class_def);
3220 // We allow duplicate definitions of the same field in a class_data_item
3221 // but ignore the repeated indexes here, b/21868015.
3222 uint32_t last_field_idx = dex::kDexNoIndex;
3223 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3224 uint32_t field_idx = field.GetIndex();
3225 // Ordering enforced by DexFileVerifier.
3226 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3227 if (UNLIKELY(field_idx == last_field_idx)) {
3228 continue;
3229 }
3230 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003231 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003232 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3233 char c = descriptor[0];
3234 switch (c) {
3235 case 'L':
3236 case '[':
3237 num_ref++;
3238 break;
3239 case 'J':
3240 case 'D':
3241 num_64++;
3242 break;
3243 case 'I':
3244 case 'F':
3245 num_32++;
3246 break;
3247 case 'S':
3248 case 'C':
3249 num_16++;
3250 break;
3251 case 'B':
3252 case 'Z':
3253 num_8++;
3254 break;
3255 default:
3256 LOG(FATAL) << "Unknown descriptor: " << c;
3257 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003258 }
3259 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003260 return mirror::Class::ComputeClassSize(false,
3261 0,
3262 num_8,
3263 num_16,
3264 num_32,
3265 num_64,
3266 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003267 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003268}
3269
Alex Lightfc49fec2018-01-16 22:28:36 +00003270// Special case to get oat code without overwriting a trampoline.
3271const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003272 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003273 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003274 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003275 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003276 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3277 if (code != nullptr) {
3278 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003279 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003280 if (method->IsNative()) {
3281 // No code and native? Use generic trampoline.
3282 return GetQuickGenericJniStub();
3283 }
3284 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003285}
3286
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003287bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003288 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003289 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3290 return false;
3291 }
3292
Elliott Hughes956af0f2014-12-11 14:34:28 -08003293 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003294 return true;
3295 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003296
3297 Runtime* runtime = Runtime::Current();
3298 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3299 if (instr->InterpretOnly()) {
3300 return true;
3301 }
3302
3303 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3304 // Doing this check avoids doing compiled/interpreter transitions.
3305 return true;
3306 }
3307
Alex Light3dacdd62019-03-12 15:45:47 +00003308 if (Thread::Current()->IsForceInterpreter() ||
3309 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003310 // Force the use of interpreter when it is required by the debugger.
3311 return true;
3312 }
3313
Alex Light8f34aba2017-10-09 13:46:32 -07003314 if (Thread::Current()->IsAsyncExceptionPending()) {
3315 // Force use of interpreter to handle async-exceptions
3316 return true;
3317 }
3318
Alex Light2d441b12018-06-08 15:33:21 -07003319 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3320 const void* instr_target = instr->GetCodeForInvoke(method);
3321 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3322 return ShouldUseInterpreterEntrypoint(method, instr_target);
3323 }
3324
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003325 if (runtime->IsJavaDebuggable()) {
3326 // For simplicity, we ignore precompiled code and go to the interpreter
3327 // assuming we don't already have jitted code.
3328 // We could look at the oat file where `quick_code` is being defined,
3329 // and check whether it's been compiled debuggable, but we decided to
3330 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003331 jit::Jit* jit = Runtime::Current()->GetJit();
3332 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3333 }
3334
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003335 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003336 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003337 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003338 // since we want to JIT it (at first use) with extra stackmaps for native
3339 // debugging. We keep however all AOT code from the boot image,
3340 // since the JIT-at-first-use is blocking and would result in non-negligible
3341 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003342 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003343 }
3344
3345 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003346}
3347
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003348void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003349 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003350 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003351 if (klass->NumDirectMethods() == 0) {
3352 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003353 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003354 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003355 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003356 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003357 return; // OAT file unavailable.
3358 }
Ian Rogers19846512012-02-24 11:42:47 -08003359 }
Alex Light64ad14d2014-08-19 14:23:13 -07003360
Mathieu Chartierf8322842014-05-16 10:59:25 -07003361 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003362 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3363 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3364 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003365 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003366 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003367 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003368 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3369 klass->GetDexClassDefIndex(),
3370 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003371 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003372 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003373 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003374 if (!method->IsStatic()) {
3375 // Only update static methods.
3376 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003377 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003378 const void* quick_code = nullptr;
3379 if (has_oat_class) {
3380 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003381 quick_code = oat_method.GetQuickCode();
3382 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003383 // Check if we have JIT compiled code for it.
3384 if (quick_code == nullptr && Runtime::Current()->GetJit() != nullptr) {
3385 quick_code = Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteSavedEntryPoint(method);
3386 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003387 // Check whether the method is native, in which case it's generic JNI.
3388 if (quick_code == nullptr && method->IsNative()) {
3389 quick_code = GetQuickGenericJniStub();
3390 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003391 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003392 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003393 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003394 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003395 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003396 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003397}
3398
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003399// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3400// method. Should only be called on non-invokable methods.
3401inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003402 DCHECK(method != nullptr);
3403 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003404 method->SetEntryPointFromQuickCompiledCodePtrSize(
3405 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3406 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003407}
3408
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003409static void LinkCode(ClassLinker* class_linker,
3410 ArtMethod* method,
3411 const OatFile::OatClass* oat_class,
3412 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003413 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003414 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003415 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003416 // The following code only applies to a non-compiler runtime.
3417 return;
3418 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003419 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003420 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003421 if (oat_class != nullptr) {
3422 // Every kind of method should at least get an invoke stub from the oat_method.
3423 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003424 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003425 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003426 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003427
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003428 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003429 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003430 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003431
Alex Light9139e002015-10-09 15:59:48 -07003432 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003433 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003434 return;
3435 }
Ian Rogers19846512012-02-24 11:42:47 -08003436
3437 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003438 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003439 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3440 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003441 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003442 } else if (quick_code == nullptr && method->IsNative()) {
3443 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003444 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003445 // Set entry point from compiled code if there's no code or in interpreter only mode.
3446 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003447 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003448
Ian Rogers62d6c772013-02-27 08:32:07 -08003449 if (method->IsNative()) {
3450 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003451 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003452
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003453 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003454 // We have a native method here without code. Then it should have either the generic JNI
3455 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3456 // TODO: this doesn't handle all the cases where trampolines may be installed.
3457 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003458 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3459 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003460 }
Nicolas Geoffray5a0622a2019-04-12 16:35:17 +01003461
3462 // For the jitzygote configuration we want JNI stubs to be compiled, just like boot classpath
3463 // AOT where we compile all native entries.
3464 if (!Runtime::Current()->IsUsingDefaultBootImageLocation() &&
3465 method->GetDeclaringClass()->GetClassLoader() == nullptr &&
3466 Runtime::Current()->GetJit() != nullptr) {
3467 Runtime::Current()->GetJit()->CompileMethod(
3468 method, Thread::Current(), /* baseline= */ false, /* osr= */ false);
3469 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003470 }
3471}
3472
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003473void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003474 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003475 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003476 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003477 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003478 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003479 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003480 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003481 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003482
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003483 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003484 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003485 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003486 klass->SetAccessFlags(access_flags);
3487 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003488 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003489 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003490
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003491 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003492 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003493}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003494
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003495LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3496 LinearAlloc* allocator,
3497 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003498 if (length == 0) {
3499 return nullptr;
3500 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003501 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3502 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3503 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003504 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003505 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003506 CHECK(ret != nullptr);
3507 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3508 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003509}
3510
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003511LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3512 LinearAlloc* allocator,
3513 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003514 if (length == 0) {
3515 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003516 }
Vladimir Marko14632852015-08-17 12:07:23 +01003517 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3518 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003519 const size_t storage_size =
3520 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003521 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003522 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003523 CHECK(ret != nullptr);
3524 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003525 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003526 }
3527 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003528}
3529
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003530LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003531 if (class_loader == nullptr) {
3532 return Runtime::Current()->GetLinearAlloc();
3533 }
3534 LinearAlloc* allocator = class_loader->GetAllocator();
3535 DCHECK(allocator != nullptr);
3536 return allocator;
3537}
3538
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003539LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003540 if (class_loader == nullptr) {
3541 return Runtime::Current()->GetLinearAlloc();
3542 }
3543 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3544 LinearAlloc* allocator = class_loader->GetAllocator();
3545 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003546 RegisterClassLoader(class_loader);
3547 allocator = class_loader->GetAllocator();
3548 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003549 }
3550 return allocator;
3551}
3552
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003553void ClassLinker::LoadClass(Thread* self,
3554 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003555 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003556 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003557 ClassAccessor accessor(dex_file,
3558 dex_class_def,
3559 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003560 if (!accessor.HasClassData()) {
3561 return;
3562 }
3563 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003564 {
3565 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3566 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003567 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003568 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003569 // We allow duplicate definitions of the same field in a class_data_item
3570 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003571 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003572 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3573 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003574 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003575 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3576 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003577 accessor.NumInstanceFields());
3578 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003579 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003580 uint32_t last_static_field_idx = 0u;
3581 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003582
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003583 // Methods
3584 bool has_oat_class = false;
3585 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3586 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3587 : OatFile::OatClass::Invalid();
3588 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3589 klass->SetMethodsPtr(
3590 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3591 accessor.NumDirectMethods(),
3592 accessor.NumVirtualMethods());
3593 size_t class_def_method_index = 0;
3594 uint32_t last_dex_method_index = dex::kDexNoIndex;
3595 size_t last_class_def_method_index = 0;
3596
3597 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3598 // methods needs to decode all of the fields.
3599 accessor.VisitFieldsAndMethods([&](
3600 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3601 uint32_t field_idx = field.GetIndex();
3602 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3603 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3604 LoadField(field, klass, &sfields->At(num_sfields));
3605 ++num_sfields;
3606 last_static_field_idx = field_idx;
3607 }
3608 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3609 uint32_t field_idx = field.GetIndex();
3610 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3611 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3612 LoadField(field, klass, &ifields->At(num_ifields));
3613 ++num_ifields;
3614 last_instance_field_idx = field_idx;
3615 }
3616 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3617 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3618 image_pointer_size_);
3619 LoadMethod(dex_file, method, klass, art_method);
3620 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3621 uint32_t it_method_index = method.GetIndex();
3622 if (last_dex_method_index == it_method_index) {
3623 // duplicate case
3624 art_method->SetMethodIndex(last_class_def_method_index);
3625 } else {
3626 art_method->SetMethodIndex(class_def_method_index);
3627 last_dex_method_index = it_method_index;
3628 last_class_def_method_index = class_def_method_index;
3629 }
3630 ++class_def_method_index;
3631 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3632 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3633 class_def_method_index - accessor.NumDirectMethods(),
3634 image_pointer_size_);
3635 LoadMethod(dex_file, method, klass, art_method);
3636 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3637 ++class_def_method_index;
3638 });
3639
3640 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003641 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003642 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3643 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3644 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003645 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3646 if (sfields != nullptr) {
3647 sfields->SetSize(num_sfields);
3648 }
3649 if (ifields != nullptr) {
3650 ifields->SetSize(num_ifields);
3651 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003652 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003653 // Set the field arrays.
3654 klass->SetSFieldsPtr(sfields);
3655 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003656 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003657 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003658 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003659 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003660 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003661 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003662}
3663
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003664void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003665 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003666 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003667 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003668 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003669 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003670
David Brazdil85865692018-10-30 17:26:20 +00003671 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3672 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003673}
3674
Mathieu Chartier268764d2016-09-13 12:09:38 -07003675void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003676 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003677 Handle<mirror::Class> klass,
3678 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003679 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003680 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003681 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003682
Mathieu Chartier268764d2016-09-13 12:09:38 -07003683 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003684 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003685 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003686 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003687
David Brazdil85865692018-10-30 17:26:20 +00003688 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3689 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003690
Ian Rogersdfb325e2013-10-30 01:00:44 -07003691 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003692 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003693 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3694 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003695 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003696 klass->SetFinalizable();
3697 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003698 std::string temp;
3699 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003700 // The Enum class declares a "final" finalize() method to prevent subclasses from
3701 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3702 // subclasses, so we exclude it here.
3703 // We also want to avoid setting the flag on Object, where we know that finalize() is
3704 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003705 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3706 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003707 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003708 }
3709 }
3710 }
3711 } else if (method_name[0] == '<') {
3712 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003713 bool is_init = (strcmp("<init>", method_name) == 0);
3714 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003715 if (UNLIKELY(!is_init && !is_clinit)) {
3716 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3717 } else {
3718 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3719 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003720 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003721 access_flags |= kAccConstructor;
3722 }
3723 }
3724 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003725 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3726 // Check if the native method is annotated with @FastNative or @CriticalNative.
3727 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3728 dex_file, dst->GetClassDef(), dex_method_idx);
3729 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003730 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003731 // Must be done after SetAccessFlags since IsAbstract depends on it.
3732 if (klass->IsInterface() && dst->IsAbstract()) {
3733 dst->CalculateAndSetImtIndex();
3734 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003735}
3736
Ian Rogers7b078e82014-09-10 14:44:24 -07003737void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003738 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003739 self,
3740 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003741 Runtime::Current()->GetLinearAlloc());
3742 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003743 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003744}
3745
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003746void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003747 ObjPtr<mirror::DexCache> dex_cache) {
3748 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003749 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003750 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003751 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003752}
3753
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003754void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003755 ObjPtr<mirror::DexCache> dex_cache,
3756 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003757 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003758 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003759 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003760 // For app images, the dex cache location may be a suffix of the dex file location since the
3761 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003762 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3763 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003764 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3765 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003766 // The following paths checks don't work on preopt when using boot dex files, where the dex
3767 // cache location is the one on device, and the dex_file's location is the one on host.
3768 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3769 CHECK_GE(dex_file_location.length(), dex_cache_length)
3770 << dex_cache_location << " " << dex_file.GetLocation();
3771 const std::string dex_file_suffix = dex_file_location.substr(
3772 dex_file_location.length() - dex_cache_length,
3773 dex_cache_length);
3774 // Example dex_cache location is SettingsProvider.apk and
3775 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3776 CHECK_EQ(dex_cache_location, dex_file_suffix);
3777 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003778 const OatFile* oat_file =
3779 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003780 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3781 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3782 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3783 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003784 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003785 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3786 DexCacheData data = *it;
3787 if (self->IsJWeakCleared(data.weak_root)) {
3788 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003789 it = dex_caches_.erase(it);
3790 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003791 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003792 it->dex_file->GetOatDexFile() != nullptr &&
3793 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003794 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003795 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003796 ++it;
3797 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003798 }
Vladimir Markob066d432018-01-03 13:14:37 +00003799 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003800 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003801 }
David Brazdila5c3a802019-03-08 14:59:41 +00003802 // Let hiddenapi assign a domain to the newly registered dex file.
3803 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3804
Vladimir Markocd556b02017-02-03 11:47:34 +00003805 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003806 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003807 DexCacheData data;
3808 data.weak_root = dex_cache_jweak;
3809 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003810 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003811 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003812 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003813 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3814 // path dex caches without an image.
3815 data.class_table->InsertStrongRoot(dex_cache);
3816 if (class_loader != nullptr) {
3817 // Since we added a strong root to the class table, do the write barrier as required for
3818 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003819 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003820 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003821 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003822}
3823
Vladimir Markocd556b02017-02-03 11:47:34 +00003824ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3825 return data.IsValid()
3826 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3827 : nullptr;
3828}
3829
3830ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3831 Thread* self,
3832 ObjPtr<mirror::DexCache> dex_cache,
3833 const DexCacheData& data,
3834 ObjPtr<mirror::ClassLoader> class_loader) {
3835 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3836 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3837 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3838 "Attempt to register dex file %s with multiple class loaders",
3839 data.dex_file->GetLocation().c_str());
3840 return nullptr;
3841 }
3842 return dex_cache;
3843}
3844
Alex Light07f06212017-06-01 14:01:43 -07003845void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3846 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003847 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003848 Thread* self = Thread::Current();
3849 StackHandleScope<2> hs(self);
3850 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3851 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3852 const DexFile* dex_file = dex_cache->GetDexFile();
3853 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3854 if (kIsDebugBuild) {
3855 DexCacheData old_data;
3856 {
3857 ReaderMutexLock mu(self, *Locks::dex_lock_);
3858 old_data = FindDexCacheDataLocked(*dex_file);
3859 }
3860 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3861 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3862 << "been registered on dex file " << dex_file->GetLocation();
3863 }
3864 ClassTable* table;
3865 {
3866 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3867 table = InsertClassTableForClassLoader(h_class_loader.Get());
3868 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003869 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3870 // a thread holding the dex lock and blocking on a condition variable regarding
3871 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003872 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003873 WriterMutexLock mu(self, *Locks::dex_lock_);
3874 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3875 table->InsertStrongRoot(h_dex_cache.Get());
3876 if (h_class_loader.Get() != nullptr) {
3877 // Since we added a strong root to the class table, do the write barrier as required for
3878 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003879 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003880 }
3881}
3882
Vladimir Markocd556b02017-02-03 11:47:34 +00003883ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3884 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003885 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003886 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003887 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003888 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003889 old_data = FindDexCacheDataLocked(dex_file);
3890 }
3891 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3892 if (old_dex_cache != nullptr) {
3893 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003894 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003895 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003896 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3897 DCHECK(linear_alloc != nullptr);
3898 ClassTable* table;
3899 {
3900 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3901 table = InsertClassTableForClassLoader(class_loader);
3902 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003903 // Don't alloc while holding the lock, since allocation may need to
3904 // suspend all threads and another thread may need the dex_lock_ to
3905 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003906 StackHandleScope<3> hs(self);
3907 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003908 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003909 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3910 self,
3911 dex_file)));
3912 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003913 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003914 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3915 // a thread holding the dex lock and blocking on a condition variable regarding
3916 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003917 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003918 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003919 old_data = FindDexCacheDataLocked(dex_file);
3920 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003921 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003922 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3923 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3924 // that the arrays are null.
3925 mirror::DexCache::InitializeDexCache(self,
3926 h_dex_cache.Get(),
3927 h_location.Get(),
3928 &dex_file,
3929 linear_alloc,
3930 image_pointer_size_);
3931 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003932 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003933 }
3934 if (old_dex_cache != nullptr) {
3935 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3936 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003937 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003938 self->ClearException();
3939 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3940 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3941 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003942 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003943 self->AssertPendingOOMException();
3944 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003945 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003946 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003947 if (h_class_loader.Get() != nullptr) {
3948 // Since we added a strong root to the class table, do the write barrier as required for
3949 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003950 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003951 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003952 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003953}
3954
Vladimir Markocd556b02017-02-03 11:47:34 +00003955bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003956 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003957 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003958}
3959
Vladimir Markocd556b02017-02-03 11:47:34 +00003960ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3961 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003962 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3963 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003964 if (dex_cache != nullptr) {
3965 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003966 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003967 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003968 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003969 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003970 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003971 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003972 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003973 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3974 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003975 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003976}
3977
Vladimir Markocd556b02017-02-03 11:47:34 +00003978ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3979 const DexFile* dex_file = dex_cache->GetDexFile();
3980 DCHECK(dex_file != nullptr);
3981 ReaderMutexLock mu(self, *Locks::dex_lock_);
3982 // Search assuming unique-ness of dex file.
3983 for (const DexCacheData& data : dex_caches_) {
3984 // Avoid decoding (and read barriers) other unrelated dex caches.
3985 if (data.dex_file == dex_file) {
3986 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3987 if (registered_dex_cache != nullptr) {
3988 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3989 return data.class_table;
3990 }
3991 }
3992 }
3993 return nullptr;
3994}
3995
3996ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3997 // Search assuming unique-ness of dex file.
3998 for (const DexCacheData& data : dex_caches_) {
3999 // Avoid decoding (and read barriers) other unrelated dex caches.
4000 if (data.dex_file == &dex_file) {
4001 return data;
4002 }
4003 }
4004 return DexCacheData();
4005}
4006
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004007ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004008 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004009 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01004010 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004011 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004012 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004013 }
Ian Rogers1f539342012-10-03 21:09:42 -07004014 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004015 StackHandleScope<1> hs(self);
4016 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004017 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004018 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
4019 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004020 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07004021 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004022 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004023 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004024 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4025 h_class.Get(),
4026 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004027 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004028 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004029}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004030
Vladimir Marko02610552018-06-04 14:38:00 +01004031inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4032 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4033}
4034
Brian Carlstrombe977852011-07-19 14:54:54 -07004035// Create an array class (i.e. the class object for the array, not the
4036// array itself). "descriptor" looks like "[C" or "[[[[B" or
4037// "[Ljava/lang/String;".
4038//
4039// If "descriptor" refers to an array of primitives, look up the
4040// primitive type's internally-generated class object.
4041//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004042// "class_loader" is the class loader of the class that's referring to
4043// us. It's used to ensure that we're looking for the element type in
4044// the right context. It does NOT become the class loader for the
4045// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004046//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004047// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004048ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4049 const char* descriptor,
4050 size_t hash,
4051 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004052 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004053 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004054 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004055
4056 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4057 // code to be executed. We put it up here so we can avoid all the allocations associated with
4058 // creating the class. This can happen with (eg) jit threads.
4059 if (!self->CanLoadClasses()) {
4060 // Make sure we don't try to load anything, potentially causing an infinite loop.
4061 ObjPtr<mirror::Throwable> pre_allocated =
4062 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4063 self->SetException(pre_allocated);
4064 return nullptr;
4065 }
4066
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004067 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4068 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004069 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004070 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004071 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004072 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4073 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004074 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004075 DCHECK(self->IsExceptionPending());
4076 return nullptr;
4077 } else {
4078 self->ClearException();
4079 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004080 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004081 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4082 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4083 return nullptr;
4084 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004085 // See if the component type is already loaded. Array classes are
4086 // always associated with the class loader of their underlying
4087 // element type -- an array of Strings goes with the loader for
4088 // java/lang/String -- so we need to look for it there. (The
4089 // caller should have checked for the existence of the class
4090 // before calling here, but they did so with *their* class loader,
4091 // not the component type's loader.)
4092 //
4093 // If we find it, the caller adds "loader" to the class' initiating
4094 // loader list, which should prevent us from going through this again.
4095 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004096 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004097 // are the same, because our caller (FindClass) just did the
4098 // lookup. (Even if we get this wrong we still have correct behavior,
4099 // because we effectively do this lookup again when we add the new
4100 // class to the hash table --- necessary because of possible races with
4101 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004102 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004103 ObjPtr<mirror::Class> new_class =
4104 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004105 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004106 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004107 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004108 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004109
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004110 // Fill out the fields in the Class.
4111 //
4112 // It is possible to execute some methods against arrays, because
4113 // all arrays are subclasses of java_lang_Object_, so we need to set
4114 // up a vtable. We can just point at the one in java_lang_Object_.
4115 //
4116 // Array classes are simple enough that we don't need to do a full
4117 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004118 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004119 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004120 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004121 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004122 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004123 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004124 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4125 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4126 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004127 } else if (strcmp(descriptor, "[Z") == 0) {
4128 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4129 } else if (strcmp(descriptor, "[B") == 0) {
4130 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4131 } else if (strcmp(descriptor, "[C") == 0) {
4132 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4133 } else if (strcmp(descriptor, "[S") == 0) {
4134 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004135 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004136 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004137 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004138 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004139 } else if (strcmp(descriptor, "[F") == 0) {
4140 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4141 } else if (strcmp(descriptor, "[D") == 0) {
4142 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004143 }
4144 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004145 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004146 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004147 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004148 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004149 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004150 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004151 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004152 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004153 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004154 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004155 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004156 new_class->SetSuperClass(java_lang_Object);
4157 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004158 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004159 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004160 if (component_type->IsPrimitive()) {
4161 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4162 } else {
4163 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4164 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004165 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004166 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4167 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4168 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004169 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004170 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004171 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004172 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004173
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004174 // All arrays have java/lang/Cloneable and java/io/Serializable as
4175 // interfaces. We need to set that up here, so that stuff like
4176 // "instanceof" works right.
4177 //
4178 // Note: The GC could run during the call to FindSystemClass,
4179 // so we need to make sure the class object is GC-valid while we're in
4180 // there. Do this by clearing the interface list so the GC will just
4181 // think that the entries are null.
4182
4183
4184 // Use the single, global copies of "interfaces" and "iftable"
4185 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004186 {
Vladimir Marko02610552018-06-04 14:38:00 +01004187 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004188 CHECK(array_iftable != nullptr);
4189 new_class->SetIfTable(array_iftable);
4190 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004191
Elliott Hughes00626c22013-06-14 15:04:14 -07004192 // Inherit access flags from the component type.
4193 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4194 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4195 access_flags &= kAccJavaFlagsMask;
4196 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004197 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004198 access_flags |= kAccAbstract | kAccFinal;
4199 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004200 // Arrays are access-checks-clean and preverified.
4201 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004202
4203 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004204
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004205 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004206 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004207 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4208 // duplicate events in case of races. Array classes don't really follow dedicated
4209 // load and prepare, anyways.
4210 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4211 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4212
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004213 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004215 }
4216 // Another thread must have loaded the class after we
4217 // started but before we finished. Abandon what we've
4218 // done.
4219 //
4220 // (Yes, this happens.)
4221
Vladimir Markobcf17522018-06-01 13:14:32 +01004222 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004223}
4224
Vladimir Marko9186b182018-11-06 14:55:54 +00004225ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4226 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004227 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004228 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4229 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4230 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4231 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4232 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4233 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4234 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4235 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4236 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004237 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004238 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004239 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004240 return GetClassRoot(class_root, this);
4241}
4242
4243ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4244 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4245 if (UNLIKELY(result == nullptr)) {
4246 std::string printable_type(PrintableChar(type));
4247 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4248 }
4249 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004250}
4251
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004252ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4253 ObjPtr<mirror::Class> klass,
4254 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004255 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004256 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004257 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004258 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004259 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004260 source += " from ";
4261 source += dex_cache->GetLocation()->ToModifiedUtf8();
4262 }
4263 LOG(INFO) << "Loaded class " << descriptor << source;
4264 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004265 {
4266 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004267 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004268 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004269 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004270 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004271 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004272 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004273 VerifyObject(klass);
4274 class_table->InsertWithHash(klass, hash);
4275 if (class_loader != nullptr) {
4276 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004277 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004278 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004279 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004280 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004281 }
4282 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004283 if (kIsDebugBuild) {
4284 // Test that copied methods correctly can find their holder.
4285 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4286 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4287 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004288 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004289 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004290}
4291
Vladimir Marko1998cd02017-01-13 13:02:58 +00004292void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004293 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4294 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4295 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4296 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004297 }
4298}
4299
Alex Lighte64300b2015-12-15 15:02:47 -08004300// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004301void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004302 LengthPrefixedArray<ArtMethod>* new_methods) {
4303 klass->SetMethodsPtrUnchecked(new_methods,
4304 klass->NumDirectMethods(),
4305 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004306 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004307 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004308}
4309
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004310ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4311 const char* descriptor,
4312 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004313 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4314}
4315
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004316ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4317 const char* descriptor,
4318 size_t hash,
4319 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004320 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4321 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4322 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004323 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004324 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004325 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004326 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004327 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004328 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004329}
4330
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004331class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4332 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004333 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004334
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004335 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004336 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004337 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004338 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004339 if (class_table != nullptr) {
4340 class_table->FreezeSnapshot();
4341 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004342 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004343};
4344
4345void ClassLinker::MoveClassTableToPreZygote() {
4346 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004347 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004348 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004349 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004350}
4351
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004352// Look up classes by hash and descriptor and put all matching ones in the result array.
4353class LookupClassesVisitor : public ClassLoaderVisitor {
4354 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004355 LookupClassesVisitor(const char* descriptor,
4356 size_t hash,
4357 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004358 : descriptor_(descriptor),
4359 hash_(hash),
4360 result_(result) {}
4361
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004362 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004363 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004364 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004365 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004366 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4367 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004368 result_->push_back(klass);
4369 }
4370 }
4371
4372 private:
4373 const char* const descriptor_;
4374 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004375 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004376};
4377
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004378void ClassLinker::LookupClasses(const char* descriptor,
4379 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004380 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004381 Thread* const self = Thread::Current();
4382 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004383 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004384 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004385 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004386 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004387 result.push_back(klass);
4388 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004389 LookupClassesVisitor visitor(descriptor, hash, &result);
4390 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004391}
4392
Alex Lightf1f10492015-10-07 16:08:36 -07004393bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4394 Handle<mirror::Class> klass,
4395 Handle<mirror::Class> supertype) {
4396 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004397 DCHECK(klass != nullptr);
4398 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004399
Alex Lightf1f10492015-10-07 16:08:36 -07004400 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4401 VerifyClass(self, supertype);
4402 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004403
4404 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4405 // The supertype is either verified, or we soft failed at AOT time.
4406 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004407 return true;
4408 }
4409 // If we got this far then we have a hard failure.
4410 std::string error_msg =
4411 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004412 klass->PrettyDescriptor().c_str(),
4413 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004414 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004415 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004416 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004417 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004418 // Set during VerifyClass call (if at all).
4419 self->ClearException();
4420 }
4421 // Change into a verify error.
4422 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004423 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004424 self->GetException()->SetCause(cause.Get());
4425 }
4426 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4427 if (Runtime::Current()->IsAotCompiler()) {
4428 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4429 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004430 // Need to grab the lock to change status.
4431 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004432 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004433 return false;
4434}
4435
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004436verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004437 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004438 {
4439 // TODO: assert that the monitor on the Class is held
4440 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004441
Andreas Gampe884f3b82016-03-30 19:52:58 -07004442 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004443 ClassStatus old_status = klass->GetStatus();
4444 while (old_status == ClassStatus::kVerifying ||
4445 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004446 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004447 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4448 // case we may see the same status again. b/62912904. This is why the check is
4449 // greater or equal.
4450 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004451 << "Class '" << klass->PrettyClass()
4452 << "' performed an illegal verification state transition from " << old_status
4453 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004454 old_status = klass->GetStatus();
4455 }
jeffhao98eacac2011-09-14 16:11:53 -07004456
Andreas Gampe884f3b82016-03-30 19:52:58 -07004457 // The class might already be erroneous, for example at compile time if we attempted to verify
4458 // this class as a parent to another.
4459 if (klass->IsErroneous()) {
4460 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004461 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004462 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004463
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004464 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004465 if (klass->IsVerified()) {
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 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004469
4470 // For AOT, don't attempt to re-verify if we have already found we should
4471 // verify at runtime.
4472 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004473 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004474 }
jeffhao98eacac2011-09-14 16:11:53 -07004475
Vladimir Marko2c64a832018-01-04 11:31:56 +00004476 if (klass->GetStatus() == ClassStatus::kResolved) {
4477 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004478 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004479 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004480 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004481 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004482 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004483 }
4484
4485 // Skip verification if disabled.
4486 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004487 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004488 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004489 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004490 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004491 }
4492
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004493 VLOG(class_linker) << "Beginning verification for class: "
4494 << klass->PrettyDescriptor()
4495 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4496
Ian Rogers9ffb0392012-09-10 11:56:50 -07004497 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004498 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004499 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4500 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004501 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004502 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004503 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004504 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004505
Alex Lightf1f10492015-10-07 16:08:36 -07004506 // Verify all default super-interfaces.
4507 //
4508 // (1) Don't bother if the superclass has already had a soft verification failure.
4509 //
4510 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4511 // recursive initialization by themselves. This is because when an interface is initialized
4512 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4513 // but choose not to for an optimization. If the interfaces is being verified due to a class
4514 // initialization (which would need all the default interfaces to be verified) the class code
4515 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004516 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004517 && !klass->IsInterface()) { // See (2)
4518 int32_t iftable_count = klass->GetIfTableCount();
4519 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4520 // Loop through all interfaces this class has defined. It doesn't matter the order.
4521 for (int32_t i = 0; i < iftable_count; i++) {
4522 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004523 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004524 // We only care if we have default interfaces and can skip if we are already verified...
4525 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4526 continue;
4527 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4528 // We had a hard failure while verifying this interface. Just return immediately.
4529 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004530 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004531 } else if (UNLIKELY(!iface->IsVerified())) {
4532 // We softly failed to verify the iface. Stop checking and clean up.
4533 // Put the iface into the supertype handle so we know what caused us to fail.
4534 supertype.Assign(iface.Get());
4535 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004536 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004537 }
4538 }
4539
Alex Lightf1f10492015-10-07 16:08:36 -07004540 // At this point if verification failed, then supertype is the "first" supertype that failed
4541 // verification (without a specific order). If verification succeeded, then supertype is either
4542 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004543 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004544 supertype.Get() == klass->GetSuperClass() ||
4545 !supertype->IsVerified());
4546
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004547 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004548 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004549 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004550 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004551
4552 VLOG(class_linker) << "Class preverified status for class "
4553 << klass->PrettyDescriptor()
4554 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4555 << ": "
4556 << preverified;
4557
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004558 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4559 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004560 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4561 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004562
Ian Rogers62d6c772013-02-27 08:32:07 -08004563 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004564 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004565 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004566 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004567 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004568
4569 // Verification is done, grab the lock again.
4570 ObjectLock<mirror::Class> lock(self, klass);
4571
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004572 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4573 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004574 VLOG(class_linker) << "Soft verification failure in class "
4575 << klass->PrettyDescriptor()
4576 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4577 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004578 }
Ian Rogers1f539342012-10-03 21:09:42 -07004579 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004580 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004581 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004582 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004583 // Even though there were no verifier failures we need to respect whether the super-class and
4584 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004585 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004586 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004587 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004588 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4589 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004590 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004591 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004592 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004593 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004594 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004595 // Soft failures at compile time should be retried at runtime. Soft
4596 // failures at runtime will be handled by slow paths in the generated
4597 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004598 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004599 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004600 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004601 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004602 // As this is a fake verified status, make sure the methods are _not_ marked
4603 // kAccSkipAccessChecks later.
4604 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004605 }
4606 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004607 } else {
David Sehr709b0702016-10-13 09:12:37 -07004608 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004609 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4610 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004611 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004612 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004613 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004614 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004615 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004616 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004617 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004618 // method.
4619 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004620 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004621 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004622
4623 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4624 // Never skip access checks if the verification soft fail is forced.
4625 // Mark the class as having a verification attempt to avoid re-running the verifier.
4626 klass->SetVerificationAttempted();
4627 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004628 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004629 }
Andreas Gampe48498592014-09-10 19:48:05 -07004630 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004631 // Done verifying. Notify the compiler about the verification status, in case the class
4632 // was verified implicitly (eg super class of a compiled class).
4633 if (Runtime::Current()->IsAotCompiler()) {
4634 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4635 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4636 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004637 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004638}
4639
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004640verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4641 Handle<mirror::Class> klass,
4642 verifier::HardFailLogMode log_level,
4643 std::string* error_msg) {
4644 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004645 return verifier::ClassVerifier::VerifyClass(self,
4646 klass.Get(),
4647 runtime->GetCompilerCallbacks(),
4648 runtime->IsAotCompiler(),
4649 log_level,
4650 Runtime::Current()->GetTargetSdkVersion(),
4651 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004652}
4653
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004654bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004655 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004656 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004657 // If we're compiling, we can only verify the class using the oat file if
4658 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004659 // the compilation unit (app - dependencies). We will let the compiler callback
4660 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004661 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004662 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004663 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004664 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004665 return false;
4666 }
4667 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004668 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004669 return false;
4670 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004671 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004672
Andreas Gampeb40d3612018-06-26 15:49:42 -07004673 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004674 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004675 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004676 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4677 // For boot classpath classes in the case we're not using a default boot image:
4678 // we don't have the infrastructure yet to query verification data on individual
4679 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4680 // verified. This should be taken into account when measuring boot time and app
4681 // startup compare to the (current) production system where both:
4682 // 1) updatable boot classpath classes, and
4683 // 2) classes in /system referencing updatable classes
4684 // will be verified at runtime.
4685 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4686 oat_file_class_status = ClassStatus::kVerified;
4687 return true;
4688 }
4689 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004690 return false;
4691 }
4692
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004693 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004694 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004695 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004696 return true;
4697 }
4698 // If we only verified a subset of the classes at compile time, we can end up with classes that
4699 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004700 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004701 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004702 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004703 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004704 // Compile time verification failed with a soft error. Compile time verification can fail
4705 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004706 // class ... {
4707 // Foo x;
4708 // .... () {
4709 // if (...) {
4710 // v1 gets assigned a type of resolved class Foo
4711 // } else {
4712 // v1 gets assigned a type of unresolved class Bar
4713 // }
4714 // iput x = v1
4715 // } }
4716 // when we merge v1 following the if-the-else it results in Conflict
4717 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4718 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4719 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4720 // at compile time).
4721 return false;
4722 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004723 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004724 // Compile time verification failed with a hard error. This is caused by invalid instructions
4725 // in the class. These errors are unrecoverable.
4726 return false;
4727 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004728 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004729 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4730 // not loading the class.
4731 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4732 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004733 return false;
4734 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004735 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004736 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004737 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004738 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004739 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004740}
4741
Alex Light5a559862016-01-29 12:24:48 -08004742void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004743 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004744 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004745 }
4746}
4747
Alex Light5a559862016-01-29 12:24:48 -08004748void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004749 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004750 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004751 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004752 return; // native or abstract method
4753 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004754 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004755 return; // nothing to process
4756 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004757 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004758 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004759 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4760 CatchHandlerIterator iterator(handlers_ptr);
4761 for (; iterator.HasNext(); iterator.Next()) {
4762 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4763 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004764 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004765 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004766 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004767 DCHECK(Thread::Current()->IsExceptionPending());
4768 Thread::Current()->ClearException();
4769 }
4770 }
4771 }
4772 handlers_ptr = iterator.EndDataPointer();
4773 }
4774}
4775
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004776ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4777 jstring name,
4778 jobjectArray interfaces,
4779 jobject loader,
4780 jobjectArray methods,
4781 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004782 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004783
4784 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4785 // code to be executed. We put it up here so we can avoid all the allocations associated with
4786 // creating the class. This can happen with (eg) jit-threads.
4787 if (!self->CanLoadClasses()) {
4788 // Make sure we don't try to load anything, potentially causing an infinite loop.
4789 ObjPtr<mirror::Throwable> pre_allocated =
4790 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4791 self->SetException(pre_allocated);
4792 return nullptr;
4793 }
4794
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004795 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004796 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004797 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004798 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004799 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004800 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004801 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004802 DCHECK(temp_klass->GetClass() != nullptr);
4803 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004804 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4805 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004806 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4807 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4808 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4809 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004810 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004811 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004812 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004813 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004814 std::string storage;
4815 const char* descriptor = temp_klass->GetDescriptor(&storage);
4816 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004817
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004818 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004819 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004820
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004821 // Insert the class before loading the fields as the field roots
4822 // (ArtField::declaring_class_) are only visited from the class
4823 // table. There can't be any suspend points between inserting the
4824 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004825 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004826 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004827
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004828 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004829 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004830 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004831 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004832
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004833 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4834 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004835 ArtField& interfaces_sfield = sfields->At(0);
4836 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004837 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004838 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004839
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004840 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004841 ArtField& throws_sfield = sfields->At(1);
4842 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004843 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004844 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004845
Ian Rogers466bb252011-10-14 03:29:56 -07004846 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004847 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004848
Alex Lighte64300b2015-12-15 15:02:47 -08004849 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004850 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004851 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004852 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004853 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004854
4855 // Create the methods array.
4856 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4857 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004858 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4859 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004860 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004861 self->AssertPendingOOMException();
4862 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004863 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004864 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004865
4866 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004867 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004868
4869 // Create virtual method using specified prototypes.
4870 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004871 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004872 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004873 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004874 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004875 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4876 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004877 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004878
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004879 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004880 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004881 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004882 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004883 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004884
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004885 // At this point the class is loaded. Publish a ClassLoad event.
4886 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4887 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4888
4889 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004890 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004891 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004892 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004893 // Link the fields and virtual methods, creating vtable and iftables.
4894 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004895 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004896 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004897 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004898 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004899 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004900 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004901 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004902 CHECK(temp_klass->IsRetired());
4903 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004904
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004905 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004906 interfaces_sfield.SetObject<false>(
4907 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004908 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004909 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4910 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004911 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004912 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004913
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004914 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4915
Vladimir Marko305c38b2018-02-14 11:50:07 +00004916 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4917 // See also ClassLinker::EnsureInitialized().
4918 if (kBitstringSubtypeCheckEnabled) {
4919 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4920 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4921 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4922 }
4923
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004924 {
4925 // Lock on klass is released. Lock new class object.
4926 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004927 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004928 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004929 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004930
4931 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004932 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004933 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004934 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4935
Ian Rogersc2b44472011-12-14 21:17:17 -08004936 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004937 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4938 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004939 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004940 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004941
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004942 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004943 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004944 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004945 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004946 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004947
4948 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004949 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004950 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004951
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004952 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004953 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004954 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004955 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004956 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004957 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004958}
4959
Mathieu Chartiere401d142015-04-22 13:56:20 -07004960void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4961 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004962 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4963 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004964
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004965 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4966 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004967 ArtMethod* proxy_constructor =
4968 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004969 DCHECK(proxy_constructor != nullptr)
4970 << "Could not find <init> method in java.lang.reflect.Proxy";
4971
Jeff Haodb8a6642014-08-14 17:18:52 -07004972 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4973 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004974 DCHECK(out != nullptr);
4975 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004976 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004977 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004978 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004979 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4980 kAccPublic |
4981 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004982 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004983
4984 // Set the original constructor method.
4985 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004986}
4987
Mathieu Chartiere401d142015-04-22 13:56:20 -07004988void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004989 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004990 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4991 CHECK_STREQ(np->GetName(), "<init>");
4992 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004993 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004994}
4995
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004996void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004997 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004998 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004999 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005000 DCHECK(out != nullptr);
5001 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005002
Alex Lighte9dd04f2016-03-16 16:09:45 -07005003 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005004 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005005 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5006 // preference to the invocation handler.
5007 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5008 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005009 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5010 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005011 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5012
5013 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5014 // method they copy might (if it's a default method).
5015 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005016
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005017 // Set the original interface method.
5018 out->SetDataPtrSize(prototype, image_pointer_size_);
5019
Ian Rogers466bb252011-10-14 03:29:56 -07005020 // At runtime the method looks like a reference and argument saving method, clone the code
5021 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005022 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005023}
Jesse Wilson95caa792011-10-12 18:14:17 -04005024
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005026 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005027 CHECK(!prototype->IsFinal());
5028 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005029 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005030
5031 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5032 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005033 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005034 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005035}
5036
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005037bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005038 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005039 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005040 return true;
5041 }
5042 if (!can_init_statics) {
5043 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005044 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005045 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005046 return false;
5047 }
5048 // Check if there are encoded static values needing initialization.
5049 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005050 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005051 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005052 if (dex_class_def->static_values_off_ != 0) {
5053 return false;
5054 }
5055 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005056 // If we are a class we need to initialize all interfaces with default methods when we are
5057 // initialized. Check all of them.
5058 if (!klass->IsInterface()) {
5059 size_t num_interfaces = klass->GetIfTableCount();
5060 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005061 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005062 if (iface->HasDefaultMethods() &&
5063 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5064 return false;
5065 }
5066 }
5067 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005068 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005069 if (klass->IsInterface() || !klass->HasSuperClass()) {
5070 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005071 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005072 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005073 if (!can_init_parents && !super_class->IsInitialized()) {
5074 return false;
5075 }
5076 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005077}
5078
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005079bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5080 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005081 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5082
5083 // Are we already initialized and therefore done?
5084 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5085 // an initialized class will never change its state.
5086 if (klass->IsInitialized()) {
5087 return true;
5088 }
5089
5090 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005091 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005092 return false;
5093 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005094
Ian Rogers7b078e82014-09-10 14:44:24 -07005095 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005096 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005097 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005098 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005099
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005100 // Re-check under the lock in case another thread initialized ahead of us.
5101 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005102 return true;
5103 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005104
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005105 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005106 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005107 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005108 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005109 return false;
5110 }
5111
Vladimir Marko72ab6842017-01-20 19:32:50 +00005112 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5113 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005114
5115 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005116 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005117 if (!klass->IsVerified()) {
5118 // We failed to verify, expect either the klass to be erroneous or verification failed at
5119 // compile time.
5120 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005121 // The class is erroneous. This may be a verifier error, or another thread attempted
5122 // verification and/or initialization and failed. We can distinguish those cases by
5123 // whether an exception is already pending.
5124 if (self->IsExceptionPending()) {
5125 // Check that it's a VerifyError.
5126 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005127 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005128 } else {
5129 // Check that another thread attempted initialization.
5130 DCHECK_NE(0, klass->GetClinitThreadId());
5131 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5132 // Need to rethrow the previous failure now.
5133 ThrowEarlierClassFailure(klass.Get(), true);
5134 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005135 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005136 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005137 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005138 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005139 self->AssertNoPendingException();
5140 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005141 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005142 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005143 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005144 } else {
5145 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005146 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005147
5148 // A separate thread could have moved us all the way to initialized. A "simple" example
5149 // involves a subclass of the current class being initialized at the same time (which
5150 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005151 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005152 if (klass->IsInitialized()) {
5153 return true;
5154 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005155 }
5156
Vladimir Marko2c64a832018-01-04 11:31:56 +00005157 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005158 // initializing higher up the stack or another thread has beat us
5159 // to initializing and we need to wait. Either way, this
5160 // invocation of InitializeClass will not be responsible for
5161 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005162 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005163 // Could have got an exception during verification.
5164 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005165 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005166 return false;
5167 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005168 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005169 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005170 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005171 return true;
5172 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005173 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005174 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005175 }
5176
Jeff Haoe2e40342017-07-19 10:45:18 -07005177 // Try to get the oat class's status for this class if the oat file is present. The compiler
5178 // tries to validate superclass descriptors, and writes the result into the oat file.
5179 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5180 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5181 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005182 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005183 const Runtime* runtime = Runtime::Current();
5184 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5185 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5186 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005187 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005188 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005189 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005190 return false;
5191 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005192 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005193
Vladimir Marko2c64a832018-01-04 11:31:56 +00005194 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005195 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005196
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005197 // From here out other threads may observe that we're initializing and so changes of state
5198 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005199 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005200 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005201
5202 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005203 }
5204
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005205 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005206 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005207 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005208 if (!super_class->IsInitialized()) {
5209 CHECK(!super_class->IsInterface());
5210 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005211 StackHandleScope<1> hs(self);
5212 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005213 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005214 if (!super_initialized) {
5215 // The super class was verified ahead of entering initializing, we should only be here if
5216 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005217 // For the case of aot compiler, the super class might also be initializing but we don't
5218 // want to process circular dependencies in pre-compile.
5219 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005220 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005221 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005222 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005223 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005224 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005225 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005226 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005227 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005228 return false;
5229 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005230 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005231 }
5232
Alex Lighteb7c1442015-08-31 13:17:42 -07005233 if (!klass->IsInterface()) {
5234 // Initialize interfaces with default methods for the JLS.
5235 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005236 // Only setup the (expensive) handle scope if we actually need to.
5237 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005238 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005239 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5240 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005241 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005242 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005243 CHECK(handle_scope_iface->IsInterface());
5244 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5245 // We have already done this for this interface. Skip it.
5246 continue;
5247 }
5248 // We cannot just call initialize class directly because we need to ensure that ALL
5249 // interfaces with default methods are initialized. Non-default interface initialization
5250 // will not affect other non-default super-interfaces.
5251 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5252 handle_scope_iface,
5253 can_init_statics,
5254 can_init_parents);
5255 if (!iface_initialized) {
5256 ObjectLock<mirror::Class> lock(self, klass);
5257 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005258 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005259 return false;
5260 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005261 }
5262 }
5263 }
5264
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005265 const size_t num_static_fields = klass->NumStaticFields();
5266 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005267 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005268 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005269 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005270 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005271 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005272
5273 // Eagerly fill in static fields so that the we don't have to do as many expensive
5274 // Class::FindStaticField in ResolveField.
5275 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005276 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005277 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005278 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005279 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005280 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005281 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5282 field,
5283 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5284 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005285 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005286 } else {
5287 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005288 }
5289 }
5290
Vladimir Markoe11dd502017-12-08 14:09:45 +00005291 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5292 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005293 this,
5294 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005295 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005296
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005297 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005298 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005299 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005300 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5301 if (!value_it.HasNext()) {
5302 break;
5303 }
5304 ArtField* art_field = ResolveField(field.GetIndex(),
5305 dex_cache,
5306 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005307 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005308 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005309 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005310 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005311 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005312 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005313 if (self->IsExceptionPending()) {
5314 break;
5315 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005316 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005317 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005318 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005319 }
5320 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005321
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005322
Mathieu Chartierda595be2016-08-10 13:57:39 -07005323 if (!self->IsExceptionPending()) {
5324 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5325 if (clinit != nullptr) {
5326 CHECK(can_init_statics);
5327 JValue result;
5328 clinit->Invoke(self, nullptr, 0, &result, "V");
5329 }
5330 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005331 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005332 uint64_t t1 = NanoTime();
5333
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005334 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005335 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005336 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005337
5338 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005339 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005340 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005341 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005342 } else if (Runtime::Current()->IsTransactionAborted()) {
5343 // The exception thrown when the transaction aborted has been caught and cleared
5344 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005345 VLOG(compiler) << "Return from class initializer of "
5346 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005347 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005348 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005349 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005350 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005351 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005352 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5353 RuntimeStats* thread_stats = self->GetStats();
5354 ++global_stats->class_init_count;
5355 ++thread_stats->class_init_count;
5356 global_stats->class_init_time_ns += (t1 - t0);
5357 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005358 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005359 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005360 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005361 std::string temp;
5362 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005363 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005364 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005365 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005366 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005367 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005368 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005369 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005370}
5371
Alex Lighteb7c1442015-08-31 13:17:42 -07005372// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5373// and perform the initialization only on those interfaces that contain default methods.
5374bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5375 Handle<mirror::Class> iface,
5376 bool can_init_statics,
5377 bool can_init_parents) {
5378 CHECK(iface->IsInterface());
5379 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005380 // Only create the (expensive) handle scope if we need it.
5381 if (UNLIKELY(num_direct_ifaces > 0)) {
5382 StackHandleScope<1> hs(self);
5383 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5384 // First we initialize all of iface's super-interfaces recursively.
5385 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005386 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005387 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005388 if (!super_iface->HasBeenRecursivelyInitialized()) {
5389 // Recursive step
5390 handle_super_iface.Assign(super_iface);
5391 if (!InitializeDefaultInterfaceRecursive(self,
5392 handle_super_iface,
5393 can_init_statics,
5394 can_init_parents)) {
5395 return false;
5396 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005397 }
5398 }
5399 }
5400
5401 bool result = true;
5402 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5403 // initialize if we don't have default methods.
5404 if (iface->HasDefaultMethods()) {
5405 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5406 }
5407
5408 // Mark that this interface has undergone recursive default interface initialization so we know we
5409 // can skip it on any later class initializations. We do this even if we are not a default
5410 // interface since we can still avoid the traversal. This is purely a performance optimization.
5411 if (result) {
5412 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005413 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5414 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5415 // initialization is a performance optimization (to avoid another idempotent visit
5416 // for other implementing classes/interfaces), and can be revisited later.
5417 ObjectTryLock<mirror::Class> lock(self, iface);
5418 if (lock.Acquired()) {
5419 iface->SetRecursivelyInitialized();
5420 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005421 }
5422 return result;
5423}
5424
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005425bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5426 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005427 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005428 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005429 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005430 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005431 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005432 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005433
5434 // When we wake up, repeat the test for init-in-progress. If
5435 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005436 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005437 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005438 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005439 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005440 return false;
5441 }
5442 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005443 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005444 continue;
5445 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005446 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005447 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005448 // Compile time initialization failed.
5449 return false;
5450 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005451 if (klass->IsErroneous()) {
5452 // The caller wants an exception, but it was thrown in a
5453 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005454 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005455 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005456 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005457 return false;
5458 }
5459 if (klass->IsInitialized()) {
5460 return true;
5461 }
David Sehr709b0702016-10-13 09:12:37 -07005462 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005463 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005464 }
Ian Rogers07140832014-09-30 15:43:59 -07005465 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005466}
5467
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005468static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5469 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005470 ArtMethod* method,
5471 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005472 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005473 DCHECK(Thread::Current()->IsExceptionPending());
5474 DCHECK(!m->IsProxyMethod());
5475 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005476 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5477 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005478 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005479 std::string return_type = dex_file->PrettyType(return_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 return 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 return_type.c_str(), class_loader.c_str());
5489}
5490
5491static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5492 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005493 ArtMethod* method,
5494 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005495 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005496 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005497 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005498 DCHECK(Thread::Current()->IsExceptionPending());
5499 DCHECK(!m->IsProxyMethod());
5500 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005501 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5502 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005503 ThrowWrappedLinkageError(klass.Get(),
5504 "While checking class %s method %s signature against %s %s: "
5505 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005506 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5507 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005508 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005509 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005510 index, arg_type.c_str(), class_loader.c_str());
5511}
5512
5513static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5514 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005515 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005516 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005517 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005518 ThrowLinkageError(klass.Get(),
5519 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005520 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5521 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005522 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005523 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005524 error_msg.c_str());
5525}
5526
Ian Rogersb5fb2072014-12-02 17:22:02 -08005527static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005528 Handle<mirror::Class> klass,
5529 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005530 ArtMethod* method1,
5531 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005532 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005533 {
5534 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005535 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005536 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005537 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005538 return false;
5539 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005540 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005541 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005542 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005543 return false;
5544 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005545 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005546 ThrowSignatureMismatch(klass, super_klass, method1,
5547 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005548 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005549 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005550 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005551 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005552 return false;
5553 }
5554 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005555 const dex::TypeList* types1 = method1->GetParameterTypeList();
5556 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005557 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005558 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005559 ThrowSignatureMismatch(klass, super_klass, method1,
5560 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005561 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005562 return false;
5563 }
5564 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005565 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005566 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005567 ThrowSignatureMismatch(klass, super_klass, method1,
5568 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005569 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005570 return false;
5571 }
5572 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005573 }
5574 uint32_t num_types = types1->Size();
5575 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005576 ThrowSignatureMismatch(klass, super_klass, method1,
5577 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005578 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005579 return false;
5580 }
5581 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005582 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005583 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005584 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005585 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005586 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005587 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005588 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005589 return false;
5590 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005591 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005592 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005593 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005594 if (UNLIKELY(other_param_type == nullptr)) {
5595 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005596 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005597 return false;
5598 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005599 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005600 ThrowSignatureMismatch(klass, super_klass, method1,
5601 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5602 i,
David Sehr709b0702016-10-13 09:12:37 -07005603 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005604 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005605 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005606 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005607 return false;
5608 }
5609 }
5610 return true;
5611}
5612
5613
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005614bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005615 if (klass->IsInterface()) {
5616 return true;
5617 }
Ian Rogers151f2212014-05-06 11:27:27 -07005618 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005619 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005620 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005621 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005622 if (klass->HasSuperClass() &&
5623 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005624 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005625 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005626 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5627 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5628 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005629 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5630 klass,
5631 super_klass,
5632 m,
5633 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005634 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005635 return false;
5636 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005637 }
5638 }
5639 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005640 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005641 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5642 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5643 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005644 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005645 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5646 j, image_pointer_size_);
5647 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5648 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005649 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5650 klass,
5651 super_klass,
5652 m,
5653 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005654 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005655 return false;
5656 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005657 }
5658 }
5659 }
5660 }
5661 return true;
5662}
5663
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005664bool ClassLinker::EnsureInitialized(Thread* self,
5665 Handle<mirror::Class> c,
5666 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005667 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005668 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005669
Mathieu Chartier524507a2014-08-27 15:28:28 -07005670 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005671 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005672 return true;
5673 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005674 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5675 //
5676 // Ensure the bitstring is initialized before any of the class initialization
5677 // logic occurs. Once a class initializer starts running, objects can
5678 // escape into the heap and use the subtype checking code.
5679 //
5680 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5681 // can be used as a source for the IsSubClass check, and that all ancestors
5682 // of the class are Assigned (can be used as a target for IsSubClass check)
5683 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005684 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005685 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005686 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005687 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5688 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005689 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005690 if (!success) {
5691 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005692 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005693 }
5694 } else {
5695 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005696 }
5697 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005698}
5699
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005700void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5701 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005702 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005703 for (ArtField& field : new_class->GetIFields()) {
5704 if (field.GetDeclaringClass() == temp_class) {
5705 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005706 }
5707 }
5708
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005709 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005710 for (ArtField& field : new_class->GetSFields()) {
5711 if (field.GetDeclaringClass() == temp_class) {
5712 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005713 }
5714 }
5715
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005716 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005717 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005718 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005719 if (method.GetDeclaringClass() == temp_class) {
5720 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005721 }
5722 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005723
5724 // Make sure the remembered set and mod-union tables know that we updated some of the native
5725 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005726 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005727}
5728
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005729void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005730 CHECK(class_loader->GetAllocator() == nullptr);
5731 CHECK(class_loader->GetClassTable() == nullptr);
5732 Thread* const self = Thread::Current();
5733 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005734 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005735 // Create and set the class table.
5736 data.class_table = new ClassTable;
5737 class_loader->SetClassTable(data.class_table);
5738 // Create and set the linear allocator.
5739 data.allocator = Runtime::Current()->CreateLinearAlloc();
5740 class_loader->SetAllocator(data.allocator);
5741 // Add to the list so that we know to free the data later.
5742 class_loaders_.push_back(data);
5743}
5744
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005745ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005746 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005747 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005748 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005749 ClassTable* class_table = class_loader->GetClassTable();
5750 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005751 RegisterClassLoader(class_loader);
5752 class_table = class_loader->GetClassTable();
5753 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005754 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005755 return class_table;
5756}
5757
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005758ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005759 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005760}
5761
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005762static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005763 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005764 while (klass->HasSuperClass()) {
5765 klass = klass->GetSuperClass();
5766 if (klass->ShouldHaveImt()) {
5767 return klass->GetImt(pointer_size);
5768 }
5769 }
5770 return nullptr;
5771}
5772
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005773bool ClassLinker::LinkClass(Thread* self,
5774 const char* descriptor,
5775 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005776 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005777 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005778 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005779
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005780 if (!LinkSuperClass(klass)) {
5781 return false;
5782 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005783 ArtMethod* imt_data[ImTable::kSize];
5784 // If there are any new conflicts compared to super class.
5785 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005786 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005787 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005788 return false;
5789 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005790 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005791 return false;
5792 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005793 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005794 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005795 return false;
5796 }
5797 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005798 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005799
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005800 ImTable* imt = nullptr;
5801 if (klass->ShouldHaveImt()) {
5802 // If there are any new conflicts compared to the super class we can not make a copy. There
5803 // can be cases where both will have a conflict method at the same slot without having the same
5804 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5805 // will possibly create a table that is incorrect for either of the classes.
5806 // Same IMT with new_conflict does not happen very often.
5807 if (!new_conflict) {
5808 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5809 if (super_imt != nullptr) {
5810 bool imt_equals = true;
5811 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5812 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5813 }
5814 if (imt_equals) {
5815 imt = super_imt;
5816 }
5817 }
5818 }
5819 if (imt == nullptr) {
5820 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5821 imt = reinterpret_cast<ImTable*>(
5822 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5823 if (imt == nullptr) {
5824 return false;
5825 }
5826 imt->Populate(imt_data, image_pointer_size_);
5827 }
5828 }
5829
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005830 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5831 // We don't need to retire this class as it has no embedded tables or it was created the
5832 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005833 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005834
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005835 if (klass->ShouldHaveEmbeddedVTable()) {
5836 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005837 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005838 if (klass->ShouldHaveImt()) {
5839 klass->SetImt(imt, image_pointer_size_);
5840 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005841
5842 // Update CHA info based on whether we override methods.
5843 // Have to do this before setting the class as resolved which allows
5844 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005845 if (cha_ != nullptr) {
5846 cha_->UpdateAfterLoadingOf(klass);
5847 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005848
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005849 // This will notify waiters on klass that saw the not yet resolved
5850 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005851 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005852 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005853 } else {
5854 CHECK(!klass->IsResolved());
5855 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005856 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005857 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005858 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5859 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5860 // may not see any references to the target space and clean the card for a class if another
5861 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005862 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005863 klass->SetSFieldsPtrUnchecked(nullptr);
5864 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005865 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005866 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005867 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005868 return false;
5869 }
5870
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005871 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5872 ObjectLock<mirror::Class> lock(self, h_new_class);
5873 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005874
5875 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005876 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005877 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005878 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005879 const ObjPtr<mirror::Class> existing =
5880 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005881 if (class_loader != nullptr) {
5882 // We updated the class in the class table, perform the write barrier so that the GC knows
5883 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005884 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005885 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005886 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005887 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005888 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5889 }
5890 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005891
Mingyao Yang063fc772016-08-02 11:02:54 -07005892 // Update CHA info based on whether we override methods.
5893 // Have to do this before setting the class as resolved which allows
5894 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005895 if (cha_ != nullptr) {
5896 cha_->UpdateAfterLoadingOf(h_new_class);
5897 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005898
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005899 // This will notify waiters on temp class that saw the not yet resolved class in the
5900 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005901 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005902
Vladimir Marko2c64a832018-01-04 11:31:56 +00005903 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005904 // This will notify waiters on new_class that saw the not yet resolved
5905 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005906 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005907 // Return the new class.
5908 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005909 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005910 return true;
5911}
5912
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005913bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005914 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005915 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005916 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5917 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005918 // Check that a class does not inherit from itself directly.
5919 //
5920 // TODO: This is a cheap check to detect the straightforward case
5921 // of a class extending itself (b/28685551), but we should do a
5922 // proper cycle detection on loaded classes, to detect all cases
5923 // of class circularity errors (b/28830038).
5924 if (super_class_idx == class_def.class_idx_) {
5925 ThrowClassCircularityError(klass.Get(),
5926 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005927 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005928 return false;
5929 }
5930
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005931 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005932 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005933 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005934 return false;
5935 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005936 // Verify
5937 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005938 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005939 super_class->PrettyDescriptor().c_str(),
5940 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005941 return false;
5942 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005943 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005944 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005945 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005946 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005947 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005948 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005949 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005950 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005951 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005952 DCHECK(Thread::Current()->IsExceptionPending());
5953 return false;
5954 }
5955 // Verify
5956 if (!klass->CanAccess(interface)) {
5957 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005958 ThrowIllegalAccessError(klass.Get(),
5959 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005960 interface->PrettyDescriptor().c_str(),
5961 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005962 return false;
5963 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005964 }
5965 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005966 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005967 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005968 return true;
5969}
5970
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005971bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005972 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005973 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005974 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5975 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005976 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005977 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005978 return false;
5979 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005980 return true;
5981 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005982 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005983 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005984 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005985 return false;
5986 }
5987 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005988 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005989 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5990 return false;
5991 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005992 if (super->IsFinal()) {
5993 ThrowVerifyError(klass.Get(),
5994 "Superclass %s of %s is declared final",
5995 super->PrettyDescriptor().c_str(),
5996 klass->PrettyDescriptor().c_str());
5997 return false;
5998 }
5999 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006000 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006001 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006002 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006003 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006004 return false;
6005 }
6006 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006007 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006008 super->PrettyDescriptor().c_str(),
6009 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006010 return false;
6011 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006012
Brian Carlstromf3632832014-05-20 15:36:53 -07006013 // Inherit kAccClassIsFinalizable from the superclass in case this
6014 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006015 if (super->IsFinalizable()) {
6016 klass->SetFinalizable();
6017 }
6018
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006019 // Inherit class loader flag form super class.
6020 if (super->IsClassLoaderClass()) {
6021 klass->SetClassLoaderClass();
6022 }
6023
Elliott Hughes2da50362011-10-10 16:57:08 -07006024 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006025 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006026 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006027 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006028 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006029 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006030 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006031 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006032 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006033 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006034 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006035 return false;
6036 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006037
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006038 if (kIsDebugBuild) {
6039 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006040 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006041 CHECK(super->IsResolved());
6042 super = super->GetSuperClass();
6043 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006044 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006045 return true;
6046}
6047
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006048// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006049bool ClassLinker::LinkMethods(Thread* self,
6050 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006051 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006052 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006053 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006054 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006055 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6056 // need to have default methods be in the virtuals array of each class but we don't set that up
6057 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006058 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006059 // Link virtual methods then interface methods.
6060 // We set up the interface lookup table first because we need it to determine if we need to update
6061 // any vtable entries with new default method implementations.
6062 return SetupInterfaceLookupTable(self, klass, interfaces)
6063 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006064 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006065}
6066
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006067// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6068// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6069// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006070class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006071 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006072 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006073 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006074 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6075 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006076 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006077 }
6078
6079 const char* GetName() {
6080 if (name_ == nullptr) {
6081 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6082 }
6083 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006084 }
6085
Mathieu Chartiere401d142015-04-22 13:56:20 -07006086 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006087 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006088 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006089 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006090 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006091 if (dex_file_ == other_dex_file) {
6092 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6093 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006094 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006095 uint32_t other_name_len;
6096 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6097 &other_name_len);
6098 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6099 return false;
6100 }
6101 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6102 }
6103
6104 private:
6105 // Dex file for the method to compare against.
6106 const DexFile* const dex_file_;
6107 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006108 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006109 // Lazily computed name from the dex file's strings.
6110 const char* name_;
6111 // Lazily computed name length.
6112 uint32_t name_len_;
6113};
6114
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006115class LinkVirtualHashTable {
6116 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006117 LinkVirtualHashTable(Handle<mirror::Class> klass,
6118 size_t hash_size,
6119 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006120 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006121 : klass_(klass),
6122 hash_size_(hash_size),
6123 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006124 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006125 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6126 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006127
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006128 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006129 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6130 virtual_method_index, image_pointer_size_);
6131 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006132 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006133 uint32_t index = hash % hash_size_;
6134 // Linear probe until we have an empty slot.
6135 while (hash_table_[index] != invalid_index_) {
6136 if (++index == hash_size_) {
6137 index = 0;
6138 }
6139 }
6140 hash_table_[index] = virtual_method_index;
6141 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006142
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006143 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006144 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006145 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006146 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006147 size_t index = hash % hash_size_;
6148 while (true) {
6149 const uint32_t value = hash_table_[index];
6150 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6151 // the block and can safely assume not found.
6152 if (value == invalid_index_) {
6153 break;
6154 }
6155 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006156 ArtMethod* virtual_method =
6157 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6158 if (comparator->HasSameNameAndSignature(
6159 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006160 hash_table_[index] = removed_index_;
6161 return value;
6162 }
6163 }
6164 if (++index == hash_size_) {
6165 index = 0;
6166 }
6167 }
6168 return GetNotFoundIndex();
6169 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006170
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006171 static uint32_t GetNotFoundIndex() {
6172 return invalid_index_;
6173 }
6174
6175 private:
6176 static const uint32_t invalid_index_;
6177 static const uint32_t removed_index_;
6178
6179 Handle<mirror::Class> klass_;
6180 const size_t hash_size_;
6181 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006182 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006183};
6184
6185const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6186const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6187
Stephen Hines1ddd9132017-02-08 01:51:18 -08006188bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006189 Thread* self,
6190 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006191 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006192 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006193 if (klass->IsInterface()) {
6194 // No vtable.
6195 if (!IsUint<16>(num_virtual_methods)) {
6196 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6197 return false;
6198 }
6199 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006200 // Assign each method an IMT index and set the default flag.
6201 for (size_t i = 0; i < num_virtual_methods; ++i) {
6202 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6203 m->SetMethodIndex(i);
6204 if (!m->IsAbstract()) {
6205 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6206 has_defaults = true;
6207 }
6208 }
6209 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6210 // during initialization. This is a performance optimization. We could simply traverse the
6211 // virtual_methods_ array again during initialization.
6212 if (has_defaults) {
6213 klass->SetHasDefaultMethods();
6214 }
6215 return true;
6216 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006217 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6218 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006219 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006220 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006221 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006222 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006223 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006224 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006225 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006226 return false;
6227 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006228 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006229 vtable->SetElementPtrSize(
6230 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006231 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006232 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6233 // might give us new default methods). If no new interfaces then we can skip the rest since
6234 // the class cannot override any of the super-class's methods. This is required for
6235 // correctness since without it we might not update overridden default method vtable entries
6236 // correctly.
6237 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006238 klass->SetVTable(vtable.Get());
6239 return true;
6240 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006241 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006242 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Markoc524e9e2019-03-26 10:54:50 +00006243 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006244 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006245 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6246 // might give us new default methods). See comment above.
6247 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006248 klass->SetVTable(super_vtable);
6249 return true;
6250 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006251 vtable = hs.NewHandle(
6252 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006253 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006254 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006255 return false;
6256 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006257 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006258 // How the algorithm works:
6259 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6260 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6261 // method which has not been matched to a vtable method, and j if the virtual method at the
6262 // index overrode the super virtual method at index j.
6263 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6264 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6265 // the need for the initial vtable which we later shrink back down).
6266 // 3. Add non overridden methods to the end of the vtable.
6267 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006268 // + 1 so that even if we only have new default methods we will still be able to use this hash
6269 // table (i.e. it will never have 0 size).
6270 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006271 uint32_t* hash_table_ptr;
6272 std::unique_ptr<uint32_t[]> hash_heap_storage;
6273 if (hash_table_size <= kMaxStackHash) {
6274 hash_table_ptr = reinterpret_cast<uint32_t*>(
6275 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6276 } else {
6277 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6278 hash_table_ptr = hash_heap_storage.get();
6279 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006280 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006281 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006282 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006283 DCHECK(klass->GetVirtualMethodDuringLinking(
6284 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006285 hash_table.Add(i);
6286 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006287 // 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 -07006288 // the hash table.
6289 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006290 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006291 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006292 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6293 super_method->GetAccessFlags())) {
6294 // Continue on to the next method since this one is package private and canot be overridden.
6295 // Before Android 4.1, the package-private method super_method might have been incorrectly
6296 // overridden.
6297 continue;
6298 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006299 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006300 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006301 // We remove the method so that subsequent lookups will be faster by making the hash-map
6302 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006303 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6304 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006305 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6306 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006307 if (super_method->IsFinal()) {
6308 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6309 virtual_method->PrettyMethod().c_str(),
6310 super_method->GetDeclaringClassDescriptor());
6311 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006312 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006313 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6314 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006315 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006316 // We didn't directly override this method but we might through default methods...
6317 // Check for default method update.
6318 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006319 switch (FindDefaultMethodImplementation(self,
6320 super_method,
6321 klass,
6322 /*out*/&default_method)) {
6323 case DefaultMethodSearchResult::kDefaultConflict: {
6324 // A conflict was found looking for default methods. Note this (assuming it wasn't
6325 // pre-existing) in the translations map.
6326 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6327 // Don't generate another conflict method to reduce memory use as an optimization.
6328 default_translations->insert(
6329 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6330 }
6331 break;
6332 }
6333 case DefaultMethodSearchResult::kAbstractFound: {
6334 // No conflict but method is abstract.
6335 // We note that this vtable entry must be made abstract.
6336 if (UNLIKELY(!super_method->IsAbstract())) {
6337 default_translations->insert(
6338 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6339 }
6340 break;
6341 }
6342 case DefaultMethodSearchResult::kDefaultFound: {
6343 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6344 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6345 // Found a default method implementation that is new.
6346 // TODO Refactor this add default methods to virtuals here and not in
6347 // LinkInterfaceMethods maybe.
6348 // The problem is default methods might override previously present
6349 // default-method or miranda-method vtable entries from the superclass.
6350 // Unfortunately we need these to be entries in this class's virtuals. We do not
6351 // give these entries there until LinkInterfaceMethods so we pass this map around
6352 // to let it know which vtable entries need to be updated.
6353 // Make a note that vtable entry j must be updated, store what it needs to be updated
6354 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6355 // then.
6356 default_translations->insert(
6357 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006358 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6359 << " overridden by default "
6360 << default_method->PrettyMethod()
6361 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006362 }
6363 break;
6364 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006365 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006366 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006367 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006368 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006369 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006370 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006371 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006372 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6373 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006374 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006375 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006376 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006377 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006378 local_method->SetMethodIndex(actual_count);
6379 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006380 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006381 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006382 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006383 return false;
6384 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006385 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006386 CHECK_LE(actual_count, max_count);
6387 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006388 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006389 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006390 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006391 return false;
6392 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006393 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006394 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006395 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006396 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006397 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006398 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6399 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006400 return false;
6401 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006402 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006403 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006404 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006405 return false;
6406 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006407 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006408 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6409 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006410 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006411 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006412 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006413 }
6414 return true;
6415}
6416
Alex Light9139e002015-10-09 15:59:48 -07006417// Determine if the given iface has any subinterface in the given list that declares the method
6418// specified by 'target'.
6419//
6420// Arguments
6421// - self: The thread we are running on
6422// - target: A comparator that will match any method that overrides the method we are checking for
6423// - iftable: The iftable we are searching for an overriding method on.
6424// - ifstart: The index of the interface we are checking to see if anything overrides
6425// - iface: The interface we are checking to see if anything overrides.
6426// - image_pointer_size:
6427// The image pointer size.
6428//
6429// Returns
6430// - True: There is some method that matches the target comparator defined in an interface that
6431// is a subtype of iface.
6432// - False: There is no method that matches the target comparator in any interface that is a subtype
6433// of iface.
6434static bool ContainsOverridingMethodOf(Thread* self,
6435 MethodNameAndSignatureComparator& target,
6436 Handle<mirror::IfTable> iftable,
6437 size_t ifstart,
6438 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006439 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006440 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006441 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006442 DCHECK(iface != nullptr);
6443 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006444 DCHECK_GE(ifstart, 0u);
6445 DCHECK_LT(ifstart, iftable->Count());
6446 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6447 DCHECK(iface->IsInterface());
6448
6449 size_t iftable_count = iftable->Count();
6450 StackHandleScope<1> hs(self);
6451 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6452 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6453 // Skip ifstart since our current interface obviously cannot override itself.
6454 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006455 // Iterate through every method on this interface. The order does not matter.
6456 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006457 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006458 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006459 // Check if the i'th interface is a subtype of this one.
6460 if (iface->IsAssignableFrom(current_iface.Get())) {
6461 return true;
6462 }
6463 break;
6464 }
6465 }
6466 }
6467 return false;
6468}
6469
Alex Lighteb7c1442015-08-31 13:17:42 -07006470// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006471// out_default_method and returns kDefaultFound on success. If no default method was found return
6472// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6473// default_method conflict) it will return kDefaultConflict.
6474ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6475 Thread* self,
6476 ArtMethod* target_method,
6477 Handle<mirror::Class> klass,
6478 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006479 DCHECK(self != nullptr);
6480 DCHECK(target_method != nullptr);
6481 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006482
6483 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006484
6485 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6486 // table. This lets us walk the table backwards when searching for default methods. The first one
6487 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6488 // track of it and then continue checking all other interfaces, since we need to throw an error if
6489 // we encounter conflicting default method implementations (one is not a subtype of the other).
6490 //
6491 // The order of unrelated interfaces does not matter and is not defined.
6492 size_t iftable_count = klass->GetIfTableCount();
6493 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006494 // No interfaces. We have already reset out to null so just return kAbstractFound.
6495 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006496 }
6497
Alex Light9139e002015-10-09 15:59:48 -07006498 StackHandleScope<3> hs(self);
6499 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006500 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006501 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006502 MethodNameAndSignatureComparator target_name_comparator(
6503 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6504 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006505 for (size_t k = iftable_count; k != 0; ) {
6506 --k;
6507
Alex Lighteb7c1442015-08-31 13:17:42 -07006508 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006509
6510 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006511 // Iterate through every declared method on this interface. The order does not matter.
6512 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6513 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006514 // Skip abstract methods and methods with different names.
6515 if (current_method->IsAbstract() ||
6516 !target_name_comparator.HasSameNameAndSignature(
6517 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6518 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006519 } else if (!current_method->IsPublic()) {
6520 // The verifier should have caught the non-public method for dex version 37. Just warn and
6521 // skip it since this is from before default-methods so we don't really need to care that it
6522 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006523 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6524 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006525 << "This will be a fatal error in subsequent versions of android. "
6526 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006527 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006528 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006529 // We have multiple default impls of the same method. This is a potential default conflict.
6530 // We need to check if this possibly conflicting method is either a superclass of the chosen
6531 // default implementation or is overridden by a non-default interface method. In either case
6532 // there is no conflict.
6533 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6534 !ContainsOverridingMethodOf(self,
6535 target_name_comparator,
6536 iftable,
6537 k,
6538 iface,
6539 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006540 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006541 << current_method->PrettyMethod() << " and "
6542 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6543 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006544 *out_default_method = nullptr;
6545 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006546 } else {
6547 break; // Continue checking at the next interface.
6548 }
6549 } else {
Alex Light9139e002015-10-09 15:59:48 -07006550 // chosen_iface == null
6551 if (!ContainsOverridingMethodOf(self,
6552 target_name_comparator,
6553 iftable,
6554 k,
6555 iface,
6556 image_pointer_size_)) {
6557 // Don't set this as the chosen interface if something else is overriding it (because that
6558 // other interface would be potentially chosen instead if it was default). If the other
6559 // interface was abstract then we wouldn't select this interface as chosen anyway since
6560 // the abstract method masks it.
6561 *out_default_method = current_method;
6562 chosen_iface.Assign(iface.Get());
6563 // We should now finish traversing the graph to find if we have default methods that
6564 // conflict.
6565 } else {
David Sehr709b0702016-10-13 09:12:37 -07006566 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6567 << "' was "
6568 << "skipped because it was overridden by an abstract method in a "
6569 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006570 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006571 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006572 break;
6573 }
6574 }
Alex Light9139e002015-10-09 15:59:48 -07006575 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006576 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6577 << "' selected "
6578 << "as the implementation for '" << target_method->PrettyMethod()
6579 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006580 return DefaultMethodSearchResult::kDefaultFound;
6581 } else {
6582 return DefaultMethodSearchResult::kAbstractFound;
6583 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006584}
6585
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006586ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006587 ArtMethod* conflict_method,
6588 ArtMethod* interface_method,
6589 ArtMethod* method,
6590 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006591 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006592 Runtime* const runtime = Runtime::Current();
6593 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6594 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6595
6596 // Create a new entry if the existing one is the shared conflict method.
6597 ArtMethod* new_conflict_method = new_entry
6598 ? runtime->CreateImtConflictMethod(linear_alloc)
6599 : conflict_method;
6600
6601 // Allocate a new table. Note that we will leak this table at the next conflict,
6602 // but that's a tradeoff compared to making the table fixed size.
6603 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006604 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6605 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006606 if (data == nullptr) {
6607 LOG(ERROR) << "Failed to allocate conflict table";
6608 return conflict_method;
6609 }
6610 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6611 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006612 method,
6613 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006614
6615 // Do a fence to ensure threads see the data in the table before it is assigned
6616 // to the conflict method.
6617 // Note that there is a race in the presence of multiple threads and we may leak
6618 // memory from the LinearAlloc, but that's a tradeoff compared to using
6619 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006620 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006621 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006622 return new_conflict_method;
6623}
6624
Vladimir Marko921094a2017-01-12 18:37:06 +00006625bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6626 Handle<mirror::Class> klass,
6627 Handle<mirror::IfTable> iftable) {
6628 DCHECK(!klass->IsInterface());
6629 const bool has_superclass = klass->HasSuperClass();
6630 const bool extend_super_iftable = has_superclass;
6631 const size_t ifcount = klass->GetIfTableCount();
6632 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6633 for (size_t i = 0; i < ifcount; ++i) {
6634 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6635 if (num_methods > 0) {
6636 const bool is_super = i < super_ifcount;
6637 // This is an interface implemented by a super-class. Therefore we can just copy the method
6638 // array from the superclass.
6639 const bool super_interface = is_super && extend_super_iftable;
6640 ObjPtr<mirror::PointerArray> method_array;
6641 if (super_interface) {
6642 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6643 DCHECK(if_table != nullptr);
6644 DCHECK(if_table->GetMethodArray(i) != nullptr);
6645 // If we are working on a super interface, try extending the existing method array.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00006646 method_array = ObjPtr<mirror::PointerArray>::DownCast(
6647 if_table->GetMethodArray(i)->Clone(self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006648 } else {
6649 method_array = AllocPointerArray(self, num_methods);
6650 }
6651 if (UNLIKELY(method_array == nullptr)) {
6652 self->AssertPendingOOMException();
6653 return false;
6654 }
6655 iftable->SetMethodArray(i, method_array);
6656 }
6657 }
6658 return true;
6659}
6660
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006661void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6662 ArtMethod* imt_conflict_method,
6663 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006664 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006665 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006666 // Place method in imt if entry is empty, place conflict otherwise.
6667 if (*imt_ref == unimplemented_method) {
6668 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006669 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006670 // If we are not a conflict and we have the same signature and name as the imt
6671 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006672 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6673 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006674 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006675 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006676 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006677 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006678 *imt_ref = current_method;
6679 } else {
Alex Light9139e002015-10-09 15:59:48 -07006680 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006681 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006682 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006683 } else {
6684 // Place the default conflict method. Note that there may be an existing conflict
6685 // method in the IMT, but it could be one tailored to the super class, with a
6686 // specific ImtConflictTable.
6687 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006688 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006689 }
6690}
6691
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006692void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006693 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6694 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006695 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006696 Runtime* const runtime = Runtime::Current();
6697 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6698 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006699 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006700 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006701 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006702 FillIMTFromIfTable(klass->GetIfTable(),
6703 unimplemented_method,
6704 conflict_method,
6705 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006706 /*create_conflict_tables=*/true,
6707 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006708 &new_conflict,
6709 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006710 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006711 if (!klass->ShouldHaveImt()) {
6712 return;
6713 }
6714 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6715 // we can just use the same pointer.
6716 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006717 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006718 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6719 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6720 bool same = true;
6721 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6722 ArtMethod* method = imt_data[i];
6723 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6724 if (method != super_method) {
6725 bool is_conflict_table = method->IsRuntimeMethod() &&
6726 method != unimplemented_method &&
6727 method != conflict_method;
6728 // Verify conflict contents.
6729 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6730 super_method != unimplemented_method &&
6731 super_method != conflict_method;
6732 if (!is_conflict_table || !super_conflict_table) {
6733 same = false;
6734 } else {
6735 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6736 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6737 same = same && table1->Equals(table2, image_pointer_size_);
6738 }
6739 }
6740 }
6741 if (same) {
6742 imt = super_imt;
6743 }
6744 }
6745 if (imt == nullptr) {
6746 imt = klass->GetImt(image_pointer_size_);
6747 DCHECK(imt != nullptr);
6748 imt->Populate(imt_data, image_pointer_size_);
6749 } else {
6750 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006751 }
6752}
6753
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006754ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6755 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006756 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006757 void* data = linear_alloc->Alloc(Thread::Current(),
6758 ImtConflictTable::ComputeSize(count,
6759 image_pointer_size));
6760 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6761}
6762
6763ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6764 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6765}
6766
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006767void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006768 ArtMethod* unimplemented_method,
6769 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006770 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006771 bool create_conflict_tables,
6772 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006773 /*out*/bool* new_conflict,
6774 /*out*/ArtMethod** imt) {
6775 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006776 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006777 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006778 const size_t num_virtuals = interface->NumVirtualMethods();
6779 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6780 // Virtual methods can be larger than the if table methods if there are default methods.
6781 DCHECK_GE(num_virtuals, method_array_count);
6782 if (kIsDebugBuild) {
6783 if (klass->IsInterface()) {
6784 DCHECK_EQ(method_array_count, 0u);
6785 } else {
6786 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6787 }
6788 }
6789 if (method_array_count == 0) {
6790 continue;
6791 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006792 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006793 for (size_t j = 0; j < method_array_count; ++j) {
6794 ArtMethod* implementation_method =
6795 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6796 if (ignore_copied_methods && implementation_method->IsCopied()) {
6797 continue;
6798 }
6799 DCHECK(implementation_method != nullptr);
6800 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6801 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6802 // or interface methods in the IMT here they will not create extra conflicts since we compare
6803 // names and signatures in SetIMTRef.
6804 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006805 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006806
6807 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6808 // the same implementation method, keep track of this to avoid creating a conflict table in
6809 // this case.
6810
6811 // Conflict table size for each IMT slot.
6812 ++conflict_counts[imt_index];
6813
6814 SetIMTRef(unimplemented_method,
6815 imt_conflict_method,
6816 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006817 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006818 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006819 }
6820 }
6821
6822 if (create_conflict_tables) {
6823 // Create the conflict tables.
6824 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006825 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006826 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006827 if (imt[i] == imt_conflict_method) {
6828 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6829 if (new_table != nullptr) {
6830 ArtMethod* new_conflict_method =
6831 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6832 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6833 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006834 } else {
6835 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006836 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006837 }
6838 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006839 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006840 }
6841 }
6842
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006843 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006844 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006845 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6846 // Virtual methods can be larger than the if table methods if there are default methods.
6847 if (method_array_count == 0) {
6848 continue;
6849 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006850 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006851 for (size_t j = 0; j < method_array_count; ++j) {
6852 ArtMethod* implementation_method =
6853 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6854 if (ignore_copied_methods && implementation_method->IsCopied()) {
6855 continue;
6856 }
6857 DCHECK(implementation_method != nullptr);
6858 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006859 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006860 if (!imt[imt_index]->IsRuntimeMethod() ||
6861 imt[imt_index] == unimplemented_method ||
6862 imt[imt_index] == imt_conflict_method) {
6863 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006864 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006865 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6866 const size_t num_entries = table->NumEntries(image_pointer_size_);
6867 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6868 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006869 }
6870 }
6871 }
6872}
6873
Alex Lighteb7c1442015-08-31 13:17:42 -07006874// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6875// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006876static bool NotSubinterfaceOfAny(
6877 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6878 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006879 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006880 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006881 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006882 for (ObjPtr<mirror::Class> c : classes) {
6883 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006884 return false;
6885 }
6886 }
6887 return true;
6888}
6889
6890// Fills in and flattens the interface inheritance hierarchy.
6891//
6892// By the end of this function all interfaces in the transitive closure of to_process are added to
6893// the iftable and every interface precedes all of its sub-interfaces in this list.
6894//
6895// all I, J: Interface | I <: J implies J precedes I
6896//
6897// (note A <: B means that A is a subtype of B)
6898//
6899// This returns the total number of items in the iftable. The iftable might be resized down after
6900// this call.
6901//
6902// We order this backwards so that we do not need to reorder superclass interfaces when new
6903// interfaces are added in subclass's interface tables.
6904//
6905// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6906// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6907// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6908// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006909static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006910 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006911 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006912 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006913 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006914 // This is the set of all class's already in the iftable. Used to make checking if a class has
6915 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006916 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006917 // The first super_ifcount elements are from the superclass. We note that they are already added.
6918 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006919 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006920 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6921 classes_in_iftable.insert(iface);
6922 }
6923 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006924 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006925 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6926 // At this point in the loop current-iface-list has the invariant that:
6927 // for every pair of interfaces I,J within it:
6928 // if index_of(I) < index_of(J) then I is not a subtype of J
6929
6930 // If we have already seen this element then all of its super-interfaces must already be in the
6931 // current-iface-list so we can skip adding it.
6932 if (!ContainsElement(classes_in_iftable, interface)) {
6933 // We haven't seen this interface so add all of its super-interfaces onto the
6934 // current-iface-list, skipping those already on it.
6935 int32_t ifcount = interface->GetIfTableCount();
6936 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006937 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006938 if (!ContainsElement(classes_in_iftable, super_interface)) {
6939 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6940 classes_in_iftable.insert(super_interface);
6941 iftable->SetInterface(filled_ifcount, super_interface);
6942 filled_ifcount++;
6943 }
6944 }
6945 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6946 // Place this interface onto the current-iface-list after all of its super-interfaces.
6947 classes_in_iftable.insert(interface);
6948 iftable->SetInterface(filled_ifcount, interface);
6949 filled_ifcount++;
6950 } else if (kIsDebugBuild) {
6951 // Check all super-interfaces are already in the list.
6952 int32_t ifcount = interface->GetIfTableCount();
6953 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006954 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006955 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006956 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6957 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006958 }
6959 }
6960 }
6961 if (kIsDebugBuild) {
6962 // Check that the iftable is ordered correctly.
6963 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006964 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006965 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006966 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006967 // !(if_a <: if_b)
6968 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006969 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6970 << ") extends "
6971 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006972 << "interface list.";
6973 }
6974 }
6975 }
6976 return filled_ifcount;
6977}
6978
6979bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6980 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6981 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006982 const bool has_superclass = klass->HasSuperClass();
6983 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006984 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006985 const size_t num_interfaces =
6986 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006987 if (num_interfaces == 0) {
6988 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006989 if (LIKELY(has_superclass)) {
6990 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6991 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006992 // Class implements no interfaces.
6993 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006994 return true;
6995 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006996 // Class implements same interfaces as parent, are any of these not marker interfaces?
6997 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006998 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006999 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007000 if (super_iftable->GetMethodArrayCount(i) > 0) {
7001 has_non_marker_interface = true;
7002 break;
7003 }
7004 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007005 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007006 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007007 klass->SetIfTable(super_iftable);
7008 return true;
7009 }
7010 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007011 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007012 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007013 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007014 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007015 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007016 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007017 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007018 if (UNLIKELY(!interface->IsInterface())) {
7019 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007020 ThrowIncompatibleClassChangeError(klass.Get(),
7021 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007022 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007023 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7024 return false;
7025 }
7026 ifcount += interface->GetIfTableCount();
7027 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007028 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007029 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007030 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007031 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007032 return false;
7033 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007034 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007035 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007036 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007037 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007038 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007039 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007040 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007041 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007042
7043 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7044 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7045 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007046 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007047
7048 size_t new_ifcount;
7049 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007050 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007051 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007052 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007053 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007054 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007055 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007056 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007057
7058 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007059 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007060
Ian Rogers7b078e82014-09-10 14:44:24 -07007061 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007062
Ian Rogersb52b01a2012-01-12 17:01:38 -08007063 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007064 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007065 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007066 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007067 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007068 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007069 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007070 return false;
7071 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007072 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007073 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007074 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007075 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007076 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007077 return true;
7078}
7079
Alex Light1f3925d2016-09-07 12:04:20 -07007080// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7081// of methods must be unique.
7082static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7083 return nullptr;
7084}
7085
7086template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007087static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007088 const ScopedArenaVector<ArtMethod*>& list,
7089 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007090 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007091 for (ArtMethod* method : list) {
7092 if (cmp.HasSameNameAndSignature(method)) {
7093 return method;
7094 }
7095 }
Alex Light1f3925d2016-09-07 12:04:20 -07007096 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007097}
7098
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007099namespace {
7100
Alex Light1f3925d2016-09-07 12:04:20 -07007101// Check that all vtable entries are present in this class's virtuals or are the same as a
7102// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007103void CheckClassOwnsVTableEntries(Thread* self,
7104 Handle<mirror::Class> klass,
7105 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007106 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007107 StackHandleScope<2> hs(self);
7108 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007109 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007110 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007111 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007112 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7113 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7114 CHECK(m != nullptr);
7115
Alex Lighta41a30782017-03-29 11:33:19 -07007116 if (m->GetMethodIndexDuringLinking() != i) {
7117 LOG(WARNING) << m->PrettyMethod()
7118 << " has an unexpected method index for its spot in the vtable for class"
7119 << klass->PrettyClass();
7120 }
Alex Lighte64300b2015-12-15 15:02:47 -08007121 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7122 auto is_same_method = [m] (const ArtMethod& meth) {
7123 return &meth == m;
7124 };
Alex Light3f980532017-03-17 15:10:32 -07007125 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7126 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7127 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7128 << klass->PrettyClass() << " or any of its superclasses!";
7129 }
Alex Lighte64300b2015-12-15 15:02:47 -08007130 }
7131}
7132
Alex Light1f3925d2016-09-07 12:04:20 -07007133// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7134// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007135template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007136void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007137 REQUIRES_SHARED(Locks::mutator_lock_) {
7138 StackHandleScope<1> hs(self);
7139 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7140 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007141
7142 // Observations:
7143 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7144 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7145 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7146 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7147 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7148 // * The single-pass algorithm will trade memory for speed, but that is OK.
7149
7150 CHECK_GT(num_entries, 0);
7151
7152 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7153 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7154 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7155 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7156 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7157 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7158 << m2->PrettyMethod() << " (0x" << std::hex
7159 << reinterpret_cast<uintptr_t>(m2) << ")";
7160 };
7161 struct BaseHashType {
7162 static size_t HashCombine(size_t seed, size_t val) {
7163 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7164 }
7165 };
7166
7167 // Check assuming all entries come from the same dex file.
7168 {
7169 // Find the first interesting method and its dex file.
7170 int32_t start = 0;
7171 for (; start < num_entries; ++start) {
7172 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7173 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7174 // maybe).
7175 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7176 vtable_entry->GetAccessFlags())) {
7177 continue;
7178 }
7179 break;
7180 }
7181 if (start == num_entries) {
7182 return;
7183 }
7184 const DexFile* dex_file =
7185 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7186 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7187
7188 // Helper function to avoid logging if we have to run the cross-file checks.
7189 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7190 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7191 using PairType = std::pair<uint32_t, uint16_t>;
7192 struct PairHash : BaseHashType {
7193 size_t operator()(const PairType& key) const {
7194 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7195 }
7196 };
7197 std::unordered_map<PairType, int32_t, PairHash> seen;
7198 seen.reserve(2 * num_entries);
7199 bool need_slow_path = false;
7200 bool found_dup = false;
7201 for (int i = start; i < num_entries; ++i) {
7202 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7203 // wrt/ kPointerSize.
7204 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7205 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7206 vtable_entry->GetAccessFlags())) {
7207 continue;
7208 }
7209 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7210 if (dex_file != m->GetDexFile()) {
7211 need_slow_path = true;
7212 break;
7213 }
7214 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7215 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7216 auto it = seen.find(pair);
7217 if (it != seen.end()) {
7218 found_dup = true;
7219 if (log_warn) {
7220 log_fn(it->second, i);
7221 }
7222 } else {
7223 seen.emplace(pair, i);
7224 }
7225 }
7226 return std::make_pair(need_slow_path, found_dup);
7227 };
7228 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7229 if (!result.first) {
7230 if (result.second) {
7231 check_fn(/* log_warn= */ true);
7232 }
7233 return;
7234 }
7235 }
7236
7237 // Need to check across dex files.
7238 struct Entry {
7239 size_t cached_hash = 0;
7240 const char* name = nullptr;
7241 Signature signature = Signature::NoSignature();
7242 uint32_t name_len = 0;
7243
7244 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7245 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7246 signature(dex_file->GetMethodSignature(mid)) {
7247 }
7248
7249 bool operator==(const Entry& other) const {
7250 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7251 return false;
7252 }
7253 return signature == other.signature;
7254 }
7255 };
7256 struct EntryHash {
7257 size_t operator()(const Entry& key) const {
7258 return key.cached_hash;
7259 }
7260 };
7261 std::unordered_map<Entry, int32_t, EntryHash> map;
7262 for (int32_t i = 0; i < num_entries; ++i) {
7263 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7264 // wrt/ kPointerSize.
7265 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7266 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7267 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007268 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7269 vtable_entry->GetAccessFlags())) {
7270 continue;
7271 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007272 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7273 const DexFile* dex_file = m->GetDexFile();
7274 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7275
7276 Entry e(dex_file, mid);
7277
7278 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7279 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7280 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7281 sig_hash);
7282
7283 auto it = map.find(e);
7284 if (it != map.end()) {
7285 log_fn(it->second, i);
7286 } else {
7287 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007288 }
7289 }
7290}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007291
7292void CheckVTableHasNoDuplicates(Thread* self,
7293 Handle<mirror::Class> klass,
7294 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007295 REQUIRES_SHARED(Locks::mutator_lock_) {
7296 switch (pointer_size) {
7297 case PointerSize::k64:
7298 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7299 break;
7300 case PointerSize::k32:
7301 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7302 break;
7303 }
7304}
Alex Light1f3925d2016-09-07 12:04:20 -07007305
7306static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7307 REQUIRES_SHARED(Locks::mutator_lock_) {
7308 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7309 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7310}
7311
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007312} // namespace
7313
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007314void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7315 ArtMethod* unimplemented_method,
7316 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007317 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007318 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007319 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007320 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007321 if (super_class->ShouldHaveImt()) {
7322 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7323 for (size_t i = 0; i < ImTable::kSize; ++i) {
7324 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007325 }
7326 } else {
7327 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007328 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007329 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007330 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007331 FillIMTFromIfTable(if_table,
7332 unimplemented_method,
7333 imt_conflict_method,
7334 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007335 /*create_conflict_tables=*/false,
7336 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007337 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007338 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007339 }
7340 }
7341}
7342
Vladimir Marko921094a2017-01-12 18:37:06 +00007343class ClassLinker::LinkInterfaceMethodsHelper {
7344 public:
7345 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7346 Handle<mirror::Class> klass,
7347 Thread* self,
7348 Runtime* runtime)
7349 : class_linker_(class_linker),
7350 klass_(klass),
7351 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7352 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7353 self_(self),
7354 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7355 allocator_(&stack_),
7356 default_conflict_methods_(allocator_.Adapter()),
7357 overriding_default_conflict_methods_(allocator_.Adapter()),
7358 miranda_methods_(allocator_.Adapter()),
7359 default_methods_(allocator_.Adapter()),
7360 overriding_default_methods_(allocator_.Adapter()),
7361 move_table_(allocator_.Adapter()) {
7362 }
7363
7364 ArtMethod* FindMethod(ArtMethod* interface_method,
7365 MethodNameAndSignatureComparator& interface_name_comparator,
7366 ArtMethod* vtable_impl)
7367 REQUIRES_SHARED(Locks::mutator_lock_);
7368
7369 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7370 MethodNameAndSignatureComparator& interface_name_comparator)
7371 REQUIRES_SHARED(Locks::mutator_lock_);
7372
7373 bool HasNewVirtuals() const {
7374 return !(miranda_methods_.empty() &&
7375 default_methods_.empty() &&
7376 overriding_default_methods_.empty() &&
7377 overriding_default_conflict_methods_.empty() &&
7378 default_conflict_methods_.empty());
7379 }
7380
7381 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7382
7383 ObjPtr<mirror::PointerArray> UpdateVtable(
7384 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7385 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7386
7387 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7388
7389 void UpdateIMT(ArtMethod** out_imt);
7390
7391 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7392 if (kIsDebugBuild) {
7393 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7394 // Check that there are no stale methods are in the dex cache array.
7395 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7396 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007397 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7398 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007399 CHECK(move_table_.find(m) == move_table_.end() ||
7400 // The original versions of copied methods will still be present so allow those too.
7401 // Note that if the first check passes this might fail to GetDeclaringClass().
7402 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7403 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7404 [m] (ArtMethod& meth) {
7405 return &meth == m;
7406 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7407 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7408 }
7409 }
7410 }
7411
7412 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7413 LengthPrefixedArray<ArtMethod>* methods) {
7414 if (kIsDebugBuild) {
7415 CHECK(methods != nullptr);
7416 // Put some random garbage in old methods to help find stale pointers.
7417 if (methods != old_methods && old_methods != nullptr) {
7418 // Need to make sure the GC is not running since it could be scanning the methods we are
7419 // about to overwrite.
7420 ScopedThreadStateChange tsc(self_, kSuspended);
7421 gc::ScopedGCCriticalSection gcs(self_,
7422 gc::kGcCauseClassLinker,
7423 gc::kCollectorTypeClassLinker);
7424 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7425 method_size_,
7426 method_alignment_);
7427 memset(old_methods, 0xFEu, old_size);
7428 }
7429 }
7430 }
7431
7432 private:
7433 size_t NumberOfNewVirtuals() const {
7434 return miranda_methods_.size() +
7435 default_methods_.size() +
7436 overriding_default_conflict_methods_.size() +
7437 overriding_default_methods_.size() +
7438 default_conflict_methods_.size();
7439 }
7440
7441 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7442 return !klass_->IsInterface();
7443 }
7444
7445 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7446 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7447 << "Interfaces should only have default-conflict methods appended to them.";
7448 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7449 << miranda_methods_.size()
7450 << " default_methods=" << default_methods_.size()
7451 << " overriding_default_methods=" << overriding_default_methods_.size()
7452 << " default_conflict_methods=" << default_conflict_methods_.size()
7453 << " overriding_default_conflict_methods="
7454 << overriding_default_conflict_methods_.size();
7455 }
7456
7457 ClassLinker* class_linker_;
7458 Handle<mirror::Class> klass_;
7459 size_t method_alignment_;
7460 size_t method_size_;
7461 Thread* const self_;
7462
7463 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7464 // the virtual methods array.
7465 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7466 // during cross compilation.
7467 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7468 ArenaStack stack_;
7469 ScopedArenaAllocator allocator_;
7470
7471 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7472 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7473 ScopedArenaVector<ArtMethod*> miranda_methods_;
7474 ScopedArenaVector<ArtMethod*> default_methods_;
7475 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7476
7477 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7478};
7479
7480ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7481 ArtMethod* interface_method,
7482 MethodNameAndSignatureComparator& interface_name_comparator,
7483 ArtMethod* vtable_impl) {
7484 ArtMethod* current_method = nullptr;
7485 switch (class_linker_->FindDefaultMethodImplementation(self_,
7486 interface_method,
7487 klass_,
7488 /*out*/&current_method)) {
7489 case DefaultMethodSearchResult::kDefaultConflict: {
7490 // Default method conflict.
7491 DCHECK(current_method == nullptr);
7492 ArtMethod* default_conflict_method = nullptr;
7493 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7494 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7495 default_conflict_method = vtable_impl;
7496 } else {
7497 // See if we already have a conflict method for this method.
7498 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7499 interface_name_comparator,
7500 default_conflict_methods_,
7501 overriding_default_conflict_methods_);
7502 if (LIKELY(preexisting_conflict != nullptr)) {
7503 // We already have another conflict we can reuse.
7504 default_conflict_method = preexisting_conflict;
7505 } else {
7506 // Note that we do this even if we are an interface since we need to create this and
7507 // cannot reuse another classes.
7508 // Create a new conflict method for this to use.
7509 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7510 new(default_conflict_method) ArtMethod(interface_method,
7511 class_linker_->GetImagePointerSize());
7512 if (vtable_impl == nullptr) {
7513 // Save the conflict method. We need to add it to the vtable.
7514 default_conflict_methods_.push_back(default_conflict_method);
7515 } else {
7516 // Save the conflict method but it is already in the vtable.
7517 overriding_default_conflict_methods_.push_back(default_conflict_method);
7518 }
7519 }
7520 }
7521 current_method = default_conflict_method;
7522 break;
7523 } // case kDefaultConflict
7524 case DefaultMethodSearchResult::kDefaultFound: {
7525 DCHECK(current_method != nullptr);
7526 // Found a default method.
7527 if (vtable_impl != nullptr &&
7528 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7529 // We found a default method but it was the same one we already have from our
7530 // superclass. Don't bother adding it to our vtable again.
7531 current_method = vtable_impl;
7532 } else if (LIKELY(FillTables())) {
7533 // Interfaces don't need to copy default methods since they don't have vtables.
7534 // Only record this default method if it is new to save space.
7535 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7536 // would make lookup for interface super much faster. (We would only need to scan
7537 // the iftable to find if there is a NSME or AME.)
7538 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7539 default_methods_,
7540 overriding_default_methods_);
7541 if (old == nullptr) {
7542 // We found a default method implementation and there were no conflicts.
7543 if (vtable_impl == nullptr) {
7544 // Save the default method. We need to add it to the vtable.
7545 default_methods_.push_back(current_method);
7546 } else {
7547 // Save the default method but it is already in the vtable.
7548 overriding_default_methods_.push_back(current_method);
7549 }
7550 } else {
7551 CHECK(old == current_method) << "Multiple default implementations selected!";
7552 }
7553 }
7554 break;
7555 } // case kDefaultFound
7556 case DefaultMethodSearchResult::kAbstractFound: {
7557 DCHECK(current_method == nullptr);
7558 // Abstract method masks all defaults.
7559 if (vtable_impl != nullptr &&
7560 vtable_impl->IsAbstract() &&
7561 !vtable_impl->IsDefaultConflicting()) {
7562 // We need to make this an abstract method but the version in the vtable already is so
7563 // don't do anything.
7564 current_method = vtable_impl;
7565 }
7566 break;
7567 } // case kAbstractFound
7568 }
7569 return current_method;
7570}
7571
7572ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7573 ArtMethod* interface_method,
7574 MethodNameAndSignatureComparator& interface_name_comparator) {
7575 // Find out if there is already a miranda method we can use.
7576 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7577 miranda_methods_);
7578 if (miranda_method == nullptr) {
7579 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7580 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7581 CHECK(miranda_method != nullptr);
7582 // Point the interface table at a phantom slot.
7583 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7584 miranda_methods_.push_back(miranda_method);
7585 }
7586 return miranda_method;
7587}
7588
7589void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7590 LogNewVirtuals();
7591
7592 const size_t old_method_count = klass_->NumMethods();
7593 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7594 DCHECK_NE(old_method_count, new_method_count);
7595
7596 // Attempt to realloc to save RAM if possible.
7597 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7598 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7599 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7600 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7601 // CopyFrom has internal read barriers.
7602 //
7603 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7604 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7605 method_size_,
7606 method_alignment_);
7607 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7608 method_size_,
7609 method_alignment_);
7610 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7611 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007612 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007613 self_, old_methods, old_methods_ptr_size, new_size));
7614 CHECK(methods != nullptr); // Native allocation failure aborts.
7615
7616 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7617 if (methods != old_methods) {
7618 // Maps from heap allocated miranda method to linear alloc miranda method.
7619 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7620 // Copy over the old methods.
7621 for (auto& m : klass_->GetMethods(pointer_size)) {
7622 move_table_.emplace(&m, &*out);
7623 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7624 // barriers when it copies.
7625 out->CopyFrom(&m, pointer_size);
7626 ++out;
7627 }
7628 }
7629 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7630 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7631 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007632 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7633 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007634 ArtMethod& new_method = *out;
7635 new_method.CopyFrom(mir_method, pointer_size);
7636 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7637 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7638 << "Miranda method should be abstract!";
7639 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007640 // Update the entry in the method array, as the array will be used for future lookups,
7641 // where thread suspension is allowed.
7642 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7643 // would not see them.
7644 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007645 ++out;
7646 }
7647 // We need to copy the default methods into our own method table since the runtime requires that
7648 // every method on a class's vtable be in that respective class's virtual method table.
7649 // NOTE This means that two classes might have the same implementation of a method from the same
7650 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7651 // default method found on a class with one found on the declaring interface directly and must
7652 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007653 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7654 &overriding_default_methods_}) {
7655 for (size_t i = 0; i < methods_vec->size(); ++i) {
7656 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007657 ArtMethod& new_method = *out;
7658 new_method.CopyFrom(def_method, pointer_size);
7659 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7660 // verified yet it shouldn't have methods that are skipping access checks.
7661 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7662 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007663 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007664 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7665 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7666 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7667 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007668 // Update the entry in the method array, as the array will be used for future lookups,
7669 // where thread suspension is allowed.
7670 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7671 // would not see them.
7672 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007673 ++out;
7674 }
7675 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007676 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7677 &overriding_default_conflict_methods_}) {
7678 for (size_t i = 0; i < methods_vec->size(); ++i) {
7679 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007680 ArtMethod& new_method = *out;
7681 new_method.CopyFrom(conf_method, pointer_size);
7682 // This is a type of default method (there are default method impls, just a conflict) so
7683 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7684 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7685 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007686 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7687 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007688 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007689 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007690 constexpr uint32_t kMaskFlags =
7691 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007692 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7693 DCHECK(new_method.IsDefaultConflicting());
7694 // The actual method might or might not be marked abstract since we just copied it from a
7695 // (possibly default) interface method. We need to set it entry point to be the bridge so
7696 // that the compiler will not invoke the implementation of whatever method we copied from.
7697 EnsureThrowsInvocationError(class_linker_, &new_method);
7698 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007699 // Update the entry in the method array, as the array will be used for future lookups,
7700 // where thread suspension is allowed.
7701 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7702 // would not see them.
7703 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007704 ++out;
7705 }
7706 }
7707 methods->SetSize(new_method_count);
7708 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7709}
7710
7711ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7712 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7713 ObjPtr<mirror::PointerArray> old_vtable) {
7714 // Update the vtable to the new method structures. We can skip this for interfaces since they
7715 // do not have vtables.
7716 const size_t old_vtable_count = old_vtable->GetLength();
7717 const size_t new_vtable_count = old_vtable_count +
7718 miranda_methods_.size() +
7719 default_methods_.size() +
7720 default_conflict_methods_.size();
7721
7722 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007723 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007724 if (UNLIKELY(vtable == nullptr)) {
7725 self_->AssertPendingOOMException();
7726 return nullptr;
7727 }
7728
7729 size_t vtable_pos = old_vtable_count;
7730 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7731 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7732 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7733 default_conflict_methods_,
7734 miranda_methods_}) {
7735 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007736 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007737 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7738 // fields are references into the dex file the method was defined in. Since the ArtMethod
7739 // does not store that information it uses declaring_class_->dex_cache_.
7740 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7741 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7742 ++vtable_pos;
7743 }
7744 }
7745 DCHECK_EQ(vtable_pos, new_vtable_count);
7746
7747 // Update old vtable methods. We use the default_translations map to figure out what each
7748 // vtable entry should be updated to, if they need to be at all.
7749 for (size_t i = 0; i < old_vtable_count; ++i) {
7750 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7751 // Try and find what we need to change this method to.
7752 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007753 if (translation_it != default_translations.end()) {
7754 if (translation_it->second.IsInConflict()) {
7755 // Find which conflict method we are to use for this method.
7756 MethodNameAndSignatureComparator old_method_comparator(
7757 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7758 // We only need to look through overriding_default_conflict_methods since this is an
7759 // overridden method we are fixing up here.
7760 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7761 old_method_comparator, overriding_default_conflict_methods_);
7762 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7763 translated_method = new_conflict_method;
7764 } else if (translation_it->second.IsAbstract()) {
7765 // Find which miranda method we are to use for this method.
7766 MethodNameAndSignatureComparator old_method_comparator(
7767 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7768 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7769 miranda_methods_);
7770 DCHECK(miranda_method != nullptr);
7771 translated_method = miranda_method;
7772 } else {
7773 // Normal default method (changed from an older default or abstract interface method).
7774 DCHECK(translation_it->second.IsTranslation());
7775 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007776 auto it = move_table_.find(translated_method);
7777 DCHECK(it != move_table_.end());
7778 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007779 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007780 } else {
7781 auto it = move_table_.find(translated_method);
7782 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007783 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007784
7785 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007786 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007787 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007788 if (kIsDebugBuild) {
7789 auto* methods = klass_->GetMethodsPtr();
7790 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007791 reinterpret_cast<uintptr_t>(translated_method));
7792 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007793 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7794 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007795 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007796 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007797 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007798 }
7799 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007800 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007801 return vtable;
7802}
7803
7804void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7805 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7806 const size_t ifcount = klass_->GetIfTableCount();
7807 // Go fix up all the stale iftable pointers.
7808 for (size_t i = 0; i < ifcount; ++i) {
7809 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007810 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7811 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007812 DCHECK(m != nullptr) << klass_->PrettyClass();
7813 auto it = move_table_.find(m);
7814 if (it != move_table_.end()) {
7815 auto* new_m = it->second;
7816 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7817 method_array->SetElementPtrSize(j, new_m, pointer_size);
7818 }
7819 }
7820 }
7821}
7822
7823void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7824 // Fix up IMT next.
7825 for (size_t i = 0; i < ImTable::kSize; ++i) {
7826 auto it = move_table_.find(out_imt[i]);
7827 if (it != move_table_.end()) {
7828 out_imt[i] = it->second;
7829 }
7830 }
7831}
7832
Alex Light705ad492015-09-21 11:36:30 -07007833// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007834bool ClassLinker::LinkInterfaceMethods(
7835 Thread* self,
7836 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007837 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007838 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007839 ArtMethod** out_imt) {
7840 StackHandleScope<3> hs(self);
7841 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007842
7843 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007844 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007845 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007846 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007847 const size_t ifcount = klass->GetIfTableCount();
7848
Vladimir Marko921094a2017-01-12 18:37:06 +00007849 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007850
7851 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7852 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007853 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007854 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007855 const bool extend_super_iftable = has_superclass;
7856 if (has_superclass && fill_tables) {
7857 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007858 unimplemented_method,
7859 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007860 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007861 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007862 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007863 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7864 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007865 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007866 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7867 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007868 }
7869 }
7870
Vladimir Marko921094a2017-01-12 18:37:06 +00007871 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7872
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007873 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007874 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007875 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7876 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7877 // they will already be null. This has the additional benefit that the declarer of a miranda
7878 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007879 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007880 --i;
Alex Light9139e002015-10-09 15:59:48 -07007881 DCHECK_LT(i, ifcount);
7882
Alex Light705ad492015-09-21 11:36:30 -07007883 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007884 if (num_methods > 0) {
7885 StackHandleScope<2> hs2(self);
7886 const bool is_super = i < super_ifcount;
7887 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007888 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7889 // conflict methods. Just set this as nullptr in those cases.
7890 Handle<mirror::PointerArray> method_array(fill_tables
7891 ? hs2.NewHandle(iftable->GetMethodArray(i))
7892 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007893
Alex Lighte64300b2015-12-15 15:02:47 -08007894 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007895 ScopedNullHandle<mirror::PointerArray> null_handle;
7896 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007897 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007898
Alex Light9139e002015-10-09 15:59:48 -07007899 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7900 // and confusing. Default methods should always look through all the superclasses
7901 // because they are the last choice of an implementation. We get around this by looking
7902 // at the super-classes iftable methods (copied into method_array previously) when we are
7903 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007904 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007905 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007906 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007907 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007908 using_virtuals = true;
7909 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7910 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007911 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007912 // For a new interface, however, we need the whole vtable in case a new
7913 // interface method is implemented in the whole superclass.
7914 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007915 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007916 input_vtable_array = vtable;
7917 input_array_length = input_vtable_array->GetLength();
7918 }
Alex Lighte64300b2015-12-15 15:02:47 -08007919
Alex Lighteb7c1442015-08-31 13:17:42 -07007920 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007921 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007922 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007923 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007924 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007925 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007926 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007927 // For each method listed in the interface's method list, find the
7928 // matching method in our class's method list. We want to favor the
7929 // subclass over the superclass, which just requires walking
7930 // back from the end of the vtable. (This only matters if the
7931 // superclass defines a private method and this class redefines
7932 // it -- otherwise it would use the same vtable slot. In .dex files
7933 // those don't end up in the virtual method table, so it shouldn't
7934 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007935 //
7936 // To find defaults we need to do the same but also go over interfaces.
7937 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007938 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007939 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007940 ArtMethod* vtable_method = using_virtuals ?
7941 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007942 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7943 ArtMethod* vtable_method_for_name_comparison =
7944 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007945 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007946 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007947 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007948 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7949 // allocations.
7950 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007951 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007952 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007953 vtable_method->PrettyMethod().c_str(),
7954 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007955 return false;
Alex Light9139e002015-10-09 15:59:48 -07007956 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007957 // We might have a newer, better, default method for this, so we just skip it. If we
7958 // are still using this we will select it again when scanning for default methods. To
7959 // obviate the need to copy the method again we will make a note that we already found
7960 // a default here.
7961 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007962 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007963 break;
7964 } else {
7965 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007966 if (LIKELY(fill_tables)) {
7967 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7968 // Place method in imt if entry is empty, place conflict otherwise.
7969 SetIMTRef(unimplemented_method,
7970 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007971 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007972 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007973 /*out*/imt_ptr);
7974 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007975 break;
7976 }
7977 }
Alex Light9139e002015-10-09 15:59:48 -07007978 }
7979 // Continue on to the next method if we are done.
7980 if (LIKELY(found_impl)) {
7981 continue;
7982 } else if (LIKELY(super_interface)) {
7983 // Don't look for a default implementation when the super-method is implemented directly
7984 // by the class.
7985 //
7986 // See if we can use the superclasses method and skip searching everything else.
7987 // Note: !found_impl && super_interface
7988 CHECK(extend_super_iftable);
7989 // If this is a super_interface method it is possible we shouldn't override it because a
7990 // superclass could have implemented it directly. We get the method the superclass used
7991 // to implement this to know if we can override it with a default method. Doing this is
7992 // safe since we know that the super_iftable is filled in so we can simply pull it from
7993 // there. We don't bother if this is not a super-classes interface since in that case we
7994 // have scanned the entire vtable anyway and would have found it.
7995 // TODO This is rather dirty but it is faster than searching through the entire vtable
7996 // every time.
7997 ArtMethod* supers_method =
7998 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7999 DCHECK(supers_method != nullptr);
8000 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008001 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008002 // The method is not overridable by a default method (i.e. it is directly implemented
8003 // in some class). Therefore move onto the next interface method.
8004 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008005 } else {
8006 // If the super-classes method is override-able by a default method we need to keep
8007 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8008 // 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 -07008009 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8010 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8011 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008012 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008013 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8014 << " and not 'nullptr' or "
8015 << supers_method->PrettyMethod()
8016 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008017 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008018 }
8019 }
8020 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008021 ArtMethod* current_method = helper.FindMethod(interface_method,
8022 interface_name_comparator,
8023 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008024 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008025 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008026 // We could not find an implementation for this method and since it is a brand new
8027 // interface we searched the entire vtable (and all default methods) for an
8028 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008029 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8030 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008031 }
8032
8033 if (current_method != nullptr) {
8034 // We found a default method implementation. Record it in the iftable and IMT.
8035 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8036 SetIMTRef(unimplemented_method,
8037 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008038 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008039 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008040 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008041 }
8042 }
Alex Light705ad492015-09-21 11:36:30 -07008043 } // For each method in interface end.
8044 } // if (num_methods > 0)
8045 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008046 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008047 if (helper.HasNewVirtuals()) {
8048 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8049 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8050 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8051
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008052 // 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 -07008053 // suspension assert.
8054 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008055
Alex Light705ad492015-09-21 11:36:30 -07008056 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008057 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008058 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008059 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008060 return false;
8061 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008062 helper.UpdateIfTable(iftable);
8063 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008064 }
Alex Light705ad492015-09-21 11:36:30 -07008065
Vladimir Marko921094a2017-01-12 18:37:06 +00008066 helper.CheckNoStaleMethodsInDexCache();
8067 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008068 } else {
8069 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008070 }
Alex Light705ad492015-09-21 11:36:30 -07008071 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008072 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008073 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008074 return true;
8075}
8076
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008077bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008078 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008079 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008080}
8081
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008082bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008083 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008084 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008085}
8086
Brian Carlstromdbc05252011-09-09 01:59:59 -07008087struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008088 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008089 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008090 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008091 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008092 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008093 // 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 -07008094 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8095 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008096 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008097 if (type1 == Primitive::kPrimNot) {
8098 // Reference always goes first.
8099 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008100 }
Vladimir Markod5777482014-11-12 17:02:02 +00008101 if (type2 == Primitive::kPrimNot) {
8102 // Reference always goes first.
8103 return false;
8104 }
8105 size_t size1 = Primitive::ComponentSize(type1);
8106 size_t size2 = Primitive::ComponentSize(type2);
8107 if (size1 != size2) {
8108 // Larger primitive types go first.
8109 return size1 > size2;
8110 }
8111 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8112 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008113 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008114 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8115 // by name and for equal names by type id index.
8116 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8117 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008118 }
8119};
8120
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008121bool ClassLinker::LinkFields(Thread* self,
8122 Handle<mirror::Class> klass,
8123 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008124 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008125 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008126 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008127 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8128 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008129
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008130 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008131 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008132 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008133 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008134 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008135 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008136 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008137 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008138 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008139 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008140 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008141 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008142
David Sehr709b0702016-10-13 09:12:37 -07008143 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008144
Brian Carlstromdbc05252011-09-09 01:59:59 -07008145 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008146 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008147 //
8148 // The overall sort order order is:
8149 // 1) All object reference fields, sorted alphabetically.
8150 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8151 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8152 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8153 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8154 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8155 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8156 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8157 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8158 //
8159 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8160 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008161 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008162 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008163 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008164 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008165 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008166 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008167 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8168 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008169
Fred Shih381e4ca2014-08-25 17:24:27 -07008170 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008171 size_t current_field = 0;
8172 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008173 FieldGaps gaps;
8174
Brian Carlstromdbc05252011-09-09 01:59:59 -07008175 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008176 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008177 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008178 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008179 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008180 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008181 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008182 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8183 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008184 MemberOffset old_offset = field_offset;
8185 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8186 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8187 }
Roland Levillain14d90572015-07-16 10:52:26 +01008188 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008189 grouped_and_sorted_fields.pop_front();
8190 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008191 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008192 field_offset = MemberOffset(field_offset.Uint32Value() +
8193 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008194 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008195 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8196 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008197 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8198 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8199 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8200 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008201 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8202 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008203 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008204
Elliott Hughesadb460d2011-10-05 17:02:34 -07008205 // 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 -07008206 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008207 // We know there are no non-reference fields in the Reference classes, and we know
8208 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008209 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008210 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008211 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008212 --num_reference_fields;
8213 }
8214
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008215 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008216 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008217 if (is_static) {
8218 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008219 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008220 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008221 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008222 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008223 if (num_reference_fields == 0 || super_class == nullptr) {
8224 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008225 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008226 if (super_class == nullptr ||
8227 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8228 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008229 }
8230 }
8231 if (kIsDebugBuild) {
8232 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8233 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008234 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008235 while (cur_super != nullptr) {
8236 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8237 cur_super = cur_super->GetSuperClass();
8238 }
8239 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008240 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008241 } else {
8242 // Check that there is at least num_reference_fields other than Object.class.
8243 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008244 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008245 }
8246 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008247 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008248 std::string temp;
8249 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8250 size_t previous_size = klass->GetObjectSize();
8251 if (previous_size != 0) {
8252 // Make sure that we didn't originally have an incorrect size.
8253 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008254 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008255 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008256 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008257 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008258
8259 if (kIsDebugBuild) {
8260 // Make sure that the fields array is ordered by name but all reference
8261 // offsets are at the beginning as far as alignment allows.
8262 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008263 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008264 : klass->GetFirstReferenceInstanceFieldOffset();
8265 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8266 num_reference_fields *
8267 sizeof(mirror::HeapReference<mirror::Object>));
8268 MemberOffset current_ref_offset = start_ref_offset;
8269 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008270 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008271 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008272 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8273 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008274 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008275 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008276 // NOTE: The field names can be the same. This is not possible in the Java language
8277 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008278 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008279 }
8280 Primitive::Type type = field->GetTypeAsPrimitiveType();
8281 bool is_primitive = type != Primitive::kPrimNot;
8282 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8283 strcmp("referent", field->GetName()) == 0) {
8284 is_primitive = true; // We lied above, so we have to expect a lie here.
8285 }
8286 MemberOffset offset = field->GetOffsetDuringLinking();
8287 if (is_primitive) {
8288 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8289 // Shuffled before references.
8290 size_t type_size = Primitive::ComponentSize(type);
8291 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8292 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8293 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8294 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8295 }
8296 } else {
8297 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8298 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8299 sizeof(mirror::HeapReference<mirror::Object>));
8300 }
8301 }
8302 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008304 return true;
8305}
8306
Vladimir Marko76649e82014-11-10 18:32:59 +00008307// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008308void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008309 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008310 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008311 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008312 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008313 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008314 // Compute reference offsets unless our superclass overflowed.
8315 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8316 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008317 if (num_reference_fields != 0u) {
8318 // All of the fields that contain object references are guaranteed be grouped in memory
8319 // starting at an appropriately aligned address after super class object data.
8320 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8321 sizeof(mirror::HeapReference<mirror::Object>));
8322 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008323 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008324 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008325 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008326 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008327 reference_offsets |= (0xffffffffu << start_bit) &
8328 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008329 }
8330 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008331 }
8332 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008333 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008334}
8335
Vladimir Marko18090d12018-06-01 16:53:12 +01008336ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8337 ObjPtr<mirror::DexCache> dex_cache) {
8338 StackHandleScope<1> hs(Thread::Current());
8339 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8340 return DoResolveString(string_idx, h_dex_cache);
8341}
8342
8343ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8344 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008345 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008346 uint32_t utf16_length;
8347 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008348 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008349 if (string != nullptr) {
8350 dex_cache->SetResolvedString(string_idx, string);
8351 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008352 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008353}
8354
Vladimir Marko18090d12018-06-01 16:53:12 +01008355ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8356 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008357 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008358 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008359 uint32_t utf16_length;
8360 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008361 ObjPtr<mirror::String> string =
8362 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008363 if (string != nullptr) {
8364 dex_cache->SetResolvedString(string_idx, string);
8365 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008366 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008367}
8368
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008369ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008370 ObjPtr<mirror::Class> referrer) {
8371 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8372}
8373
8374ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008375 ObjPtr<mirror::DexCache> dex_cache,
8376 ObjPtr<mirror::ClassLoader> class_loader) {
8377 const DexFile& dex_file = *dex_cache->GetDexFile();
8378 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8379 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8380 ObjPtr<mirror::Class> type = nullptr;
8381 if (descriptor[1] == '\0') {
8382 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8383 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008384 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008385 } else {
8386 Thread* const self = Thread::Current();
8387 DCHECK(self != nullptr);
8388 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8389 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008390 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008391 }
8392 if (type != nullptr) {
8393 if (type->IsResolved()) {
8394 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008395 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008396 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008397 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008398 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008399 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008400}
8401
Andreas Gampe4835d212018-11-21 14:55:10 -08008402template <typename T>
8403ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008404 StackHandleScope<2> hs(Thread::Current());
8405 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8406 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8407 return DoResolveType(type_idx, dex_cache, class_loader);
8408}
8409
Andreas Gampe4835d212018-11-21 14:55:10 -08008410// Instantiate the above.
8411template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8412 ArtField* referrer);
8413template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8414 ArtMethod* referrer);
8415template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8416 ObjPtr<mirror::Class> referrer);
8417
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008418ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008419 Handle<mirror::DexCache> dex_cache,
8420 Handle<mirror::ClassLoader> class_loader) {
8421 Thread* self = Thread::Current();
8422 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8423 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8424 if (resolved != nullptr) {
8425 // TODO: we used to throw here if resolved's class loader was not the
8426 // boot class loader. This was to permit different classes with the
8427 // same name to be loaded simultaneously by different loaders
8428 dex_cache->SetResolvedType(type_idx, resolved);
8429 } else {
8430 CHECK(self->IsExceptionPending())
8431 << "Expected pending exception for failed resolution of: " << descriptor;
8432 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8433 StackHandleScope<1> hs(self);
8434 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008435 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008436 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8437 self->ClearException();
8438 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8439 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008440 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008441 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008442 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008443 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008444 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008445}
8446
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008447ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8448 ObjPtr<mirror::DexCache> dex_cache,
8449 ObjPtr<mirror::ClassLoader> class_loader,
8450 uint32_t method_idx) {
8451 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8452 // functions can optimize the search if the dex_cache is the same as the DexCache
8453 // of the class, with fall-back to name and signature search otherwise.
8454 ArtMethod* resolved = nullptr;
8455 if (klass->IsInterface()) {
8456 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8457 } else {
8458 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8459 }
8460 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008461 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008462 hiddenapi::ShouldDenyAccessToMember(resolved,
8463 hiddenapi::AccessContext(class_loader, dex_cache),
8464 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008465 resolved = nullptr;
8466 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008467 if (resolved != nullptr) {
8468 // In case of jmvti, the dex file gets verified before being registered, so first
8469 // check if it's registered before checking class tables.
8470 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008471 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8472 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008473 << "DexFile referrer: " << dex_file.GetLocation()
8474 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8475 // Be a good citizen and update the dex cache to speed subsequent calls.
8476 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008477 // Disable the following invariant check as the verifier breaks it. b/73760543
8478 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8479 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8480 // << "Method: " << resolved->PrettyMethod() << ", "
8481 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8482 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008483 }
8484 return resolved;
8485}
8486
David Brazdil4525e0b2018-04-05 16:57:32 +01008487// Returns true if `method` is either null or hidden.
8488// Does not print any warnings if it is hidden.
8489static bool CheckNoSuchMethod(ArtMethod* method,
8490 ObjPtr<mirror::DexCache> dex_cache,
8491 ObjPtr<mirror::ClassLoader> class_loader)
8492 REQUIRES_SHARED(Locks::mutator_lock_) {
8493 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008494 hiddenapi::ShouldDenyAccessToMember(method,
8495 hiddenapi::AccessContext(class_loader, dex_cache),
8496 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008497}
8498
8499ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8500 ObjPtr<mirror::DexCache> dex_cache,
8501 ObjPtr<mirror::ClassLoader> class_loader,
8502 uint32_t method_idx) {
8503 if (klass->IsInterface()) {
8504 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8505 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8506 } else {
8507 // If there was an interface method with the same signature, we would have
8508 // found it in the "copied" methods. Only DCHECK that the interface method
8509 // really does not exist.
8510 if (kIsDebugBuild) {
8511 ArtMethod* method =
8512 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8513 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8514 }
8515 return nullptr;
8516 }
8517}
8518
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008519template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008520ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008521 Handle<mirror::DexCache> dex_cache,
8522 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008523 ArtMethod* referrer,
8524 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008525 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008526 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008527 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008528 PointerSize pointer_size = image_pointer_size_;
8529 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008530 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008531 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8532 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008533 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8534 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008535 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008536 return resolved;
8537 }
Vladimir Marko89011192017-12-11 13:45:05 +00008538 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008539 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008540 ObjPtr<mirror::Class> klass = nullptr;
8541 if (valid_dex_cache_method) {
8542 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8543 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008544 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008545 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008546 // We normaly should not end up here. However the verifier currently doesn't guarantee
8547 // the invariant of having the klass in the class table. b/73760543
8548 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008549 }
Vladimir Markoba118822017-06-12 15:41:56 +01008550 } else {
8551 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008552 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008553 if (klass == nullptr) {
8554 DCHECK(Thread::Current()->IsExceptionPending());
8555 return nullptr;
8556 }
8557 }
8558
8559 // Check if the invoke type matches the class type.
8560 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008561 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008562 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008563 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008564 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008565 }
Vladimir Markoba118822017-06-12 15:41:56 +01008566
8567 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008568 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008569 }
Vladimir Markoba118822017-06-12 15:41:56 +01008570
8571 // Note: We can check for IllegalAccessError only if we have a referrer.
8572 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8573 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8574 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8575 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8576 resolved,
8577 dex_cache.Get(),
8578 method_idx,
8579 type)) {
8580 DCHECK(Thread::Current()->IsExceptionPending());
8581 return nullptr;
8582 }
8583 }
8584
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008585 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008586 if (LIKELY(resolved != nullptr) &&
8587 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8588 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008589 return resolved;
8590 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008591 // If we had a method, or if we can find one with another lookup type,
8592 // it's an incompatible-class-change error.
8593 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008594 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008595 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008596 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008597 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008598 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008599 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008600 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8601 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008602 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008603 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008604 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008605 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008606 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008607}
8608
Vladimir Marko89011192017-12-11 13:45:05 +00008609ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008610 Handle<mirror::DexCache> dex_cache,
8611 Handle<mirror::ClassLoader> class_loader) {
8612 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008613 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008614 if (resolved != nullptr) {
8615 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008616 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8617 return resolved;
8618 }
8619 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008620 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008621 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008622 if (klass == nullptr) {
8623 Thread::Current()->AssertPendingException();
8624 return nullptr;
8625 }
8626 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008627 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8628 } else {
8629 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008630 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008631 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008632 hiddenapi::ShouldDenyAccessToMember(
8633 resolved,
8634 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8635 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008636 resolved = nullptr;
8637 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008638 return resolved;
8639}
8640
Vladimir Markof44d36c2017-03-14 14:18:46 +00008641ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8642 ObjPtr<mirror::DexCache> dex_cache,
8643 ObjPtr<mirror::ClassLoader> class_loader,
8644 bool is_static) {
8645 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008646 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008647 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8648 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008649 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008650 }
8651 if (klass == nullptr) {
8652 // The class has not been resolved yet, so the field is also unresolved.
8653 return nullptr;
8654 }
8655 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008656
David Brazdil1ab0fa82018-05-04 11:28:03 +01008657 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008658}
8659
Vladimir Markoe11dd502017-12-08 14:09:45 +00008660ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008661 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008662 Handle<mirror::ClassLoader> class_loader,
8663 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008664 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008665 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008666 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008667 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008668 return resolved;
8669 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008670 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008671 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008672 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008673 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008674 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008675 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008676 }
8677
David Brazdil1ab0fa82018-05-04 11:28:03 +01008678 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008679 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008680 const char* name = dex_file.GetFieldName(field_id);
8681 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008682 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008683 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008684 return resolved;
8685}
8686
Vladimir Markoe11dd502017-12-08 14:09:45 +00008687ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008688 Handle<mirror::DexCache> dex_cache,
8689 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008690 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008691 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008692 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008693 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008694 return resolved;
8695 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008696 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008697 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008698 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008699 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008700 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008701 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008702 }
8703
David Brazdil1ab0fa82018-05-04 11:28:03 +01008704 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8705 if (resolved == nullptr) {
8706 const char* name = dex_file.GetFieldName(field_id);
8707 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008708 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008709 }
8710 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008711}
8712
David Brazdil1ab0fa82018-05-04 11:28:03 +01008713ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8714 ObjPtr<mirror::DexCache> dex_cache,
8715 ObjPtr<mirror::ClassLoader> class_loader,
8716 uint32_t field_idx,
8717 bool is_static) {
8718 ArtField* resolved = nullptr;
8719 Thread* self = is_static ? Thread::Current() : nullptr;
8720 const DexFile& dex_file = *dex_cache->GetDexFile();
8721
8722 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8723 : klass->FindInstanceField(dex_cache, field_idx);
8724
8725 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008726 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008727 const char* name = dex_file.GetFieldName(field_id);
8728 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8729 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8730 : klass->FindInstanceField(name, type);
8731 }
8732
8733 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008734 hiddenapi::ShouldDenyAccessToMember(resolved,
8735 hiddenapi::AccessContext(class_loader, dex_cache),
8736 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008737 resolved = nullptr;
8738 }
8739
8740 if (resolved != nullptr) {
8741 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8742 }
8743
8744 return resolved;
8745}
8746
8747ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8748 ObjPtr<mirror::DexCache> dex_cache,
8749 ObjPtr<mirror::ClassLoader> class_loader,
8750 uint32_t field_idx) {
8751 ArtField* resolved = nullptr;
8752 Thread* self = Thread::Current();
8753 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008754 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008755
8756 const char* name = dex_file.GetFieldName(field_id);
8757 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8758 resolved = mirror::Class::FindField(self, klass, name, type);
8759
8760 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008761 hiddenapi::ShouldDenyAccessToMember(resolved,
8762 hiddenapi::AccessContext(class_loader, dex_cache),
8763 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008764 resolved = nullptr;
8765 }
8766
8767 if (resolved != nullptr) {
8768 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8769 }
8770
8771 return resolved;
8772}
8773
Vladimir Markoaf940202017-12-08 15:01:18 +00008774ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8775 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008776 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008777 Handle<mirror::DexCache> dex_cache,
8778 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008779 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008780 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008781
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008782 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008783 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008784 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008785 }
8786
Narayan Kamath25352fc2016-08-03 12:46:58 +01008787 StackHandleScope<4> hs(self);
8788
8789 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008790 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008791 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008792 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008793 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008794 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008795 DCHECK(self->IsExceptionPending());
8796 return nullptr;
8797 }
8798
8799 // Then resolve the argument types.
8800 //
8801 // TODO: Is there a better way to figure out the number of method arguments
8802 // other than by looking at the shorty ?
8803 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8804
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008805 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008806 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8807 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008808 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008809 DCHECK(self->IsExceptionPending());
8810 return nullptr;
8811 }
8812
8813 DexFileParameterIterator it(dex_file, proto_id);
8814 int32_t i = 0;
8815 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8816 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008817 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008818 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008819 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008820 DCHECK(self->IsExceptionPending());
8821 return nullptr;
8822 }
8823
8824 method_params->Set(i++, param_class.Get());
8825 }
8826
8827 DCHECK(!it.HasNext());
8828
8829 Handle<mirror::MethodType> type = hs.NewHandle(
8830 mirror::MethodType::Create(self, return_type, method_params));
8831 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8832
8833 return type.Get();
8834}
8835
Vladimir Markoaf940202017-12-08 15:01:18 +00008836ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008837 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008838 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008839 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008840 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8841 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008842 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008843}
8844
Vladimir Marko5aead702019-03-27 11:00:36 +00008845ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008846 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008847 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008848 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008849 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008850 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8851 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008852 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008853 bool is_static;
8854 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008855 switch (handle_type) {
8856 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008857 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008858 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008859 is_static = true;
8860 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008861 break;
8862 }
8863 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008864 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008865 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008866 is_static = true;
8867 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008868 break;
8869 }
8870 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008871 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008872 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008873 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008874 num_params = 2;
8875 break;
8876 }
8877 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008878 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008879 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008880 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008881 num_params = 1;
8882 break;
8883 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008884 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008885 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008886 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008887 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008888 case DexFile::MethodHandleType::kInvokeInterface:
8889 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008890 }
8891
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008892 ArtField* target_field =
8893 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8894 if (LIKELY(target_field != nullptr)) {
8895 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8896 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8897 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8898 ThrowIllegalAccessErrorField(referring_class, target_field);
8899 return nullptr;
8900 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008901 if (UNLIKELY(is_put && target_field->IsFinal())) {
8902 ThrowIllegalAccessErrorField(referring_class, target_field);
8903 return nullptr;
8904 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008905 } else {
8906 DCHECK(Thread::Current()->IsExceptionPending());
8907 return nullptr;
8908 }
8909
8910 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008911 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008912 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8913 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008914 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008915 DCHECK(self->IsExceptionPending());
8916 return nullptr;
8917 }
8918
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008919 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008920 Handle<mirror::Class> return_type;
8921 switch (handle_type) {
8922 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008923 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008924 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008925 break;
8926 }
8927 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008928 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008929 break;
8930 }
8931 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008932 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008933 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008934 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008935 break;
8936 }
8937 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008938 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008939 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008940 break;
8941 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008942 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008943 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008944 case DexFile::MethodHandleType::kInvokeConstructor:
8945 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008946 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008947 UNREACHABLE();
8948 }
8949
8950 for (int32_t i = 0; i < num_params; ++i) {
8951 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8952 DCHECK(self->IsExceptionPending());
8953 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008954 }
8955 }
8956
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008957 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008958 DCHECK(self->IsExceptionPending());
8959 return nullptr;
8960 }
8961
8962 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008963 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8964 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008965 DCHECK(self->IsExceptionPending());
8966 return nullptr;
8967 }
Orion Hodson631827d2017-04-10 14:53:47 +01008968
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008969 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8970 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8971}
8972
Vladimir Marko5aead702019-03-27 11:00:36 +00008973ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008974 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008975 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008976 ArtMethod* referrer) {
8977 DexFile::MethodHandleType handle_type =
8978 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8979 mirror::MethodHandle::Kind kind;
8980 uint32_t receiver_count = 0;
8981 ArtMethod* target_method = nullptr;
8982 switch (handle_type) {
8983 case DexFile::MethodHandleType::kStaticPut:
8984 case DexFile::MethodHandleType::kStaticGet:
8985 case DexFile::MethodHandleType::kInstancePut:
8986 case DexFile::MethodHandleType::kInstanceGet:
8987 UNREACHABLE();
8988 case DexFile::MethodHandleType::kInvokeStatic: {
8989 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8990 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008991 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8992 method_handle.field_or_method_idx_,
8993 referrer,
8994 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008995 break;
8996 }
8997 case DexFile::MethodHandleType::kInvokeInstance: {
8998 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8999 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009000 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9001 method_handle.field_or_method_idx_,
9002 referrer,
9003 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009004 break;
9005 }
9006 case DexFile::MethodHandleType::kInvokeConstructor: {
9007 // Constructors are currently implemented as a transform. They
9008 // are special cased later in this method.
9009 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9010 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009011 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9012 method_handle.field_or_method_idx_,
9013 referrer,
9014 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009015 break;
9016 }
9017 case DexFile::MethodHandleType::kInvokeDirect: {
9018 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9019 receiver_count = 1;
9020 StackHandleScope<2> hs(self);
9021 // A constant method handle with type kInvokeDirect can refer to
9022 // a method that is private or to a method in a super class. To
9023 // disambiguate the two options, we resolve the method ignoring
9024 // the invocation type to determine if the method is private. We
9025 // then resolve again specifying the intended invocation type to
9026 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009027 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009028 hs.NewHandle(referrer->GetDexCache()),
9029 hs.NewHandle(referrer->GetClassLoader()));
9030 if (UNLIKELY(target_method == nullptr)) {
9031 break;
9032 }
9033
9034 if (target_method->IsPrivate()) {
9035 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009036 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9037 method_handle.field_or_method_idx_,
9038 referrer,
9039 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009040 } else {
9041 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009042 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9043 method_handle.field_or_method_idx_,
9044 referrer,
9045 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009046 if (UNLIKELY(target_method == nullptr)) {
9047 break;
9048 }
9049 // Find the method specified in the parent in referring class
9050 // so invoke-super invokes the method in the parent of the
9051 // referrer.
9052 target_method =
9053 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9054 kRuntimePointerSize);
9055 }
9056 break;
9057 }
9058 case DexFile::MethodHandleType::kInvokeInterface: {
9059 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9060 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009061 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9062 method_handle.field_or_method_idx_,
9063 referrer,
9064 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009065 break;
9066 }
Orion Hodson631827d2017-04-10 14:53:47 +01009067 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009068
9069 if (UNLIKELY(target_method == nullptr)) {
9070 DCHECK(Thread::Current()->IsExceptionPending());
9071 return nullptr;
9072 }
9073
9074 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9075 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9076 uint32_t access_flags = target_method->GetAccessFlags();
9077 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9078 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9079 return nullptr;
9080 }
9081
9082 // Calculate the number of parameters from the method shorty. We add the
9083 // receiver count (0 or 1) and deduct one for the return value.
9084 uint32_t shorty_length;
9085 target_method->GetShorty(&shorty_length);
9086 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9087
Orion Hodsonecd58562018-09-24 11:27:33 +01009088 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009089 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009090 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9091 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9092 if (method_params.Get() == nullptr) {
9093 DCHECK(self->IsExceptionPending());
9094 return nullptr;
9095 }
9096
Orion Hodsonecd58562018-09-24 11:27:33 +01009097 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009098 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009099 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009100 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009101 // Insert receiver. Use the class identified in the method handle rather than the declaring
9102 // class of the resolved method which may be super class or default interface method
9103 // (b/115964401).
9104 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9105 // receiver_class should have been resolved when resolving the target method.
9106 DCHECK(receiver_class != nullptr);
9107 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009108 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009109
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009110 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009111 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009112 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009113 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009114 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009115 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009116 if (nullptr == klass) {
9117 DCHECK(self->IsExceptionPending());
9118 return nullptr;
9119 }
9120 method_params->Set(index++, klass);
9121 it.Next();
9122 }
9123
Orion Hodsonecd58562018-09-24 11:27:33 +01009124 Handle<mirror::Class> return_type =
9125 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009126 if (UNLIKELY(return_type.IsNull())) {
9127 DCHECK(self->IsExceptionPending());
9128 return nullptr;
9129 }
9130
9131 Handle<mirror::MethodType>
9132 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9133 if (UNLIKELY(method_type.IsNull())) {
9134 DCHECK(self->IsExceptionPending());
9135 return nullptr;
9136 }
9137
9138 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9139 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9140 Handle<mirror::MethodHandlesLookup> lookup =
9141 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9142 return lookup->FindConstructor(self, constructor_class, method_type);
9143 }
9144
9145 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9146 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9147}
9148
Vladimir Markoaf940202017-12-08 15:01:18 +00009149ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9150 uint32_t method_handle_idx,
9151 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009152 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009153 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009154 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009155 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9156 case DexFile::MethodHandleType::kStaticPut:
9157 case DexFile::MethodHandleType::kStaticGet:
9158 case DexFile::MethodHandleType::kInstancePut:
9159 case DexFile::MethodHandleType::kInstanceGet:
9160 return ResolveMethodHandleForField(self, method_handle, referrer);
9161 case DexFile::MethodHandleType::kInvokeStatic:
9162 case DexFile::MethodHandleType::kInvokeInstance:
9163 case DexFile::MethodHandleType::kInvokeConstructor:
9164 case DexFile::MethodHandleType::kInvokeDirect:
9165 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009166 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009167 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009168}
9169
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009170bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9171 return (entry_point == GetQuickResolutionStub()) ||
9172 (quick_resolution_trampoline_ == entry_point);
9173}
9174
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009175bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9176 return (entry_point == GetQuickToInterpreterBridge()) ||
9177 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9178}
9179
9180bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9181 return (entry_point == GetQuickGenericJniStub()) ||
9182 (quick_generic_jni_trampoline_ == entry_point);
9183}
9184
David Sehra49e0532017-08-25 08:05:29 -07009185bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9186 return entry_point == GetJniDlsymLookupStub();
9187}
9188
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009189const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9190 return GetQuickGenericJniStub();
9191}
9192
Mathieu Chartiere401d142015-04-22 13:56:20 -07009193void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009194 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009195 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9196 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009197 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009198 }
9199}
9200
Alex Lightdb01a092017-04-03 15:39:55 -07009201void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9202 DCHECK(method->IsObsolete());
9203 // We cannot mess with the entrypoints of native methods because they are used to determine how
9204 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9205 if (!method->IsNative()) {
9206 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9207 }
9208}
9209
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009210void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009211 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009212 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009213 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9214 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009215 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9216 os << "Dumping registered class loaders\n";
9217 size_t class_loader_index = 0;
9218 for (const ClassLoaderData& class_loader : class_loaders_) {
9219 ObjPtr<mirror::ClassLoader> loader =
9220 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9221 if (loader != nullptr) {
9222 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9223 bool saw_one_dex_file = false;
9224 for (const DexCacheData& dex_cache : dex_caches_) {
9225 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9226 if (saw_one_dex_file) {
9227 os << ":";
9228 }
9229 saw_one_dex_file = true;
9230 os << dex_cache.dex_file->GetLocation();
9231 }
9232 }
9233 os << "]";
9234 bool found_parent = false;
9235 if (loader->GetParent() != nullptr) {
9236 size_t parent_index = 0;
9237 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9238 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9239 soa.Self()->DecodeJObject(class_loader2.weak_root));
9240 if (loader2 == loader->GetParent()) {
9241 os << ", parent #" << parent_index;
9242 found_parent = true;
9243 break;
9244 }
9245 parent_index++;
9246 }
9247 if (!found_parent) {
9248 os << ", unregistered parent of type "
9249 << loader->GetParent()->GetClass()->PrettyDescriptor();
9250 }
9251 } else {
9252 os << ", no parent";
9253 }
9254 os << "\n";
9255 }
9256 }
9257 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009258}
9259
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009260class CountClassesVisitor : public ClassLoaderVisitor {
9261 public:
9262 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9263
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009264 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009265 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009266 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009267 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009268 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9269 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009270 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009271 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009272
9273 size_t num_zygote_classes;
9274 size_t num_non_zygote_classes;
9275};
9276
9277size_t ClassLinker::NumZygoteClasses() const {
9278 CountClassesVisitor visitor;
9279 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009280 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009281}
9282
9283size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009284 CountClassesVisitor visitor;
9285 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009286 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009287}
9288
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009289size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009290 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009291 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009292 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009293}
9294
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009295pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009296 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009297}
9298
9299pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009300 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009301}
9302
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009303void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009304 DCHECK(!init_done_);
9305
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009306 DCHECK(klass != nullptr);
9307 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009308
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009309 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009310 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009311 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9312 int32_t index = static_cast<int32_t>(class_root);
9313 DCHECK(class_roots->Get(index) == nullptr);
9314 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009315}
9316
Roland Levillain0e840272018-08-23 19:55:30 +01009317void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9318 ObjPtr<mirror::Class> java_lang_Class,
9319 ClassRoot primitive_array_class_root,
9320 ClassRoot primitive_class_root,
9321 const char* descriptor) {
9322 StackHandleScope<1> hs(self);
9323 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9324 AllocPrimitiveArrayClass(self, java_lang_Class)));
9325 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9326 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9327 CheckSystemClass(self, primitive_array_class, descriptor);
9328}
9329
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009330ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9331 Thread* self,
9332 const std::vector<const DexFile*>& dex_files,
9333 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009334 Handle<mirror::ClassLoader> parent_loader,
9335 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009336
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009337 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009338
Mathieu Chartierc7853442015-03-27 14:35:38 -07009339 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009340 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009341
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009342 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009343 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009344 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009345 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009346 mirror::ObjectArray<mirror::Object>::Alloc(self,
9347 dex_elements_class.Get(),
9348 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009349 Handle<mirror::Class> h_dex_element_class =
9350 hs.NewHandle(dex_elements_class->GetComponentType());
9351
Mathieu Chartierc7853442015-03-27 14:35:38 -07009352 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009353 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009354 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009355
Andreas Gampe08883de2016-11-08 13:20:52 -08009356 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009357 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009358
Andreas Gampe08883de2016-11-08 13:20:52 -08009359 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009360 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009361
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009362 // Fill the elements array.
9363 int32_t index = 0;
9364 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009365 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009366
Calin Juravle7865ac72017-06-28 11:03:12 -07009367 // CreateWellKnownClassLoader is only used by gtests and compiler.
9368 // 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 -07009369 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9370 self,
9371 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009372 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009373 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009374
Mathieu Chartier3738e982017-05-12 16:07:28 -07009375 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9376 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009377 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009378 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009379 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009380 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009381
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009382 Handle<mirror::String> h_file_name = hs2.NewHandle(
9383 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009384 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009385 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9386
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009387 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009388 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009389 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009390
9391 h_dex_elements->Set(index, h_element.Get());
9392 index++;
9393 }
9394 DCHECK_EQ(index, h_dex_elements->GetLength());
9395
9396 // Create DexPathList.
9397 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009398 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009399 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009400 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009401 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009402 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9403 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9404 // elements.
9405 {
9406 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9407 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9408 DCHECK(native_lib_dirs != nullptr);
9409 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9410 DCHECK(list_class != nullptr);
9411 {
9412 StackHandleScope<1> h_list_scope(self);
9413 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9414 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9415 DCHECK(list_init);
9416 list_class = h_list_class.Get();
9417 }
9418 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9419 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9420 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9421 // normally never null), as long as one does not try to add elements, this will still
9422 // work.
9423 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9424 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009425
Calin Juravle7865ac72017-06-28 11:03:12 -07009426 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009427 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9428 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009429 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009430 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009431 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009432 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009433 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009434 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009435
9436 // Make a pretend boot-classpath.
9437 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009438 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009439 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009440 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009441 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009442 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009443 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009444 if (parent_loader.Get() == nullptr) {
9445 ScopedObjectAccessUnchecked soa(self);
9446 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9447 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9448 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9449 } else {
9450 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9451 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009452
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009453 ArtField* shared_libraries_field =
9454 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9455 DCHECK(shared_libraries_field != nullptr);
9456 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9457
9458 return h_class_loader.Get();
9459}
9460
9461jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9462 const std::vector<const DexFile*>& dex_files,
9463 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009464 jobject parent_loader,
9465 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009466 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9467 WellKnownClasses::dalvik_system_PathClassLoader) ||
9468 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009469 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9470 self->GetJniEnv()->IsSameObject(loader_class,
9471 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009472
9473 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9474 // We could move the jobject to the callers, but all call-sites do this...
9475 ScopedObjectAccessUnchecked soa(self);
9476
9477 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009478 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009479
9480 Handle<mirror::Class> h_loader_class =
9481 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009482 Handle<mirror::ClassLoader> h_parent =
9483 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9484 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9485 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009486
9487 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9488 self,
9489 dex_files,
9490 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009491 h_parent,
9492 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009493
9494 // Make it a global ref and return.
9495 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009496 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009497 return soa.Env()->NewGlobalRef(local_ref.get());
9498}
9499
Calin Juravle7865ac72017-06-28 11:03:12 -07009500jobject ClassLinker::CreatePathClassLoader(Thread* self,
9501 const std::vector<const DexFile*>& dex_files) {
9502 return CreateWellKnownClassLoader(self,
9503 dex_files,
9504 WellKnownClasses::dalvik_system_PathClassLoader,
9505 nullptr);
9506}
9507
Andreas Gampe8ac75952015-06-02 21:01:45 -07009508void ClassLinker::DropFindArrayClassCache() {
9509 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9510 find_array_class_cache_next_victim_ = 0;
9511}
9512
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009513void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009514 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009515 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009516 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009517 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9518 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009519 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009520 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009521 }
9522 }
9523}
9524
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009525void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9526 for (const ClassLoaderData& data : class_loaders_) {
9527 LinearAlloc* alloc = data.allocator;
9528 if (alloc != nullptr && !visitor->Visit(alloc)) {
9529 break;
9530 }
9531 }
9532}
9533
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009534void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9535 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009536 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009537 Thread* const self = Thread::Current();
9538 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009539 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009540 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009541 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009542 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9543 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009544 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009545 }
9546}
9547
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009548void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009549 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009550 std::vector<ClassLoaderData> to_delete;
9551 // Do the delete outside the lock to avoid lock violation in jit code cache.
9552 {
9553 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9554 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9555 const ClassLoaderData& data = *it;
9556 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009557 ObjPtr<mirror::ClassLoader> class_loader =
9558 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009559 if (class_loader != nullptr) {
9560 ++it;
9561 } else {
9562 VLOG(class_linker) << "Freeing class loader";
9563 to_delete.push_back(data);
9564 it = class_loaders_.erase(it);
9565 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009566 }
9567 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009568 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009569 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009570 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009571 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009572}
9573
Vladimir Marko21300532017-01-24 18:06:55 +00009574class GetResolvedClassesVisitor : public ClassVisitor {
9575 public:
9576 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9577 : result_(result),
9578 ignore_boot_classes_(ignore_boot_classes),
9579 last_resolved_classes_(result->end()),
9580 last_dex_file_(nullptr),
9581 vlog_is_on_(VLOG_IS_ON(class_linker)),
9582 extra_stats_(),
9583 last_extra_stats_(extra_stats_.end()) { }
9584
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009585 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009586 if (!klass->IsProxyClass() &&
9587 !klass->IsArrayClass() &&
9588 klass->IsResolved() &&
9589 !klass->IsErroneousResolved() &&
9590 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9591 const DexFile& dex_file = klass->GetDexFile();
9592 if (&dex_file != last_dex_file_) {
9593 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009594 DexCacheResolvedClasses resolved_classes(
9595 dex_file.GetLocation(),
9596 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9597 dex_file.GetLocationChecksum(),
9598 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009599 last_resolved_classes_ = result_->find(resolved_classes);
9600 if (last_resolved_classes_ == result_->end()) {
9601 last_resolved_classes_ = result_->insert(resolved_classes).first;
9602 }
9603 }
9604 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9605 if (UNLIKELY(vlog_is_on_) && added) {
9606 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9607 if (last_extra_stats_ == extra_stats_.end() ||
9608 last_extra_stats_->first != resolved_classes) {
9609 last_extra_stats_ = extra_stats_.find(resolved_classes);
9610 if (last_extra_stats_ == extra_stats_.end()) {
9611 last_extra_stats_ =
9612 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9613 }
9614 }
9615 }
9616 }
9617 return true;
9618 }
9619
9620 void PrintStatistics() const {
9621 if (vlog_is_on_) {
9622 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9623 auto it = extra_stats_.find(std::addressof(resolved_classes));
9624 DCHECK(it != extra_stats_.end());
9625 const ExtraStats& extra_stats = it->second;
9626 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9627 << " has " << resolved_classes.GetClasses().size() << " / "
9628 << extra_stats.number_of_class_defs_ << " resolved classes";
9629 }
9630 }
9631 }
9632
9633 private:
9634 struct ExtraStats {
9635 explicit ExtraStats(uint32_t number_of_class_defs)
9636 : number_of_class_defs_(number_of_class_defs) {}
9637 uint32_t number_of_class_defs_;
9638 };
9639
9640 std::set<DexCacheResolvedClasses>* result_;
9641 bool ignore_boot_classes_;
9642 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9643 const DexFile* last_dex_file_;
9644
9645 // Statistics.
9646 bool vlog_is_on_;
9647 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9648 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9649};
9650
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009651std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009652 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009653 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009654 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009655 std::set<DexCacheResolvedClasses> ret;
9656 VLOG(class_linker) << "Collecting resolved classes";
9657 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009658 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9659 VisitClasses(&visitor);
9660 if (VLOG_IS_ON(class_linker)) {
9661 visitor.PrintStatistics();
9662 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009663 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009664 return ret;
9665}
9666
Mathieu Chartier65975772016-08-05 10:46:36 -07009667class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9668 public:
9669 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9670 : method_(method),
9671 pointer_size_(pointer_size) {}
9672
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009673 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009674 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9675 holder_ = klass;
9676 }
9677 // Return false to stop searching if holder_ is not null.
9678 return holder_ == nullptr;
9679 }
9680
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009681 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009682 const ArtMethod* const method_;
9683 const PointerSize pointer_size_;
9684};
9685
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009686ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009687 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9688 CHECK(method->IsCopied());
9689 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9690 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009691 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009692}
9693
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009694ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9695 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009696 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009697 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009698 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009699}
9700
Roland Levillain0e840272018-08-23 19:55:30 +01009701// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009702template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009703 uint32_t method_idx,
9704 Handle<mirror::DexCache> dex_cache,
9705 Handle<mirror::ClassLoader> class_loader,
9706 ArtMethod* referrer,
9707 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009708template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009709 uint32_t method_idx,
9710 Handle<mirror::DexCache> dex_cache,
9711 Handle<mirror::ClassLoader> class_loader,
9712 ArtMethod* referrer,
9713 InvokeType type);
9714
Roland Levillain0e840272018-08-23 19:55:30 +01009715// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009716template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009717 Thread* self,
9718 ObjPtr<mirror::Class> java_lang_Class,
9719 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009720template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009721 Thread* self,
9722 ObjPtr<mirror::Class> java_lang_Class,
9723 uint32_t class_size);
9724
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009725} // namespace art