blob: 97234afc50760e01c3983999e922b22cd99d9b16 [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
Alex Lightd6251582016-10-31 11:12:30 -0700178static 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;
Alex Lightd6251582016-10-31 11:12:30 -0700244 if (GetVerifyError(c) != nullptr) {
245 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
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 {
Alex Lightd6251582016-10-31 11:12:30 -0700265 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800266 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800267 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800268 }
Alex Lightd6251582016-10-31 11:12:30 -0700269 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
270 // might have meant to go down the earlier if statement with the original error but it got
271 // swallowed by the OOM so we end up here.
272 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800273 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
274 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
275 // exception will be a cause.
276 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700277 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700278 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700279 }
280}
281
Brian Carlstromb23eab12014-10-08 17:55:21 -0700282static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700283 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700284 if (VLOG_IS_ON(class_linker)) {
285 std::string temp;
286 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000287 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700288 }
289}
290
291static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700292 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700293 Thread* self = Thread::Current();
294 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700295
296 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700297 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700298
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800299 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
300 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
301 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800302 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800303 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
304 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
305 // could have caused the error.
306 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
307 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
308 << " failed initialization: "
309 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800310 }
311
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700312 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700313 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
314 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700315
Elliott Hughesa4f94742012-05-29 16:28:38 -0700316 // We only wrap non-Error exceptions; an Error can just be used as-is.
317 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000318 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700319 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700320 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700321}
322
Fred Shih381e4ca2014-08-25 17:24:27 -0700323// Gap between two fields in object layout.
324struct FieldGap {
325 uint32_t start_offset; // The offset from the start of the object.
326 uint32_t size; // The gap size of 1, 2, or 4 bytes.
327};
328struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800329 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700330 }
331 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
332 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800333 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700334 // Note that the priority queue returns the largest element, so operator()
335 // should return true if lhs is less than rhs.
336 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700337 }
338};
Andreas Gampec55bb392018-09-21 00:02:02 +0000339using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700340
341// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800342static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700343 DCHECK(gaps != nullptr);
344
345 uint32_t current_offset = gap_start;
346 while (current_offset != gap_end) {
347 size_t remaining = gap_end - current_offset;
348 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
349 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
350 current_offset += sizeof(uint32_t);
351 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
352 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
353 current_offset += sizeof(uint16_t);
354 } else {
355 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
356 current_offset += sizeof(uint8_t);
357 }
358 DCHECK_LE(current_offset, gap_end) << "Overran gap";
359 }
360}
361// Shuffle fields forward, making use of gaps whenever possible.
362template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000363static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700364 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700365 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700366 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700367 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700368 DCHECK(current_field_idx != nullptr);
369 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700370 DCHECK(gaps != nullptr);
371 DCHECK(field_offset != nullptr);
372
373 DCHECK(IsPowerOfTwo(n));
374 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700375 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700376 Primitive::Type type = field->GetTypeAsPrimitiveType();
377 if (Primitive::ComponentSize(type) < n) {
378 break;
379 }
380 if (!IsAligned<n>(field_offset->Uint32Value())) {
381 MemberOffset old_offset = *field_offset;
382 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
383 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
384 }
David Sehr709b0702016-10-13 09:12:37 -0700385 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700386 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700387 if (!gaps->empty() && gaps->top().size >= n) {
388 FieldGap gap = gaps->top();
389 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100390 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700391 field->SetOffset(MemberOffset(gap.start_offset));
392 if (gap.size > n) {
393 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
394 }
395 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100396 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700397 field->SetOffset(*field_offset);
398 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
399 }
400 ++(*current_field_idx);
401 }
402}
403
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800404ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700405 : boot_class_table_(new ClassTable()),
406 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800407 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800408 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700409 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000410 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700411 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800412 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800413 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100414 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800415 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700416 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700417 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
418 // For CHA disabled during Aot, see b/34193647.
419
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700420 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700421 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
422 "Array cache size wrong.");
423 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700424}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700425
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800426void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700427 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800428 if (c2 == nullptr) {
429 LOG(FATAL) << "Could not find class " << descriptor;
430 UNREACHABLE();
431 }
432 if (c1.Get() != c2) {
433 std::ostringstream os1, os2;
434 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
435 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
436 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
437 << ". This is most likely the result of a broken build. Make sure that "
438 << "libcore and art projects match.\n\n"
439 << os1.str() << "\n\n" << os2.str();
440 UNREACHABLE();
441 }
442}
443
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800444bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
445 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800446 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700447
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 Thread* const self = Thread::Current();
449 Runtime* const runtime = Runtime::Current();
450 gc::Heap* const heap = runtime->GetHeap();
451
Jeff Haodcdc85b2015-12-04 14:06:18 -0800452 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700453 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700454
Mathieu Chartiere401d142015-04-22 13:56:20 -0700455 // Use the pointer size from the runtime since we are probably creating the image.
456 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
457
Elliott Hughes30646832011-10-13 16:59:46 -0700458 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700459 // 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 -0800460 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700461 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700462 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700463 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
464 // the incorrect result when comparing to-space vs from-space.
Vladimir Markobcf17522018-06-01 13:14:32 +0100465 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(MakeObjPtr(
466 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800467 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100468 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700470 if (kUseBakerReadBarrier) {
471 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800472 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700473 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700474 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800475 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700476 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700477
Elliott Hughes418d20f2011-09-22 14:00:39 -0700478 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700479 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700480 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700483
Ian Rogers23435d02012-09-24 11:23:12 -0700484 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700485 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700486 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800487 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700488 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700489 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000490 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700491
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700492 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800493 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
494 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
495 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
496 java_lang_Object.Get(),
497 java_lang_Object->GetObjectSize(),
498 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700499
Igor Murashkin86083f72017-10-27 10:59:04 -0700500 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000501 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700502 // It might seem the lock here is unnecessary, however all the SubtypeCheck
503 // functions are annotated to require locks all the way down.
504 //
505 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
506 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000507 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
508 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700509 }
510
Ian Rogers23435d02012-09-24 11:23:12 -0700511 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700512 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700513 AllocClass(self, java_lang_Class.Get(),
514 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700516
Roland Levillain0e840272018-08-23 19:55:30 +0100517 // Setup java.lang.String.
518 //
519 // We make this class non-movable for the unlikely case where it were to be
520 // moved by a sticky-bit (minor) collection when using the Generational
521 // Concurrent Copying (CC) collector, potentially creating a stale reference
522 // in the `klass_` field of one of its instances allocated in the Large-Object
523 // Space (LOS) -- see the comment about the dirty card scanning logic in
524 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700525 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700526 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100527 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700528 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000529 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400530
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700531 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700532 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700533 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700534 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000535 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700536
Ian Rogers23435d02012-09-24 11:23:12 -0700537 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700538 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100539 mirror::ObjectArray<mirror::Class>::Alloc(self,
540 object_array_class.Get(),
541 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700542 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100543 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
544 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
545 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
546 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100547 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
548 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549
Mathieu Chartier6beced42016-11-15 15:51:31 -0800550 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
551 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
552
Vladimir Marko02610552018-06-04 14:38:00 +0100553 // Create array interface entries to populate once we can load system classes.
554 object_array_class->SetIfTable(AllocIfTable(self, 2));
555 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
556
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100558 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
559 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100560 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100561 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
562 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
563 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
564 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
565 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
566 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567
Vladimir Markoacb906d2018-05-30 10:23:49 +0100568 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700569 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100570 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100571 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100572 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700573
Vladimir Markoacb906d2018-05-30 10:23:49 +0100574 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700575 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100576 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100577 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100578 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700579
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700580 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700581
Ian Rogers52813c92012-10-11 11:50:38 -0700582 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700583 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700584 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100585 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100586 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700587 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000588 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700589
Alex Lightd6251582016-10-31 11:12:30 -0700590
591 // Setup dalvik.system.ClassExt
592 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
593 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100594 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000595 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700596
Mathieu Chartier66f19252012-09-18 08:57:04 -0700597 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700598 Handle<mirror::Class> object_array_string(hs.NewHandle(
599 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700600 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700601 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100602 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700603
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000604 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700605 // Create runtime resolution and imt conflict methods.
606 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000607 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
608 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700609
Ian Rogers23435d02012-09-24 11:23:12 -0700610 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
611 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
612 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800613 if (boot_class_path.empty()) {
614 *error_msg = "Boot classpath is empty.";
615 return false;
616 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800617 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800618 if (dex_file.get() == nullptr) {
619 *error_msg = "Null dex file.";
620 return false;
621 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700622 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800623 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700624 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700625
626 // now we can use FindSystemClass
627
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700628 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
629 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700630 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800631 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700632 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700633 quick_resolution_trampoline_ = GetQuickResolutionStub();
634 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
635 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700636 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700637
Alex Lightd6251582016-10-31 11:12:30 -0700638 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000639 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800640 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700641 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000642 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800643 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000644 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800645 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700646 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000647 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700648 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
649 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650
Ian Rogers23435d02012-09-24 11:23:12 -0700651 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100652 AllocAndSetPrimitiveArrayClassRoot(self,
653 java_lang_Class.Get(),
654 ClassRoot::kBooleanArrayClass,
655 ClassRoot::kPrimitiveBoolean,
656 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700657
Roland Levillain0e840272018-08-23 19:55:30 +0100658 AllocAndSetPrimitiveArrayClassRoot(
659 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700660
Roland Levillain0e840272018-08-23 19:55:30 +0100661 AllocAndSetPrimitiveArrayClassRoot(
662 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700663
Roland Levillain0e840272018-08-23 19:55:30 +0100664 AllocAndSetPrimitiveArrayClassRoot(
665 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800667 CheckSystemClass(self, int_array_class, "[I");
668 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700669
Roland Levillain0e840272018-08-23 19:55:30 +0100670 AllocAndSetPrimitiveArrayClassRoot(
671 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700672
Roland Levillain0e840272018-08-23 19:55:30 +0100673 AllocAndSetPrimitiveArrayClassRoot(
674 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700675
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800676 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
677 // in class_table_.
678 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700679
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800680 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
681 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700682
Ian Rogers23435d02012-09-24 11:23:12 -0700683 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700684 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800685 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700686 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800687 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700688 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
689 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100690 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
691 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700692
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700693 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
694 // suspension.
695 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000696 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700697 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000698 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700699 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000700 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700701 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000702 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700703
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700704 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100705 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700706
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800707 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700708
Ian Rogers23435d02012-09-24 11:23:12 -0700709 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100710 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
711 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700712
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700713 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100714 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700715 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100716 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700717
718 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700719 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
720 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100721 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700722
723 // Create java.lang.reflect.Constructor.class root and array root.
724 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
725 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100726 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700727 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
728 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100729 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700730
731 // Create java.lang.reflect.Method.class root and array root.
732 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
733 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100734 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700735 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
736 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100737 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700738
Orion Hodson005ac512017-10-24 15:43:43 +0100739 // Create java.lang.invoke.CallSite.class root
740 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
741 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100742 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100743
Narayan Kamathafa48272016-08-03 12:46:58 +0100744 // Create java.lang.invoke.MethodType.class root
745 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
746 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100747 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100748
749 // Create java.lang.invoke.MethodHandleImpl.class root
750 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
751 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100752 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100753 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100754
Orion Hodsonc069a302017-01-18 09:23:12 +0000755 // Create java.lang.invoke.MethodHandles.Lookup.class root
756 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
757 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100758 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000759
Orion Hodson005ac512017-10-24 15:43:43 +0100760 // Create java.lang.invoke.VarHandle.class root
761 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000762 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100763 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100764
765 // Create java.lang.invoke.FieldVarHandle.class root
766 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
767 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100768 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100769
770 // Create java.lang.invoke.ArrayElementVarHandle.class root
771 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
772 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100773 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100774
775 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
776 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
777 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100778 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100779
780 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
781 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
782 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100783 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000784
Narayan Kamath000e1882016-10-24 17:14:25 +0100785 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
786 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100787 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100788
Brian Carlstrom1f870082011-08-23 16:02:11 -0700789 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700790 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000791 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800792 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700793 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700794 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
795 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700796 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700797 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700798 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700799 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700800 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700801 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700802 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700803 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700804 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700805 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700806 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700807 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700808
Ian Rogers23435d02012-09-24 11:23:12 -0700809 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700810 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700811 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700812 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100813 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700814
jeffhao8cd6dda2012-02-22 10:15:34 -0800815 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700816 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100817 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100818 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700819 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100820 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
821 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
822 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700823 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000824 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
825 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700826
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700827 // Create conflict tables that depend on the class linker.
828 runtime->FixupConflictTables();
829
Ian Rogers98379392014-02-24 16:53:16 -0800830 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700831
Brian Carlstroma004aa92012-02-08 18:05:09 -0800832 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800833
834 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700835}
836
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700837static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
838 REQUIRES_SHARED(Locks::mutator_lock_) {
839 // Find String.<init> -> StringFactory bindings.
840 ObjPtr<mirror::Class> string_factory_class =
841 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
842 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100843 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700844 WellKnownClasses::InitStringInit(string_class, string_factory_class);
845 // Update the primordial thread.
846 self->InitStringEntryPoints();
847}
848
Ian Rogers98379392014-02-24 16:53:16 -0800849void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800850 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700851
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700852 CreateStringInitBindings(self, this);
853
Brian Carlstrom16192862011-09-12 17:50:06 -0700854 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700855 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700856 // as the types of the field can't be resolved prior to the runtime being
857 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700858 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100859 Handle<mirror::Class> java_lang_ref_Reference =
860 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700861 Handle<mirror::Class> java_lang_ref_FinalizerReference =
862 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800863
Mathieu Chartierc7853442015-03-27 14:35:38 -0700864 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700865 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
866 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700867
Mathieu Chartierc7853442015-03-27 14:35:38 -0700868 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700869 CHECK_STREQ(queue->GetName(), "queue");
870 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700871
Mathieu Chartierc7853442015-03-27 14:35:38 -0700872 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700873 CHECK_STREQ(queueNext->GetName(), "queueNext");
874 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700875
Mathieu Chartierc7853442015-03-27 14:35:38 -0700876 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700877 CHECK_STREQ(referent->GetName(), "referent");
878 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700879
Mathieu Chartierc7853442015-03-27 14:35:38 -0700880 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700881 CHECK_STREQ(zombie->GetName(), "zombie");
882 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700883
Brian Carlstroma663ea52011-08-19 23:33:41 -0700884 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100885 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700887 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700888 CHECK(klass != nullptr);
889 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700890 // note SetClassRoot does additional validation.
891 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700892 }
893
Vladimir Marko02610552018-06-04 14:38:00 +0100894 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700895
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700896 // disable the slow paths in FindClass and CreatePrimitiveClass now
897 // that Object, Class, and Object[] are setup
898 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700899
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700900 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
901 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
902 // ensure that the class will be initialized.
903 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700904 verifier::ClassVerifier::Init(); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700905
906 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
907 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
908 // Strange, but don't crash.
909 LOG(WARNING) << "Could not prepare StackOverflowError.";
910 self->ClearException();
911 }
912 }
913
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800914 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700915}
916
Vladimir Markodcfcce42018-06-27 10:00:28 +0000917void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100918 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
919 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700920 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700921 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100922 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700923 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700924 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000925 } else {
926 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700927 }
928 }
929}
930
Jeff Haodcdc85b2015-12-04 14:06:18 -0800931struct TrampolineCheckData {
932 const void* quick_resolution_trampoline;
933 const void* quick_imt_conflict_trampoline;
934 const void* quick_generic_jni_trampoline;
935 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700936 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800937 ArtMethod* m;
938 bool error;
939};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800940
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800941bool ClassLinker::InitFromBootImage(std::string* error_msg) {
942 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700943 CHECK(!init_done_);
944
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700945 Runtime* const runtime = Runtime::Current();
946 Thread* const self = Thread::Current();
947 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800948 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
949 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700950 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
951 if (!ValidPointerSize(pointer_size_unchecked)) {
952 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800953 return false;
954 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000955 const ImageHeader& image_header = spaces[0]->GetImageHeader();
956 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800957 if (!runtime->IsAotCompiler()) {
958 // Only the Aot compiler supports having an image with a different pointer size than the
959 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
960 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700961 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800962 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700963 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800964 sizeof(void*));
965 return false;
966 }
967 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000968 DCHECK(!runtime->HasResolutionMethod());
969 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
970 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
971 runtime->SetImtUnimplementedMethod(
972 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
973 runtime->SetCalleeSaveMethod(
974 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
975 CalleeSaveType::kSaveAllCalleeSaves);
976 runtime->SetCalleeSaveMethod(
977 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
978 CalleeSaveType::kSaveRefsOnly);
979 runtime->SetCalleeSaveMethod(
980 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
981 CalleeSaveType::kSaveRefsAndArgs);
982 runtime->SetCalleeSaveMethod(
983 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
984 CalleeSaveType::kSaveEverything);
985 runtime->SetCalleeSaveMethod(
986 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
987 CalleeSaveType::kSaveEverythingForClinit);
988 runtime->SetCalleeSaveMethod(
989 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
990 CalleeSaveType::kSaveEverythingForSuspendCheck);
991
Jeff Haodcdc85b2015-12-04 14:06:18 -0800992 std::vector<const OatFile*> oat_files =
993 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
994 DCHECK(!oat_files.empty());
995 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800996 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
997 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
998 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
999 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1000 if (kIsDebugBuild) {
1001 // Check that the other images use the same trampoline.
1002 for (size_t i = 1; i < oat_files.size(); ++i) {
1003 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1004 const void* ith_quick_resolution_trampoline =
1005 ith_oat_header.GetQuickResolutionTrampoline();
1006 const void* ith_quick_imt_conflict_trampoline =
1007 ith_oat_header.GetQuickImtConflictTrampoline();
1008 const void* ith_quick_generic_jni_trampoline =
1009 ith_oat_header.GetQuickGenericJniTrampoline();
1010 const void* ith_quick_to_interpreter_bridge_trampoline =
1011 ith_oat_header.GetQuickToInterpreterBridge();
1012 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1013 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1014 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1015 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1016 // Make sure that all methods in this image do not contain those trampolines as
1017 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1018 TrampolineCheckData data;
1019 data.error = false;
1020 data.pointer_size = GetImagePointerSize();
1021 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1022 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1023 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1024 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1025 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001026 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1027 if (obj->IsClass()) {
1028 ObjPtr<mirror::Class> klass = obj->AsClass();
1029 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1030 const void* entrypoint =
1031 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1032 if (entrypoint == data.quick_resolution_trampoline ||
1033 entrypoint == data.quick_imt_conflict_trampoline ||
1034 entrypoint == data.quick_generic_jni_trampoline ||
1035 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1036 data.m = &m;
1037 data.error = true;
1038 return;
1039 }
1040 }
1041 }
1042 };
1043 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001044 if (data.error) {
1045 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001046 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001047 *error_msg = "Found an ArtMethod with a bad entrypoint";
1048 return false;
1049 }
1050 }
1051 }
1052 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001053
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001054 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001055 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1056 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001057 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001058
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001059 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001060 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001061 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1062 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001063 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1064 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001065
Vladimir Marko4433c432018-12-04 14:57:47 +00001066 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1067 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001068 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001069 // Boot class loader, use a null handle.
1070 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001071 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001073 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001074 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 /*out*/&dex_files,
1076 error_msg)) {
1077 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001078 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001079 // Append opened dex files at the end.
1080 boot_dex_files_.insert(boot_dex_files_.end(),
1081 std::make_move_iterator(dex_files.begin()),
1082 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001083 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001084 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1085 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1086 }
Ian Rogers98379392014-02-24 16:53:16 -08001087 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001088
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001089 VLOG(startup) << __FUNCTION__ << " exiting";
1090 return true;
1091}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001092
Vladimir Marko4433c432018-12-04 14:57:47 +00001093void ClassLinker::AddExtraBootDexFiles(
1094 Thread* self,
1095 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1096 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1097 AppendToBootClassPath(self, *dex_file);
1098 boot_dex_files_.push_back(std::move(dex_file));
1099 }
1100}
1101
Jeff Hao5872d7c2016-04-27 11:07:41 -07001102bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001103 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001104 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001105 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1106 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001107}
1108
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001109static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1110 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001111 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001113 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001115 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116 DCHECK(dex_file_field != nullptr);
1117 DCHECK(dex_file_name_field != nullptr);
1118 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001119 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001120 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001121 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001122 // Null dex file means it was probably a jar with no dex files, return a null string.
1123 *out_name = nullptr;
1124 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001126 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001127 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001128 *out_name = name_object->AsString();
1129 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001130 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001131 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001132}
1133
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001134static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1135 ObjPtr<mirror::ClassLoader> class_loader,
1136 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1137 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001138 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001139 StackHandleScope<1> hs(soa.Self());
1140 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001141 // Get element names. Sets error to true on failure.
1142 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1143 REQUIRES_SHARED(Locks::mutator_lock_) {
1144 if (element == nullptr) {
1145 *error_msg = "Null dex element";
1146 *error = true; // Null element is a critical error.
1147 return false; // Had an error, stop the visit.
1148 }
1149 ObjPtr<mirror::String> name;
1150 if (!GetDexPathListElementName(element, &name)) {
1151 *error_msg = "Invalid dex path list element";
1152 *error = true; // Invalid element, make it a critical error.
1153 return false; // Stop the visit.
1154 }
1155 if (name != nullptr) {
1156 dex_files->push_front(name);
1157 }
1158 return true; // Continue with the next Element.
1159 };
1160 bool error = VisitClassLoaderDexElements(soa,
1161 handle,
1162 add_element_names,
1163 /*defaultReturn=*/ false);
1164 return !error;
1165}
1166
1167static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1168 ObjPtr<mirror::ClassLoader> image_class_loader,
1169 ObjPtr<mirror::ClassLoader> class_loader,
1170 std::string* error_msg)
1171 REQUIRES_SHARED(Locks::mutator_lock_) {
1172 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1173 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1174 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001175 return false;
1176 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001177 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1178 *error_msg = "Hierarchies don't match";
1179 return false;
1180 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1181 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1182 image_class_loader->PrettyTypeOf().c_str(),
1183 class_loader->PrettyTypeOf().c_str());
1184 return false;
1185 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1186 class_loader->GetClass()) {
1187 *error_msg = StringPrintf("Unknown class loader type %s",
1188 class_loader->PrettyTypeOf().c_str());
1189 // Unsupported class loader.
1190 return false;
1191 }
1192 return true;
1193}
1194
1195static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1196 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1197 std::string* error_msg)
1198 REQUIRES_SHARED(Locks::mutator_lock_) {
1199 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1200 std::equal(image_dex_files.begin(),
1201 image_dex_files.end(),
1202 loader_dex_files.begin(),
1203 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1204 REQUIRES_SHARED(Locks::mutator_lock_) {
1205 return lhs->Equals(rhs);
1206 });
1207 if (!equal) {
1208 VLOG(image) << "Image dex files " << image_dex_files.size();
1209 for (ObjPtr<mirror::String> name : image_dex_files) {
1210 VLOG(image) << name->ToModifiedUtf8();
1211 }
1212 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1213 for (ObjPtr<mirror::String> name : loader_dex_files) {
1214 VLOG(image) << name->ToModifiedUtf8();
1215 }
1216 *error_msg = "Mismatch in dex files";
1217 }
1218 return equal;
1219}
1220
1221static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1222 ObjPtr<mirror::ClassLoader> image_class_loader,
1223 ObjPtr<mirror::ClassLoader> class_loader,
1224 bool check_dex_file_names,
1225 std::string* error_msg)
1226 REQUIRES_SHARED(Locks::mutator_lock_) {
1227 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1228 return false;
1229 }
1230
1231 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1232 // No need to check further.
1233 return true;
1234 }
1235
1236 if (check_dex_file_names) {
1237 std::list<ObjPtr<mirror::String>> image_dex_files;
1238 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001239 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001240 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001241
1242 std::list<ObjPtr<mirror::String>> loader_dex_files;
1243 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1244 return false;
1245 }
1246
1247 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1248 return false;
1249 }
1250 }
1251
1252 ArtField* field =
1253 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1254 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1255 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1256 if (shared_libraries_image_loader == nullptr) {
1257 if (shared_libraries_loader != nullptr) {
1258 *error_msg = "Mismatch in shared libraries";
1259 return false;
1260 }
1261 } else if (shared_libraries_loader == nullptr) {
1262 *error_msg = "Mismatch in shared libraries";
1263 return false;
1264 } else {
1265 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1266 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1267 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1268 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1269 if (array1->GetLength() != array2->GetLength()) {
1270 *error_msg = "Mismatch in number of shared libraries";
1271 return false;
1272 }
1273
1274 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1275 // Do a full comparison of the class loaders, including comparing their dex files.
1276 if (!CompareClassLoaders(soa,
1277 array1->Get(i),
1278 array2->Get(i),
1279 /*check_dex_file_names=*/ true,
1280 error_msg)) {
1281 return false;
1282 }
1283 }
1284 }
1285
1286 // Do a full comparison of the class loaders, including comparing their dex files.
1287 if (!CompareClassLoaders(soa,
1288 image_class_loader->GetParent(),
1289 class_loader->GetParent(),
1290 /*check_dex_file_names=*/ true,
1291 error_msg)) {
1292 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001293 }
1294 return true;
1295}
1296
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001297class CHAOnDeleteUpdateClassVisitor {
1298 public:
1299 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1300 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1301 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1302 self_(Thread::Current()) {}
1303
1304 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1305 // This class is going to be unloaded. Tell CHA about it.
1306 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1307 return true;
1308 }
1309 private:
1310 const LinearAlloc* allocator_;
1311 const ClassHierarchyAnalysis* cha_;
1312 const PointerSize pointer_size_;
1313 const Thread* self_;
1314};
1315
Chris Wailes0c61be42018-09-26 17:27:34 -07001316/*
1317 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001318 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001319 */
1320class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001321 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001322 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001323 space_(space),
1324 intern_table_(*Runtime::Current()->GetInternTable()) {}
1325
Chris Wailes0c61be42018-09-26 17:27:34 -07001326 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001327 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001328 if (referred_obj != nullptr &&
1329 space_.HasAddress(referred_obj.Ptr()) &&
1330 referred_obj->IsString()) {
1331 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001332
1333 if (kIsDebugBuild) {
1334 // Saved to temporary variables to aid in debugging.
1335 ObjPtr<mirror::String> strong_lookup_result =
1336 intern_table_.LookupStrong(Thread::Current(), referred_str);
1337 ObjPtr<mirror::String> weak_lookup_result =
1338 intern_table_.LookupWeak(Thread::Current(), referred_str);
1339
1340 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1341 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001342 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001343 }
1344
Chris Wailes0c61be42018-09-26 17:27:34 -07001345 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001346 mirror::CompressedReference<mirror::Object>* root) const
1347 REQUIRES_SHARED(Locks::mutator_lock_) {
1348 if (!root->IsNull()) {
1349 VisitRoot(root);
1350 }
1351 }
1352
Chris Wailes0c61be42018-09-26 17:27:34 -07001353 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001354 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001355 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001356 }
1357
1358 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001359 void operator()(ObjPtr<mirror::Object> obj,
1360 MemberOffset offset,
1361 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001362 REQUIRES_SHARED(Locks::mutator_lock_) {
1363 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1364 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1365 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1366 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001367 ObjPtr<mirror::Object> referred_obj =
1368 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1369
1370 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001371 }
1372 }
1373
1374 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1375 ObjPtr<mirror::Reference> ref) const
1376 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001377 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001378 }
1379
Chris Wailes0c61be42018-09-26 17:27:34 -07001380 const gc::space::ImageSpace& space_;
1381 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001382};
1383
Chris Wailes0c61be42018-09-26 17:27:34 -07001384/*
1385 * This function verifies that string references in the AppImage have been
1386 * properly interned. To be considered properly interned a reference must
1387 * point to the same version of the string that the intern table does.
1388 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001389void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001390 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1391 const ImageHeader& image_header = space.GetImageHeader();
1392 const uint8_t* target_base = space.GetMemMap()->Begin();
1393 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001394
1395 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1396 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001397
1398 VerifyStringInterningVisitor visitor(space);
1399 bitmap->VisitMarkedRange(objects_begin,
1400 objects_end,
1401 [&space, &visitor](mirror::Object* obj)
1402 REQUIRES_SHARED(Locks::mutator_lock_) {
1403 if (space.HasAddress(obj)) {
1404 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001405 obj->VisitReferences</* kVisitNativeRoots= */ true,
1406 kVerifyNone,
1407 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001408 } else {
1409 // Don't visit native roots for non-dex-cache as they can't contain
1410 // native references to strings. This is verified during compilation
1411 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001412 obj->VisitReferences</* kVisitNativeRoots= */ false,
1413 kVerifyNone,
1414 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001415 }
1416 }
1417 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001418}
1419
Andreas Gampe2af99022017-04-25 08:32:59 -07001420// new_class_set is the set of classes that were read from the class table section in the image.
1421// If there was no class table section, it is null.
1422// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001423class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001424 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001425 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001426 ClassLinker* class_linker,
1427 gc::space::ImageSpace* space,
1428 Handle<mirror::ClassLoader> class_loader,
1429 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001430 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001431 REQUIRES(!Locks::dex_lock_)
1432 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001433
Chris Wailesfbeef462018-10-19 14:16:35 -07001434 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001435 REQUIRES_SHARED(Locks::mutator_lock_);
1436
1437 static void UpdateInternStrings(
1438 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001439 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001440 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1441 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001442};
1443
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001444void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001445 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001446 gc::space::ImageSpace* space,
1447 Handle<mirror::ClassLoader> class_loader,
1448 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001449 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001450 REQUIRES(!Locks::dex_lock_)
1451 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001452 ScopedTrace app_image_timing("AppImage:Updating");
1453
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001454 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001455 Runtime* const runtime = Runtime::Current();
1456 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001457 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001458 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001459 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001460 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001461 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001462 const size_t num_dex_caches = dex_caches->GetLength();
1463 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001464 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001465 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001466 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001467 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001468 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1469 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001470 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001471
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001472 if (!load_app_image_startup_cache) {
1473 dex_cache->ClearPreResolvedStrings();
1474 }
1475
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001476 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001477 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001478 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001479 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001480 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001481 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001482 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001483
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001484 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001485 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001486 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001487 DCHECK(it != new_class_set->end());
1488 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001489 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001490
Vladimir Marko1a1de672016-10-13 12:53:15 +01001491 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001492 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001493 DCHECK(it2 != new_class_set->end());
1494 DCHECK_EQ(it2->Read(), super_class);
1495 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001496
Vladimir Marko1a1de672016-10-13 12:53:15 +01001497 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1498 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001499 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1500 if (!class_linker->IsQuickResolutionStub(code) &&
1501 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001502 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001503 !m.IsNative()) {
1504 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001505 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001506 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001507
Vladimir Marko1a1de672016-10-13 12:53:15 +01001508 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1509 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001510 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1511 if (!class_linker->IsQuickResolutionStub(code) &&
1512 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001513 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001514 !m.IsNative()) {
1515 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001516 }
1517 }
1518 }
1519 }
1520 }
1521 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001522 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001523
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001524 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001525 HandleAppImageStrings(space);
1526
1527 if (kIsDebugBuild) {
1528 VerifyStringInterning(*space);
1529 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001530 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001531
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001532 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001533 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001534 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001535 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1536 header.VisitPackedArtMethods([&](ArtMethod& method)
1537 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1538 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1539 if (klass != nullptr) {
1540 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1541 }
1542 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001543 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001544}
1545
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001546void AppImageLoadingHelper::UpdateInternStrings(
1547 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001548 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001549 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1550 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001551 const ImageSection& sro_section =
1552 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1553 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001554 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001555
1556 VLOG(image)
1557 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1558 << num_string_offsets;
1559
Chris Wailesfbeef462018-10-19 14:16:35 -07001560 const auto* sro_base =
1561 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001562
1563 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001564 uint32_t base_offset = sro_base[offset_index].first;
1565
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001566 if (HasDexCacheStringNativeRefTag(base_offset)) {
1567 base_offset = ClearDexCacheNativeRefTags(base_offset);
1568 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001569
1570 ObjPtr<mirror::DexCache> dex_cache =
1571 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1572 uint32_t string_index = sro_base[offset_index].second;
1573
1574 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1575 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001576 DCHECK(referred_string != nullptr);
1577
Chris Wailesfbeef462018-10-19 14:16:35 -07001578 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001579 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001580 // This doesn't use SetResolvedString to maintain consistency with how
1581 // we load the string. The index from the source string must be
1582 // re-used due to the circular nature of the cache. Because we are not
1583 // using a helper function we need to mark the GC card manually.
1584 WriteBarrier::ForEveryFieldWrite(dex_cache);
1585 dex_cache->GetStrings()[string_index].store(
1586 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001587 } else if (!use_preresolved_strings) {
1588 dex_cache->GetStrings()[string_index].store(
1589 mirror::StringDexCachePair(intern_table->InternStrong(referred_string), source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001590 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001591 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001592 if (use_preresolved_strings) {
1593 base_offset = ClearDexCacheNativeRefTags(base_offset);
1594 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001595
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001596 ObjPtr<mirror::DexCache> dex_cache =
1597 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1598 uint32_t string_index = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001599
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001600 ObjPtr<mirror::String> referred_string =
1601 dex_cache->GetPreResolvedStrings()[string_index].Read();
1602 DCHECK(referred_string != nullptr);
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001603
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001604 auto it = intern_remap.find(referred_string.Ptr());
1605 if (it != intern_remap.end()) {
1606 // Because we are not using a helper function we need to mark the GC card manually.
1607 WriteBarrier::ForEveryFieldWrite(dex_cache);
1608 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1609 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001610 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001611 } else {
1612 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001613 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001614 DCHECK_ALIGNED(raw_member_offset, 2);
1615
1616 ObjPtr<mirror::Object> obj_ptr =
1617 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1618 MemberOffset member_offset(raw_member_offset);
1619 ObjPtr<mirror::String> referred_string =
1620 obj_ptr->GetFieldObject<mirror::String,
1621 kVerifyNone,
1622 kWithoutReadBarrier,
1623 /* kIsVolatile= */ false>(member_offset);
1624 DCHECK(referred_string != nullptr);
1625
1626 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001627 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001628 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1629 /* kCheckTransaction= */ false,
1630 kVerifyNone,
1631 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001632 } else if (!use_preresolved_strings) {
1633 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1634 /* kCheckTransaction= */ false,
1635 kVerifyNone,
1636 /* kIsVolatile= */ false>(
1637 member_offset,
1638 intern_table->InternStrong(referred_string));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001639 }
1640 }
1641 }
1642}
1643
Chris Wailesfbeef462018-10-19 14:16:35 -07001644void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001645 // Iterate over the string reference offsets stored in the image and intern
1646 // the strings they point to.
1647 ScopedTrace timing("AppImage:InternString");
1648
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001649 Runtime* const runtime = Runtime::Current();
1650 InternTable* const intern_table = runtime->GetInternTable();
1651
1652 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001653
1654 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1655 // for faster lookup.
1656 // TODO: Optimize with a bitmap or bloom filter
1657 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001658 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001659 REQUIRES_SHARED(Locks::mutator_lock_)
1660 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001661 const size_t non_boot_image_strings = intern_table->CountInterns(
1662 /*visit_boot_images=*/false,
1663 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001664 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001665 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1666 // Visit the smaller of the two sets to compute the intersection.
1667 if (interns.size() < non_boot_image_strings) {
1668 for (auto it = interns.begin(); it != interns.end(); ) {
1669 ObjPtr<mirror::String> string = it->Read();
1670 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1671 if (existing == nullptr) {
1672 existing = intern_table->LookupStrongLocked(string);
1673 }
1674 if (existing != nullptr) {
1675 intern_remap.Put(string.Ptr(), existing.Ptr());
1676 it = interns.erase(it);
1677 } else {
1678 ++it;
1679 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001680 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001681 } else {
1682 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1683 REQUIRES_SHARED(Locks::mutator_lock_)
1684 REQUIRES(Locks::intern_table_lock_) {
1685 auto it = interns.find(root);
1686 if (it != interns.end()) {
1687 ObjPtr<mirror::String> existing = root.Read();
1688 intern_remap.Put(it->Read(), existing.Ptr());
1689 it = interns.erase(it);
1690 }
1691 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1692 }
1693 // Sanity check to ensure correctness.
1694 if (kIsDebugBuild) {
1695 for (GcRoot<mirror::String>& root : interns) {
1696 ObjPtr<mirror::String> string = root.Read();
1697 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1698 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001699 }
1700 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001701 };
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001702
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001703 bool update_intern_strings;
1704 if (load_startup_cache) {
Mathieu Chartiere23b3882019-02-14 07:35:43 -08001705 VLOG(image) << "AppImage:load_startup_cache";
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001706 // Only add the intern table if we are using the startup cache. Otherwise,
1707 // UpdateInternStrings adds the strings to the intern table.
1708 intern_table->AddImageStringsToTable(space, func);
1709 update_intern_strings = kIsDebugBuild || !intern_remap.empty();
1710 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
1711 } else {
1712 update_intern_strings = true;
1713 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001714
1715 // For debug builds, always run the code below to get coverage.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001716 if (update_intern_strings) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001717 // Slow path case is when there are conflicting intern strings to fix up.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001718 UpdateInternStrings(space, /*use_preresolved_strings=*/ load_startup_cache, intern_remap);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001719 }
1720}
1721
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001722static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1723 const char* location,
1724 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001725 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001726 DCHECK(error_msg != nullptr);
1727 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001728 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001729 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001730 return std::unique_ptr<const DexFile>();
1731 }
1732 std::string inner_error_msg;
1733 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1734 if (dex_file == nullptr) {
1735 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1736 location,
1737 oat_file->GetLocation().c_str(),
1738 inner_error_msg.c_str());
1739 return std::unique_ptr<const DexFile>();
1740 }
1741
1742 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1743 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1744 location,
1745 dex_file->GetLocationChecksum(),
1746 oat_dex_file->GetDexFileLocationChecksum());
1747 return std::unique_ptr<const DexFile>();
1748 }
1749 return dex_file;
1750}
1751
1752bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1753 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1754 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001755 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001756 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001757 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001758 DCHECK(dex_caches_object != nullptr);
1759 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1760 dex_caches_object->AsObjectArray<mirror::DexCache>();
1761 const OatFile* oat_file = space->GetOatFile();
1762 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001763 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001764 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1765 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1766 dex_file_location.c_str(),
1767 error_msg);
1768 if (dex_file == nullptr) {
1769 return false;
1770 }
1771 dex_cache->SetDexFile(dex_file.get());
1772 out_dex_files->push_back(std::move(dex_file));
1773 }
1774 return true;
1775}
1776
Andreas Gampe0793bec2016-12-01 11:37:33 -08001777// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1778// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001779class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001780 public:
1781 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1782 REQUIRES_SHARED(Locks::mutator_lock_) {
1783 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001784 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1785 DCHECK(obj != nullptr);
1786 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1787 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1788 if (obj->IsClass()) {
1789 auto klass = obj->AsClass();
1790 for (ArtField& field : klass->GetIFields()) {
1791 CHECK_EQ(field.GetDeclaringClass(), klass);
1792 }
1793 for (ArtField& field : klass->GetSFields()) {
1794 CHECK_EQ(field.GetDeclaringClass(), klass);
1795 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001796 const PointerSize pointer_size = isc.pointer_size_;
1797 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001798 isc.SanityCheckArtMethod(&m, klass);
1799 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001800 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001801 if (vtable != nullptr) {
1802 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1803 }
1804 if (klass->ShouldHaveImt()) {
1805 ImTable* imt = klass->GetImt(pointer_size);
1806 for (size_t i = 0; i < ImTable::kSize; ++i) {
1807 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1808 }
1809 }
1810 if (klass->ShouldHaveEmbeddedVTable()) {
1811 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1812 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1813 }
1814 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001815 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001816 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1817 if (iftable->GetMethodArrayCount(i) > 0) {
1818 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1819 }
1820 }
1821 }
1822 };
1823 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001824 }
1825
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001826 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1827 ClassLinker* class_linker,
1828 mirror::MethodDexCacheType* arr,
1829 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001830 REQUIRES_SHARED(Locks::mutator_lock_) {
1831 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001832 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001833 }
1834
Andreas Gampe0793bec2016-12-01 11:37:33 -08001835 private:
1836 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1837 : spaces_(heap->GetBootImageSpaces()),
1838 pointer_size_(class_linker->GetImagePointerSize()) {
1839 space_begin_.reserve(spaces_.size());
1840 method_sections_.reserve(spaces_.size());
1841 runtime_method_sections_.reserve(spaces_.size());
1842 for (gc::space::ImageSpace* space : spaces_) {
1843 space_begin_.push_back(space->Begin());
1844 auto& header = space->GetImageHeader();
1845 method_sections_.push_back(&header.GetMethodsSection());
1846 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1847 }
1848 }
1849
1850 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1851 REQUIRES_SHARED(Locks::mutator_lock_) {
1852 if (m->IsRuntimeMethod()) {
1853 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1854 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1855 } else if (m->IsCopied()) {
1856 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1857 } else if (expected_class != nullptr) {
1858 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1859 }
1860 if (!spaces_.empty()) {
1861 bool contains = false;
1862 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1863 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1864 contains = method_sections_[i]->Contains(offset) ||
1865 runtime_method_sections_[i]->Contains(offset);
1866 }
1867 CHECK(contains) << m << " not found";
1868 }
1869 }
1870
1871 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1872 ObjPtr<mirror::Class> expected_class)
1873 REQUIRES_SHARED(Locks::mutator_lock_) {
1874 CHECK(arr != nullptr);
1875 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1876 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1877 // expected_class == null means we are a dex cache.
1878 if (expected_class != nullptr) {
1879 CHECK(method != nullptr);
1880 }
1881 if (method != nullptr) {
1882 SanityCheckArtMethod(method, expected_class);
1883 }
1884 }
1885 }
1886
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001887 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001888 REQUIRES_SHARED(Locks::mutator_lock_) {
1889 CHECK_EQ(arr != nullptr, size != 0u);
1890 if (arr != nullptr) {
1891 bool contains = false;
1892 for (auto space : spaces_) {
1893 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001894 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001895 contains = true;
1896 break;
1897 }
1898 }
1899 CHECK(contains);
1900 }
1901 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001902 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1903 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001904 // expected_class == null means we are a dex cache.
1905 if (method != nullptr) {
1906 SanityCheckArtMethod(method, nullptr);
1907 }
1908 }
1909 }
1910
1911 const std::vector<gc::space::ImageSpace*>& spaces_;
1912 const PointerSize pointer_size_;
1913
1914 // Cached sections from the spaces.
1915 std::vector<const uint8_t*> space_begin_;
1916 std::vector<const ImageSection*> method_sections_;
1917 std::vector<const ImageSection*> runtime_method_sections_;
1918};
1919
Andreas Gampebe7af222017-07-25 09:57:28 -07001920static void VerifyAppImage(const ImageHeader& header,
1921 const Handle<mirror::ClassLoader>& class_loader,
1922 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1923 ClassTable* class_table, gc::space::ImageSpace* space)
1924 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001925 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1926 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1927 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1928 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1929 << mirror::Class::PrettyClass(klass);
1930 }
1931 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001932 {
1933 // Verify that all direct interfaces of classes in the class table are also resolved.
1934 std::vector<ObjPtr<mirror::Class>> classes;
1935 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1936 REQUIRES_SHARED(Locks::mutator_lock_) {
1937 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1938 classes.push_back(klass);
1939 }
1940 return true;
1941 };
1942 class_table->Visit(verify_direct_interfaces_in_table);
1943 Thread* self = Thread::Current();
1944 for (ObjPtr<mirror::Class> klass : classes) {
1945 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1946 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1947 << klass->PrettyDescriptor() << " iface #" << i;
1948 }
1949 }
1950 }
1951 // Check that all non-primitive classes in dex caches are also in the class table.
1952 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1953 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1954 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1955 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1956 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1957 if (klass != nullptr && !klass->IsPrimitive()) {
1958 CHECK(class_table->Contains(klass))
1959 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1960 }
1961 }
1962 }
1963}
1964
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001965bool ClassLinker::AddImageSpace(
1966 gc::space::ImageSpace* space,
1967 Handle<mirror::ClassLoader> class_loader,
1968 jobjectArray dex_elements,
1969 const char* dex_location,
1970 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1971 std::string* error_msg) {
1972 DCHECK(out_dex_files != nullptr);
1973 DCHECK(error_msg != nullptr);
1974 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001975 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001976 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001977 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001978 DCHECK(dex_caches_object != nullptr);
1979 Runtime* const runtime = Runtime::Current();
1980 gc::Heap* const heap = runtime->GetHeap();
1981 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001982 // Check that the image is what we are expecting.
1983 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1984 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1985 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1986 image_pointer_size_);
1987 return false;
1988 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001989 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1990 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1991 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1992 expected_image_roots,
1993 header.GetImageRoots()->GetLength());
1994 return false;
1995 }
1996 StackHandleScope<3> hs(self);
1997 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1998 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1999 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2000 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002001 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002002 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2003 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002004 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002005 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002006 *error_msg = StringPrintf("Expected %d class roots but got %d",
2007 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002008 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002009 return false;
2010 }
2011 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002012 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2013 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2014 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2016 return false;
2017 }
2018 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002019 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002020 if (oat_file->GetOatHeader().GetDexFileCount() !=
2021 static_cast<uint32_t>(dex_caches->GetLength())) {
2022 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2023 "image";
2024 return false;
2025 }
2026
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002027 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002028 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2029 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002030 // TODO: Only store qualified paths.
2031 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002032 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002033 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2034 dex_file_location.c_str(),
2035 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002036 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002037 return false;
2038 }
2039
2040 if (app_image) {
2041 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2042 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002043 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002044 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002045 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002046 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002047 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002048 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002049 }
2050 }
2051 } else {
2052 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002053 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2054 this,
2055 dex_cache->GetResolvedMethods(),
2056 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002057 }
2058 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002059 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002060 }
2061 out_dex_files->push_back(std::move(dex_file));
2062 }
2063
2064 if (app_image) {
2065 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002066 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002067 // Check that the class loader resolves the same way as the ones in the image.
2068 // Image class loader [A][B][C][image dex files]
2069 // Class loader = [???][dex_elements][image dex files]
2070 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002071 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002072 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2073 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2074 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002075 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2076 *error_msg = "Unexpected BootClassLoader in app image";
2077 return false;
2078 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002079 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2080 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2081 // special case the comparison of dex files of the two class loaders, but then do full
2082 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002083 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002084 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002085 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2086 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2087 if (element != nullptr) {
2088 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002089 ObjPtr<mirror::String> name;
2090 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2091 loader_dex_file_names.push_back(name);
2092 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002093 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002094 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002095 std::string temp_error_msg;
2096 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2097 bool success = GetDexFileNames(
2098 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2099 if (success) {
2100 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2101 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2102 static_cast<size_t>(dex_caches->GetLength()));
2103 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2104 image_dex_file_names.resize(image_count);
2105 success = success && CompareDexFiles(image_dex_file_names,
2106 loader_dex_file_names,
2107 &temp_error_msg);
2108 success = success && CompareClassLoaders(soa,
2109 image_class_loader.Get(),
2110 class_loader.Get(),
2111 /*check_dex_file_names=*/ false,
2112 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002113 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002114 if (!success) {
2115 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2116 temp_error_msg.c_str());
2117 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002118 }
2119 }
2120
2121 if (kSanityCheckObjects) {
2122 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002123 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002124 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2125 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2126 if (field != nullptr) {
2127 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2128 }
2129 }
2130 }
2131 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002132 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002133 }
2134 }
2135
2136 // Set entry point to interpreter if in InterpretOnly mode.
2137 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002138 // Set image methods' entry point to interpreter.
2139 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2140 if (!method.IsRuntimeMethod()) {
2141 DCHECK(method.GetDeclaringClass() != nullptr);
2142 if (!method.IsNative() && !method.IsResolutionMethod()) {
2143 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2144 image_pointer_size_);
2145 }
2146 }
2147 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002148 }
2149
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002150 ClassTable* class_table = nullptr;
2151 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002152 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002153 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002154 }
2155 // If we have a class table section, read it and use it for verification in
2156 // UpdateAppImageClassLoadersAndDexCaches.
2157 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002158 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002159 const bool added_class_table = class_table_section.Size() > 0u;
2160 if (added_class_table) {
2161 const uint64_t start_time2 = NanoTime();
2162 size_t read_count = 0;
2163 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2164 /*make copy*/false,
2165 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002166 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002167 }
2168 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002169 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002170
2171 {
2172 ScopedTrace trace("AppImage:UpdateClassLoaders");
2173 // Update class loader and resolved strings. If added_class_table is false, the resolved
2174 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002175 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002176 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002177 // Note: We probably don't need the read barrier unless we copy the app image objects into
2178 // the region space.
2179 ObjPtr<mirror::Class> klass(root.Read());
2180 // Do not update class loader for boot image classes where the app image
2181 // class loader is only the initiating loader but not the defining loader.
2182 // Avoid read barrier since we are comparing against null.
2183 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2184 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2185 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002186 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002187 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002188
Vladimir Marko305c38b2018-02-14 11:50:07 +00002189 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002190 // Every class in the app image has initially SubtypeCheckInfo in the
2191 // Uninitialized state.
2192 //
2193 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2194 // after class initialization is complete. The app image ClassStatus as-is
2195 // are almost all ClassStatus::Initialized, and being in the
2196 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2197 //
2198 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2199 //
2200 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002201 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002202 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2203 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002204 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002205 }
2206 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002207 }
2208 if (!oat_file->GetBssGcRoots().empty()) {
2209 // Insert oat file to class table for visiting .bss GC roots.
2210 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002211 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002212
Mathieu Chartier69731002016-03-02 16:08:31 -08002213 if (added_class_table) {
2214 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2215 class_table->AddClassSet(std::move(temp_set));
2216 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002217
Mathieu Chartier69731002016-03-02 16:08:31 -08002218 if (kIsDebugBuild && app_image) {
2219 // This verification needs to happen after the classes have been added to the class loader.
2220 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002221 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002222 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002223 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002224
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002225 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002226 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002227}
2228
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002229bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002230 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2231 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002232}
2233
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002234void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002235 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2236 // enabling tracing requires the mutator lock, there are no race conditions here.
2237 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002238 Thread* const self = Thread::Current();
2239 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002240 if (kUseReadBarrier) {
2241 // We do not track new roots for CC.
2242 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2243 kVisitRootFlagClearRootLog |
2244 kVisitRootFlagStartLoggingNewRoots |
2245 kVisitRootFlagStopLoggingNewRoots));
2246 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002247 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002248 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2249 // There is 3 GC cases to handle:
2250 // Non moving concurrent:
2251 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002252 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002253 //
2254 // Moving non-concurrent:
2255 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2256 // To prevent missing roots, this case needs to ensure that there is no
2257 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2258 // class which is in the class table.
2259 //
2260 // Moving concurrent:
2261 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2262 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002263 //
2264 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2265 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2266 // these objects.
2267 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002268 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002269 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002270 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002271 for (const ClassLoaderData& data : class_loaders_) {
2272 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2273 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2274 }
2275 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002276 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002277 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002278 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002279 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002280 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002281 // Concurrent moving GC marked new roots through the to-space invariant.
2282 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002283 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002284 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2285 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2286 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2287 if (old_ref != nullptr) {
2288 DCHECK(old_ref->IsClass());
2289 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2290 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2291 // Concurrent moving GC marked new roots through the to-space invariant.
2292 CHECK_EQ(new_ref, old_ref);
2293 }
2294 }
2295 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002296 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002297 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002298 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002299 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002300 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002301 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002302 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002303 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002304 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002305 }
2306 // We deliberately ignore the class roots in the image since we
2307 // handle image roots by using the MS/CMS rescanning of dirty cards.
2308}
2309
Brian Carlstroma663ea52011-08-19 23:33:41 -07002310// Keep in sync with InitCallback. Anything we visit, we need to
2311// reinit references to when reinitializing a ClassLinker from a
2312// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002313void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002314 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002315 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002316 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2317 // unloading if we are marking roots.
2318 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002319}
2320
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002321class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2322 public:
2323 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2324 : visitor_(visitor),
2325 done_(false) {}
2326
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002327 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002328 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002329 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002330 if (!done_ && class_table != nullptr) {
2331 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2332 if (!class_table->Visit(visitor)) {
2333 // If the visitor ClassTable returns false it means that we don't need to continue.
2334 done_ = true;
2335 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002336 }
2337 }
2338
2339 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002340 // Class visitor that limits the class visits from a ClassTable to the classes with
2341 // the provided defining class loader. This filter is used to avoid multiple visits
2342 // of the same class which can be recorded for multiple initiating class loaders.
2343 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2344 public:
2345 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2346 ClassVisitor* visitor)
2347 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2348
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002349 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002350 if (klass->GetClassLoader() != defining_class_loader_) {
2351 return true;
2352 }
2353 return (*visitor_)(klass);
2354 }
2355
2356 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2357 ClassVisitor* const visitor_;
2358 };
2359
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002360 ClassVisitor* const visitor_;
2361 // If done is true then we don't need to do any more visiting.
2362 bool done_;
2363};
2364
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002365void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002366 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002367 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2368 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002369 }
2370}
2371
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002372void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002373 Thread* const self = Thread::Current();
2374 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2375 // Not safe to have thread suspension when we are holding a lock.
2376 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002377 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002378 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002379 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002380 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002381 }
2382}
2383
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002384class GetClassesInToVector : public ClassVisitor {
2385 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002386 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002387 classes_.push_back(klass);
2388 return true;
2389 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002390 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002391};
2392
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002393class GetClassInToObjectArray : public ClassVisitor {
2394 public:
2395 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2396 : arr_(arr), index_(0) {}
2397
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002398 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002399 ++index_;
2400 if (index_ <= arr_->GetLength()) {
2401 arr_->Set(index_ - 1, klass);
2402 return true;
2403 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002404 return false;
2405 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002406
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002407 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002408 return index_ <= arr_->GetLength();
2409 }
2410
2411 private:
2412 mirror::ObjectArray<mirror::Class>* const arr_;
2413 int32_t index_;
2414};
2415
2416void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002417 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2418 // is avoiding duplicates.
2419 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002420 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002421 GetClassesInToVector accumulator;
2422 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002423 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002424 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002425 return;
2426 }
2427 }
2428 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002429 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002430 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002431 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002432 // We size the array assuming classes won't be added to the class table during the visit.
2433 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002434 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002435 size_t class_table_size;
2436 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002437 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002438 // Add 100 in case new classes get loaded when we are filling in the object array.
2439 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002440 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002441 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002442 classes.Assign(
2443 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002444 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002445 GetClassInToObjectArray accumulator(classes.Get());
2446 VisitClasses(&accumulator);
2447 if (accumulator.Succeeded()) {
2448 break;
2449 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002450 }
2451 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2452 // If the class table shrank during creation of the clases array we expect null elements. If
2453 // the class table grew then the loop repeats. If classes are created after the loop has
2454 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002455 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002456 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002457 return;
2458 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002459 }
2460 }
2461}
2462
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002463ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002464 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002465 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002466 // CHA unloading analysis is not needed. No negative consequences are expected because
2467 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002468 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002469 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002470 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002471}
2472
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002473void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002474 Runtime* const runtime = Runtime::Current();
2475 JavaVMExt* const vm = runtime->GetJavaVM();
2476 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002477 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002478 if (runtime->GetJit() != nullptr) {
2479 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2480 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002481 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002482 code_cache->RemoveMethodsIn(self, *data.allocator);
2483 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002484 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002485 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002486 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002487 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002488 // Cleanup references to single implementation ArtMethods that will be deleted.
2489 if (cleanup_cha) {
2490 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2491 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2492 }
2493
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002494 delete data.allocator;
2495 delete data.class_table;
2496}
2497
Vladimir Markobcf17522018-06-01 13:14:32 +01002498ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2499 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002500 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002501 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2502 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002503}
2504
Vladimir Markobcf17522018-06-01 13:14:32 +01002505ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2506 Thread* self,
2507 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002508 StackHandleScope<1> hs(self);
2509 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002510 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002511 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002512 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002513 self->AssertPendingOOMException();
2514 return nullptr;
2515 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002516 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002517 if (location == nullptr) {
2518 self->AssertPendingOOMException();
2519 return nullptr;
2520 }
2521 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002522 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002523}
2524
Vladimir Markobcf17522018-06-01 13:14:32 +01002525ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2526 const DexFile& dex_file,
2527 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002528 ObjPtr<mirror::String> location = nullptr;
2529 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002530 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002531 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002532 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002533 mirror::DexCache::InitializeDexCache(self,
2534 dex_cache,
2535 location,
2536 &dex_file,
2537 linear_alloc,
2538 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002539 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002540 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002541}
2542
Roland Levillain0e840272018-08-23 19:55:30 +01002543template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002544ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2545 ObjPtr<mirror::Class> java_lang_Class,
2546 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002547 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002548 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002549 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002550 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002551 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2552 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002553 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002554 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002555 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002556 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002557 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002558}
2559
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002560ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002561 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002562}
2563
Roland Levillain0e840272018-08-23 19:55:30 +01002564ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2565 ObjPtr<mirror::Class> java_lang_Class) {
2566 // We make this class non-movable for the unlikely case where it were to be
2567 // moved by a sticky-bit (minor) collection when using the Generational
2568 // Concurrent Copying (CC) collector, potentially creating a stale reference
2569 // in the `klass_` field of one of its instances allocated in the Large-Object
2570 // Space (LOS) -- see the comment about the dirty card scanning logic in
2571 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002572 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002573 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2574}
2575
Vladimir Markobcf17522018-06-01 13:14:32 +01002576ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002577 Thread* self,
2578 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002579 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002580 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002581}
2582
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002583ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2584 const char* descriptor,
2585 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002586 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002587 if (kIsDebugBuild) {
2588 StackHandleScope<1> hs(self);
2589 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2590 Thread::PoisonObjectPointersIfDebug();
2591 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002592
2593 // For temporary classes we must wait for them to be retired.
2594 if (init_done_ && klass->IsTemp()) {
2595 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002596 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002597 ThrowEarlierClassFailure(klass);
2598 return nullptr;
2599 }
2600 StackHandleScope<1> hs(self);
2601 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2602 ObjectLock<mirror::Class> lock(self, h_class);
2603 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002604 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002605 lock.WaitIgnoringInterrupts();
2606 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002607 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002608 ThrowEarlierClassFailure(h_class.Get());
2609 return nullptr;
2610 }
2611 CHECK(h_class->IsRetired());
2612 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002613 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002614 }
2615
Brian Carlstromaded5f72011-10-07 17:15:04 -07002616 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002617 size_t index = 0;
2618 // Maximum number of yield iterations until we start sleeping.
2619 static const size_t kNumYieldIterations = 1000;
2620 // How long each sleep is in us.
2621 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002622 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002623 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002624 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002625 {
2626 ObjectTryLock<mirror::Class> lock(self, h_class);
2627 // Can not use a monitor wait here since it may block when returning and deadlock if another
2628 // thread has locked klass.
2629 if (lock.Acquired()) {
2630 // Check for circular dependencies between classes, the lock is required for SetStatus.
2631 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2632 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002633 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002634 return nullptr;
2635 }
2636 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002637 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002638 {
2639 // Handle wrapper deals with klass moving.
2640 ScopedThreadSuspension sts(self, kSuspended);
2641 if (index < kNumYieldIterations) {
2642 sched_yield();
2643 } else {
2644 usleep(kSleepDurationUS);
2645 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002646 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002647 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002648 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002649
Vladimir Marko72ab6842017-01-20 19:32:50 +00002650 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002651 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002652 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002653 }
2654 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002655 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002656 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002657 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002658}
2659
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002660using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002661
2662// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002663ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002664 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002665 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002666 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002667 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002668 return ClassPathEntry(dex_file, dex_class_def);
2669 }
2670 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002671 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002672}
2673
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002674bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2675 Thread* self,
2676 const char* descriptor,
2677 size_t hash,
2678 Handle<mirror::ClassLoader> class_loader,
2679 /*out*/ ObjPtr<mirror::Class>* result) {
2680 ArtField* field =
2681 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2682 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2683 if (raw_shared_libraries == nullptr) {
2684 return true;
2685 }
2686
2687 StackHandleScope<2> hs(self);
2688 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2689 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2690 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2691 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2692 temp_loader.Assign(shared_libraries->Get(i));
2693 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2694 return false; // One of the shared libraries is not supported.
2695 }
2696 if (*result != nullptr) {
2697 return true; // Found the class up the chain.
2698 }
2699 }
2700 return true;
2701}
2702
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002703bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2704 Thread* self,
2705 const char* descriptor,
2706 size_t hash,
2707 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002708 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002709 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002710 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002711 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002712 return true;
2713 }
2714
David Brazdil05909d82018-12-06 16:25:16 +00002715 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002716 // For regular path or dex class loader the search order is:
2717 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002718 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002719 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002720
Calin Juravlecdd49122017-07-05 20:09:53 -07002721 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2722 StackHandleScope<1> hs(self);
2723 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2724 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2725 return false; // One of the parents is not supported.
2726 }
2727 if (*result != nullptr) {
2728 return true; // Found the class up the chain.
2729 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002730
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002731 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2732 return false; // One of the shared library loader is not supported.
2733 }
2734 if (*result != nullptr) {
2735 return true; // Found the class in a shared library.
2736 }
2737
Calin Juravlecdd49122017-07-05 20:09:53 -07002738 // Search the current class loader classpath.
2739 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002740 return true;
2741 }
2742
Calin Juravlecdd49122017-07-05 20:09:53 -07002743 if (IsDelegateLastClassLoader(soa, class_loader)) {
2744 // For delegate last, the search order is:
2745 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002746 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002747 // - class loader dex files
2748 // - parent
2749 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2750 if (*result != nullptr) {
2751 return true; // The class is part of the boot class path.
2752 }
2753
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002754 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2755 return false; // One of the shared library loader is not supported.
2756 }
2757 if (*result != nullptr) {
2758 return true; // Found the class in a shared library.
2759 }
2760
Calin Juravlecdd49122017-07-05 20:09:53 -07002761 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2762 if (*result != nullptr) {
2763 return true; // Found the class in the current class loader
2764 }
2765
2766 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2767 StackHandleScope<1> hs(self);
2768 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2769 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2770 }
2771
2772 // Unsupported class loader.
2773 *result = nullptr;
2774 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002775}
2776
2777// Finds the class in the boot class loader.
2778// If the class is found the method returns the resolved class. Otherwise it returns null.
2779ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2780 const char* descriptor,
2781 size_t hash) {
2782 ObjPtr<mirror::Class> result = nullptr;
2783 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2784 if (pair.second != nullptr) {
2785 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2786 if (klass != nullptr) {
2787 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002788 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002789 result = DefineClass(self,
2790 descriptor,
2791 hash,
2792 ScopedNullHandle<mirror::ClassLoader>(),
2793 *pair.first,
2794 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002795 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002796 if (result == nullptr) {
2797 CHECK(self->IsExceptionPending()) << descriptor;
2798 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002799 }
2800 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002801 return result;
2802}
Andreas Gampef865ea92015-04-13 22:14:19 -07002803
Calin Juravle415dc3d2017-06-28 11:03:12 -07002804ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2805 ScopedObjectAccessAlreadyRunnable& soa,
2806 const char* descriptor,
2807 size_t hash,
2808 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002809 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2810 IsInMemoryDexClassLoader(soa, class_loader) ||
2811 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002812 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002813
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002814 ObjPtr<mirror::Class> ret;
2815 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002816 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002817 if (dex_class_def != nullptr) {
2818 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2819 descriptor,
2820 hash,
2821 class_loader,
2822 *cp_dex_file,
2823 *dex_class_def);
2824 if (klass == nullptr) {
2825 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2826 soa.Self()->ClearException();
2827 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002828 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002829 ret = klass;
2830 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002831 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002832 return true; // Continue with the next DexFile.
2833 };
2834
2835 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2836 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002837}
2838
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002839ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2840 const char* descriptor,
2841 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002842 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002843 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002844 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002845 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002846 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002847 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2848 // for primitive classes that aren't backed by dex files.
2849 return FindPrimitiveClass(descriptor[0]);
2850 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002851 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002852 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002853 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002854 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002855 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002856 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002857 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002858 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002859 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002860 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002861 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002862 return DefineClass(self,
2863 descriptor,
2864 hash,
2865 ScopedNullHandle<mirror::ClassLoader>(),
2866 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002867 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002868 } else {
2869 // The boot class loader is searched ahead of the application class loader, failures are
2870 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2871 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002872 ObjPtr<mirror::Throwable> pre_allocated =
2873 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002874 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002875 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002876 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002877 }
2878 ObjPtr<mirror::Class> result_ptr;
2879 bool descriptor_equals;
2880 if (descriptor[0] == '[') {
2881 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2882 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2883 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2884 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002885 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002886 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002887 bool known_hierarchy =
2888 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2889 if (result_ptr != nullptr) {
2890 // The chain was understood and we found the class. We still need to add the class to
2891 // the class table to protect from racy programs that can try and redefine the path list
2892 // which would change the Class<?> returned for subsequent evaluation of const-class.
2893 DCHECK(known_hierarchy);
2894 DCHECK(result_ptr->DescriptorEquals(descriptor));
2895 descriptor_equals = true;
2896 } else {
2897 // Either the chain wasn't understood or the class wasn't found.
2898 //
2899 // If the chain was understood but we did not find the class, let the Java-side
2900 // rediscover all this and throw the exception with the right stack trace. Note that
2901 // the Java-side could still succeed for racy programs if another thread is actively
2902 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002903
Alex Light185a4612018-10-04 15:54:25 -07002904 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002905 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002906 // Oops, we can't call into java so we can't run actual class-loader code.
2907 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002908 ObjPtr<mirror::Throwable> pre_allocated =
2909 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2910 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002911 return nullptr;
2912 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002913
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002914 // Inlined DescriptorToDot(descriptor) with extra validation.
2915 //
2916 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2917 // the DescriptorEquals() check below and give a confusing error message. For example,
2918 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2919 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2920 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2921 size_t descriptor_length = strlen(descriptor);
2922 if (UNLIKELY(descriptor[0] != 'L') ||
2923 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2924 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2925 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2926 return nullptr;
2927 }
2928 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2929 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2930
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002931 ScopedLocalRef<jobject> class_loader_object(
2932 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002933 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2934 {
2935 ScopedThreadStateChange tsc(self, kNative);
2936 ScopedLocalRef<jobject> class_name_object(
2937 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2938 if (class_name_object.get() == nullptr) {
2939 DCHECK(self->IsExceptionPending()); // OOME.
2940 return nullptr;
2941 }
2942 CHECK(class_loader_object.get() != nullptr);
2943 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2944 WellKnownClasses::java_lang_ClassLoader_loadClass,
2945 class_name_object.get()));
2946 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002947 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002948 // broken loader - throw NPE to be compatible with Dalvik
2949 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2950 class_name_string.c_str()).c_str());
2951 return nullptr;
2952 }
2953 result_ptr = soa.Decode<mirror::Class>(result.get());
2954 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002955 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002956 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002957 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002958
2959 if (self->IsExceptionPending()) {
2960 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2961 // However, to comply with the RI behavior, first check if another thread succeeded.
2962 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2963 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2964 self->ClearException();
2965 return EnsureResolved(self, descriptor, result_ptr);
2966 }
2967 return nullptr;
2968 }
2969
2970 // Try to insert the class to the class table, checking for mismatch.
2971 ObjPtr<mirror::Class> old;
2972 {
2973 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2974 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2975 old = class_table->Lookup(descriptor, hash);
2976 if (old == nullptr) {
2977 old = result_ptr; // For the comparison below, after releasing the lock.
2978 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002979 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002980 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002981 } // else throw below, after releasing the lock.
2982 }
2983 }
2984 if (UNLIKELY(old != result_ptr)) {
2985 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2986 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2987 mirror::Class* loader_class = class_loader->GetClass();
2988 const char* loader_class_name =
2989 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2990 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2991 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2992 << DescriptorToDot(descriptor) << "\").";
2993 return EnsureResolved(self, descriptor, old);
2994 }
2995 if (UNLIKELY(!descriptor_equals)) {
2996 std::string result_storage;
2997 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2998 std::string loader_storage;
2999 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3000 ThrowNoClassDefFoundError(
3001 "Initiating class loader of type %s returned class %s instead of %s.",
3002 DescriptorToDot(loader_class_name).c_str(),
3003 DescriptorToDot(result_name).c_str(),
3004 DescriptorToDot(descriptor).c_str());
3005 return nullptr;
3006 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003007 // Success.
3008 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003009}
3010
Vladimir Markob9c29f62019-03-20 14:22:51 +00003011static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3012 std::string_view descriptor_sv(descriptor);
3013 // Reserved conscrypt packages (includes sub-packages under these paths).
3014 return StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3015 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/");
3016}
3017
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003018ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3019 const char* descriptor,
3020 size_t hash,
3021 Handle<mirror::ClassLoader> class_loader,
3022 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003023 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003024 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003025 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003026
Brian Carlstromaded5f72011-10-07 17:15:04 -07003027 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003028 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003029 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003030 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003031 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003032 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003033 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003034 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003035 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003036 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003037 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003038 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003039 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003040 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003041 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003042 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003043 }
3044
Vladimir Markob9c29f62019-03-20 14:22:51 +00003045 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3046 // some runtime modules. Prevent definition of classes in app class loader that could clash
3047 // with these modules as these classes could be resolved differently during execution.
3048 if (class_loader != nullptr &&
3049 Runtime::Current()->IsAotCompiler() &&
3050 IsReservedBootClassPathDescriptor(descriptor)) {
3051 ObjPtr<mirror::Throwable> pre_allocated =
3052 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3053 self->SetException(pre_allocated);
3054 return nullptr;
3055 }
3056
Alex Lighte9f61032018-09-24 16:04:51 -07003057 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3058 // code to be executed. We put it up here so we can avoid all the allocations associated with
3059 // creating the class. This can happen with (eg) jit threads.
3060 if (!self->CanLoadClasses()) {
3061 // Make sure we don't try to load anything, potentially causing an infinite loop.
3062 ObjPtr<mirror::Throwable> pre_allocated =
3063 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3064 self->SetException(pre_allocated);
3065 return nullptr;
3066 }
3067
Andreas Gampefa4333d2017-02-14 11:10:34 -08003068 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003069 // Allocate a class with the status of not ready.
3070 // Interface object should get the right size here. Regular class will
3071 // figure out the right size later and be replaced with one of the right
3072 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003073 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003074 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003075 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003076 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003077 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003078 }
Alex Lightb0f11922017-01-23 14:25:17 -08003079 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3080 // nothing.
3081 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003082 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003083 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3084 // will only be called once.
3085 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3086 klass,
3087 class_loader,
3088 dex_file,
3089 dex_class_def,
3090 &new_dex_file,
3091 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003092 // Check to see if an exception happened during runtime callbacks. Return if so.
3093 if (self->IsExceptionPending()) {
3094 return nullptr;
3095 }
Alex Lightb0f11922017-01-23 14:25:17 -08003096 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003097 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003098 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003099 return nullptr;
3100 }
3101 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003102 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003103
Jeff Hao848f70a2014-01-15 13:49:50 -08003104 // Mark the string class by setting its access flag.
3105 if (UNLIKELY(!init_done_)) {
3106 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3107 klass->SetStringClass();
3108 }
3109 }
3110
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003111 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003112 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003113 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003114 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003115
Mathieu Chartier590fee92013-09-13 13:46:47 -07003116 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003117 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003118 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003119 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3120 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003121 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003122 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003123
Mathieu Chartierc7853442015-03-27 14:35:38 -07003124 // Load the fields and other things after we are inserted in the table. This is so that we don't
3125 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3126 // other reason is that the field roots are only visited from the class table. So we need to be
3127 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003128 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003129 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003130 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003131 // An exception occured during load, set status to erroneous while holding klass' lock in case
3132 // notification is necessary.
3133 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003134 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003135 }
3136 return nullptr;
3137 }
3138
Brian Carlstromaded5f72011-10-07 17:15:04 -07003139 // Finish loading (if necessary) by finding parents
3140 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003141 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003142 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003143 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003144 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003145 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003146 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003147 }
3148 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003149
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003150 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003151 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003152 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003153
Brian Carlstromaded5f72011-10-07 17:15:04 -07003154 // Link the class (if necessary)
3155 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003156 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003157 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003158
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003159 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003160 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003161 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003162 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003163 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003164 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003165 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003166 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003167 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003168 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003169 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003170
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003171 // Instrumentation may have updated entrypoints for all methods of all
3172 // classes. However it could not update methods of this class while we
3173 // were loading it. Now the class is resolved, we can update entrypoints
3174 // as required by instrumentation.
3175 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3176 // We must be in the kRunnable state to prevent instrumentation from
3177 // suspending all threads to update entrypoints while we are doing it
3178 // for this class.
3179 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003180 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003181 }
3182
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003183 /*
3184 * We send CLASS_PREPARE events to the debugger from here. The
3185 * definition of "preparation" is creating the static fields for a
3186 * class and initializing them to the standard default values, but not
3187 * executing any code (that comes later, during "initialization").
3188 *
3189 * We did the static preparation in LinkClass.
3190 *
3191 * The class has been prepared and resolved but possibly not yet verified
3192 * at this point.
3193 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003194 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003195
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003196 // Notify native debugger of the new class and its layout.
3197 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3198
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003199 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003200}
3201
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003202uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003203 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003204 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003205 size_t num_8 = 0;
3206 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003207 size_t num_32 = 0;
3208 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003209 ClassAccessor accessor(dex_file, dex_class_def);
3210 // We allow duplicate definitions of the same field in a class_data_item
3211 // but ignore the repeated indexes here, b/21868015.
3212 uint32_t last_field_idx = dex::kDexNoIndex;
3213 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3214 uint32_t field_idx = field.GetIndex();
3215 // Ordering enforced by DexFileVerifier.
3216 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3217 if (UNLIKELY(field_idx == last_field_idx)) {
3218 continue;
3219 }
3220 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003221 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003222 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3223 char c = descriptor[0];
3224 switch (c) {
3225 case 'L':
3226 case '[':
3227 num_ref++;
3228 break;
3229 case 'J':
3230 case 'D':
3231 num_64++;
3232 break;
3233 case 'I':
3234 case 'F':
3235 num_32++;
3236 break;
3237 case 'S':
3238 case 'C':
3239 num_16++;
3240 break;
3241 case 'B':
3242 case 'Z':
3243 num_8++;
3244 break;
3245 default:
3246 LOG(FATAL) << "Unknown descriptor: " << c;
3247 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003248 }
3249 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003250 return mirror::Class::ComputeClassSize(false,
3251 0,
3252 num_8,
3253 num_16,
3254 num_32,
3255 num_64,
3256 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003257 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003258}
3259
Alex Lightfc49fec2018-01-16 22:28:36 +00003260// Special case to get oat code without overwriting a trampoline.
3261const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003262 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003263 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003264 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003265 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003266 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3267 if (code != nullptr) {
3268 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003269 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003270 if (method->IsNative()) {
3271 // No code and native? Use generic trampoline.
3272 return GetQuickGenericJniStub();
3273 }
3274 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003275}
3276
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003277bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003278 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003279 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3280 return false;
3281 }
3282
Elliott Hughes956af0f2014-12-11 14:34:28 -08003283 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003284 return true;
3285 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003286
3287 Runtime* runtime = Runtime::Current();
3288 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3289 if (instr->InterpretOnly()) {
3290 return true;
3291 }
3292
3293 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3294 // Doing this check avoids doing compiled/interpreter transitions.
3295 return true;
3296 }
3297
Alex Light3dacdd62019-03-12 15:45:47 +00003298 if (Thread::Current()->IsForceInterpreter() ||
3299 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003300 // Force the use of interpreter when it is required by the debugger.
3301 return true;
3302 }
3303
Alex Light8f34aba2017-10-09 13:46:32 -07003304 if (Thread::Current()->IsAsyncExceptionPending()) {
3305 // Force use of interpreter to handle async-exceptions
3306 return true;
3307 }
3308
Alex Light2d441b12018-06-08 15:33:21 -07003309 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3310 const void* instr_target = instr->GetCodeForInvoke(method);
3311 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3312 return ShouldUseInterpreterEntrypoint(method, instr_target);
3313 }
3314
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003315 if (runtime->IsJavaDebuggable()) {
3316 // For simplicity, we ignore precompiled code and go to the interpreter
3317 // assuming we don't already have jitted code.
3318 // We could look at the oat file where `quick_code` is being defined,
3319 // and check whether it's been compiled debuggable, but we decided to
3320 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003321 jit::Jit* jit = Runtime::Current()->GetJit();
3322 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3323 }
3324
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003325 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003326 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003327 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003328 // since we want to JIT it (at first use) with extra stackmaps for native
3329 // debugging. We keep however all AOT code from the boot image,
3330 // since the JIT-at-first-use is blocking and would result in non-negligible
3331 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003332 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003333 }
3334
3335 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003336}
3337
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003338void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003339 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003340 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003341 if (klass->NumDirectMethods() == 0) {
3342 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003343 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003344 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003345 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003346 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003347 return; // OAT file unavailable.
3348 }
Ian Rogers19846512012-02-24 11:42:47 -08003349 }
Alex Light64ad14d2014-08-19 14:23:13 -07003350
Mathieu Chartierf8322842014-05-16 10:59:25 -07003351 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003352 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3353 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3354 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003355 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003356 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003357 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003358 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3359 klass->GetDexClassDefIndex(),
3360 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003361 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003362 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003363 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003364 if (!method->IsStatic()) {
3365 // Only update static methods.
3366 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003367 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003368 const void* quick_code = nullptr;
3369 if (has_oat_class) {
3370 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003371 quick_code = oat_method.GetQuickCode();
3372 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003373 // Check whether the method is native, in which case it's generic JNI.
3374 if (quick_code == nullptr && method->IsNative()) {
3375 quick_code = GetQuickGenericJniStub();
3376 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003377 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003378 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003379 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003380 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003381 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003382 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003383}
3384
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003385// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3386// method. Should only be called on non-invokable methods.
3387inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003388 DCHECK(method != nullptr);
3389 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003390 method->SetEntryPointFromQuickCompiledCodePtrSize(
3391 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3392 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003393}
3394
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003395static void LinkCode(ClassLinker* class_linker,
3396 ArtMethod* method,
3397 const OatFile::OatClass* oat_class,
3398 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003399 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003400 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003401 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003402 // The following code only applies to a non-compiler runtime.
3403 return;
3404 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003405 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003406 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003407 if (oat_class != nullptr) {
3408 // Every kind of method should at least get an invoke stub from the oat_method.
3409 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003410 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003411 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003412 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003413
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003414 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003415 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003416 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003417
Alex Light9139e002015-10-09 15:59:48 -07003418 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003419 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003420 return;
3421 }
Ian Rogers19846512012-02-24 11:42:47 -08003422
3423 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003424 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003425 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3426 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003427 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003428 } else if (quick_code == nullptr && method->IsNative()) {
3429 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003430 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003431 // Set entry point from compiled code if there's no code or in interpreter only mode.
3432 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003433 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003434
Ian Rogers62d6c772013-02-27 08:32:07 -08003435 if (method->IsNative()) {
3436 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003437 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003438
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003439 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003440 // We have a native method here without code. Then it should have either the generic JNI
3441 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3442 // TODO: this doesn't handle all the cases where trampolines may be installed.
3443 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003444 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3445 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003446 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003447 }
3448}
3449
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003450void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003451 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003452 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003453 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003454 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003455 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003456 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003457 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003458 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003459
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003460 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003461 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003462 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003463 klass->SetAccessFlags(access_flags);
3464 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003465 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003466 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003467
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003468 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003469 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003470}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003471
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003472LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3473 LinearAlloc* allocator,
3474 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003475 if (length == 0) {
3476 return nullptr;
3477 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003478 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3479 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3480 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003481 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003482 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003483 CHECK(ret != nullptr);
3484 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3485 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003486}
3487
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003488LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3489 LinearAlloc* allocator,
3490 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003491 if (length == 0) {
3492 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003493 }
Vladimir Marko14632852015-08-17 12:07:23 +01003494 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3495 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003496 const size_t storage_size =
3497 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003498 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003499 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003500 CHECK(ret != nullptr);
3501 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003502 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003503 }
3504 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003505}
3506
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003507LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003508 if (class_loader == nullptr) {
3509 return Runtime::Current()->GetLinearAlloc();
3510 }
3511 LinearAlloc* allocator = class_loader->GetAllocator();
3512 DCHECK(allocator != nullptr);
3513 return allocator;
3514}
3515
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003516LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003517 if (class_loader == nullptr) {
3518 return Runtime::Current()->GetLinearAlloc();
3519 }
3520 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3521 LinearAlloc* allocator = class_loader->GetAllocator();
3522 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003523 RegisterClassLoader(class_loader);
3524 allocator = class_loader->GetAllocator();
3525 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003526 }
3527 return allocator;
3528}
3529
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003530void ClassLinker::LoadClass(Thread* self,
3531 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003532 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003533 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003534 ClassAccessor accessor(dex_file,
3535 dex_class_def,
3536 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003537 if (!accessor.HasClassData()) {
3538 return;
3539 }
3540 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003541 {
3542 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3543 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003544 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003545 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003546 // We allow duplicate definitions of the same field in a class_data_item
3547 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003548 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003549 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3550 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003551 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003552 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3553 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003554 accessor.NumInstanceFields());
3555 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003556 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003557 uint32_t last_static_field_idx = 0u;
3558 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003559
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003560 // Methods
3561 bool has_oat_class = false;
3562 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3563 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3564 : OatFile::OatClass::Invalid();
3565 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3566 klass->SetMethodsPtr(
3567 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3568 accessor.NumDirectMethods(),
3569 accessor.NumVirtualMethods());
3570 size_t class_def_method_index = 0;
3571 uint32_t last_dex_method_index = dex::kDexNoIndex;
3572 size_t last_class_def_method_index = 0;
3573
3574 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3575 // methods needs to decode all of the fields.
3576 accessor.VisitFieldsAndMethods([&](
3577 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3578 uint32_t field_idx = field.GetIndex();
3579 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3580 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3581 LoadField(field, klass, &sfields->At(num_sfields));
3582 ++num_sfields;
3583 last_static_field_idx = field_idx;
3584 }
3585 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3586 uint32_t field_idx = field.GetIndex();
3587 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3588 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3589 LoadField(field, klass, &ifields->At(num_ifields));
3590 ++num_ifields;
3591 last_instance_field_idx = field_idx;
3592 }
3593 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3594 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3595 image_pointer_size_);
3596 LoadMethod(dex_file, method, klass, art_method);
3597 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3598 uint32_t it_method_index = method.GetIndex();
3599 if (last_dex_method_index == it_method_index) {
3600 // duplicate case
3601 art_method->SetMethodIndex(last_class_def_method_index);
3602 } else {
3603 art_method->SetMethodIndex(class_def_method_index);
3604 last_dex_method_index = it_method_index;
3605 last_class_def_method_index = class_def_method_index;
3606 }
3607 ++class_def_method_index;
3608 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3609 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3610 class_def_method_index - accessor.NumDirectMethods(),
3611 image_pointer_size_);
3612 LoadMethod(dex_file, method, klass, art_method);
3613 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3614 ++class_def_method_index;
3615 });
3616
3617 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003618 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003619 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3620 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3621 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003622 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3623 if (sfields != nullptr) {
3624 sfields->SetSize(num_sfields);
3625 }
3626 if (ifields != nullptr) {
3627 ifields->SetSize(num_ifields);
3628 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003629 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003630 // Set the field arrays.
3631 klass->SetSFieldsPtr(sfields);
3632 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003633 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003634 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003635 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003636 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003637 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003638 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003639}
3640
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003641void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003642 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003643 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003644 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003645 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003646 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003647
David Brazdil85865692018-10-30 17:26:20 +00003648 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3649 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003650}
3651
Mathieu Chartier268764d2016-09-13 12:09:38 -07003652void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003653 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003654 Handle<mirror::Class> klass,
3655 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003656 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003657 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003658 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003659
Mathieu Chartier268764d2016-09-13 12:09:38 -07003660 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003661 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003662 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003663 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003664
David Brazdil85865692018-10-30 17:26:20 +00003665 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3666 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003667
Ian Rogersdfb325e2013-10-30 01:00:44 -07003668 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003669 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003670 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3671 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003672 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003673 klass->SetFinalizable();
3674 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003675 std::string temp;
3676 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003677 // The Enum class declares a "final" finalize() method to prevent subclasses from
3678 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3679 // subclasses, so we exclude it here.
3680 // We also want to avoid setting the flag on Object, where we know that finalize() is
3681 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003682 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3683 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003684 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003685 }
3686 }
3687 }
3688 } else if (method_name[0] == '<') {
3689 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003690 bool is_init = (strcmp("<init>", method_name) == 0);
3691 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003692 if (UNLIKELY(!is_init && !is_clinit)) {
3693 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3694 } else {
3695 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3696 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003697 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003698 access_flags |= kAccConstructor;
3699 }
3700 }
3701 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003702 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3703 // Check if the native method is annotated with @FastNative or @CriticalNative.
3704 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3705 dex_file, dst->GetClassDef(), dex_method_idx);
3706 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003707 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003708 // Must be done after SetAccessFlags since IsAbstract depends on it.
3709 if (klass->IsInterface() && dst->IsAbstract()) {
3710 dst->CalculateAndSetImtIndex();
3711 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003712}
3713
Ian Rogers7b078e82014-09-10 14:44:24 -07003714void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003715 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003716 self,
3717 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003718 Runtime::Current()->GetLinearAlloc());
3719 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003720 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003721}
3722
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003723void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003724 ObjPtr<mirror::DexCache> dex_cache) {
3725 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003726 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003727 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003728 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003729}
3730
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003731void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003732 ObjPtr<mirror::DexCache> dex_cache,
3733 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003734 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003735 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003736 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003737 // For app images, the dex cache location may be a suffix of the dex file location since the
3738 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003739 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3740 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003741 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3742 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003743 // The following paths checks don't work on preopt when using boot dex files, where the dex
3744 // cache location is the one on device, and the dex_file's location is the one on host.
3745 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3746 CHECK_GE(dex_file_location.length(), dex_cache_length)
3747 << dex_cache_location << " " << dex_file.GetLocation();
3748 const std::string dex_file_suffix = dex_file_location.substr(
3749 dex_file_location.length() - dex_cache_length,
3750 dex_cache_length);
3751 // Example dex_cache location is SettingsProvider.apk and
3752 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3753 CHECK_EQ(dex_cache_location, dex_file_suffix);
3754 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003755 const OatFile* oat_file =
3756 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003757 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3758 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3759 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3760 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003761 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003762 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3763 DexCacheData data = *it;
3764 if (self->IsJWeakCleared(data.weak_root)) {
3765 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003766 it = dex_caches_.erase(it);
3767 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003768 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003769 it->dex_file->GetOatDexFile() != nullptr &&
3770 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003771 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003772 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003773 ++it;
3774 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003775 }
Vladimir Markob066d432018-01-03 13:14:37 +00003776 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003777 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003778 }
David Brazdila5c3a802019-03-08 14:59:41 +00003779 // Let hiddenapi assign a domain to the newly registered dex file.
3780 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3781
Vladimir Markocd556b02017-02-03 11:47:34 +00003782 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003783 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003784 DexCacheData data;
3785 data.weak_root = dex_cache_jweak;
3786 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003787 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003788 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003789 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003790 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3791 // path dex caches without an image.
3792 data.class_table->InsertStrongRoot(dex_cache);
3793 if (class_loader != nullptr) {
3794 // Since we added a strong root to the class table, do the write barrier as required for
3795 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003796 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003797 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003798 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003799}
3800
Vladimir Markocd556b02017-02-03 11:47:34 +00003801ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3802 return data.IsValid()
3803 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3804 : nullptr;
3805}
3806
3807ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3808 Thread* self,
3809 ObjPtr<mirror::DexCache> dex_cache,
3810 const DexCacheData& data,
3811 ObjPtr<mirror::ClassLoader> class_loader) {
3812 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3813 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3814 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3815 "Attempt to register dex file %s with multiple class loaders",
3816 data.dex_file->GetLocation().c_str());
3817 return nullptr;
3818 }
3819 return dex_cache;
3820}
3821
Alex Light07f06212017-06-01 14:01:43 -07003822void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3823 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003824 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003825 Thread* self = Thread::Current();
3826 StackHandleScope<2> hs(self);
3827 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3828 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3829 const DexFile* dex_file = dex_cache->GetDexFile();
3830 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3831 if (kIsDebugBuild) {
3832 DexCacheData old_data;
3833 {
3834 ReaderMutexLock mu(self, *Locks::dex_lock_);
3835 old_data = FindDexCacheDataLocked(*dex_file);
3836 }
3837 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3838 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3839 << "been registered on dex file " << dex_file->GetLocation();
3840 }
3841 ClassTable* table;
3842 {
3843 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3844 table = InsertClassTableForClassLoader(h_class_loader.Get());
3845 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003846 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3847 // a thread holding the dex lock and blocking on a condition variable regarding
3848 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003849 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003850 WriterMutexLock mu(self, *Locks::dex_lock_);
3851 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3852 table->InsertStrongRoot(h_dex_cache.Get());
3853 if (h_class_loader.Get() != nullptr) {
3854 // Since we added a strong root to the class table, do the write barrier as required for
3855 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003856 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003857 }
3858}
3859
Vladimir Markocd556b02017-02-03 11:47:34 +00003860ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3861 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003862 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003863 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003864 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003865 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003866 old_data = FindDexCacheDataLocked(dex_file);
3867 }
3868 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3869 if (old_dex_cache != nullptr) {
3870 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003871 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003872 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003873 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3874 DCHECK(linear_alloc != nullptr);
3875 ClassTable* table;
3876 {
3877 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3878 table = InsertClassTableForClassLoader(class_loader);
3879 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003880 // Don't alloc while holding the lock, since allocation may need to
3881 // suspend all threads and another thread may need the dex_lock_ to
3882 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003883 StackHandleScope<3> hs(self);
3884 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003885 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003886 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3887 self,
3888 dex_file)));
3889 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003890 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003891 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3892 // a thread holding the dex lock and blocking on a condition variable regarding
3893 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003894 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003895 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003896 old_data = FindDexCacheDataLocked(dex_file);
3897 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003898 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003899 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3900 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3901 // that the arrays are null.
3902 mirror::DexCache::InitializeDexCache(self,
3903 h_dex_cache.Get(),
3904 h_location.Get(),
3905 &dex_file,
3906 linear_alloc,
3907 image_pointer_size_);
3908 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003909 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003910 }
3911 if (old_dex_cache != nullptr) {
3912 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3913 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003914 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003915 self->ClearException();
3916 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3917 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3918 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003919 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003920 self->AssertPendingOOMException();
3921 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003922 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003923 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003924 if (h_class_loader.Get() != nullptr) {
3925 // Since we added a strong root to the class table, do the write barrier as required for
3926 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003927 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003928 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003929 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003930}
3931
Vladimir Markocd556b02017-02-03 11:47:34 +00003932bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003933 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003934 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003935}
3936
Vladimir Markocd556b02017-02-03 11:47:34 +00003937ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3938 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003939 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3940 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003941 if (dex_cache != nullptr) {
3942 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003943 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003944 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003945 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003946 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003947 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003948 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003949 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003950 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3951 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003952 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003953}
3954
Vladimir Markocd556b02017-02-03 11:47:34 +00003955ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3956 const DexFile* dex_file = dex_cache->GetDexFile();
3957 DCHECK(dex_file != nullptr);
3958 ReaderMutexLock mu(self, *Locks::dex_lock_);
3959 // Search assuming unique-ness of dex file.
3960 for (const DexCacheData& data : dex_caches_) {
3961 // Avoid decoding (and read barriers) other unrelated dex caches.
3962 if (data.dex_file == dex_file) {
3963 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3964 if (registered_dex_cache != nullptr) {
3965 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3966 return data.class_table;
3967 }
3968 }
3969 }
3970 return nullptr;
3971}
3972
3973ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3974 // Search assuming unique-ness of dex file.
3975 for (const DexCacheData& data : dex_caches_) {
3976 // Avoid decoding (and read barriers) other unrelated dex caches.
3977 if (data.dex_file == &dex_file) {
3978 return data;
3979 }
3980 }
3981 return DexCacheData();
3982}
3983
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003984ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003985 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003986 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003987 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003988 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003989 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003990 }
Ian Rogers1f539342012-10-03 21:09:42 -07003991 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003992 StackHandleScope<1> hs(self);
3993 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003994 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003995 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3996 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003997 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003998 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003999 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004000 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004001 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4002 h_class.Get(),
4003 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004004 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004005 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004006}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004007
Vladimir Marko02610552018-06-04 14:38:00 +01004008inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4009 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4010}
4011
Brian Carlstrombe977852011-07-19 14:54:54 -07004012// Create an array class (i.e. the class object for the array, not the
4013// array itself). "descriptor" looks like "[C" or "[[[[B" or
4014// "[Ljava/lang/String;".
4015//
4016// If "descriptor" refers to an array of primitives, look up the
4017// primitive type's internally-generated class object.
4018//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004019// "class_loader" is the class loader of the class that's referring to
4020// us. It's used to ensure that we're looking for the element type in
4021// the right context. It does NOT become the class loader for the
4022// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004023//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004024// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004025ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4026 const char* descriptor,
4027 size_t hash,
4028 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004029 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004030 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004031 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004032
4033 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4034 // code to be executed. We put it up here so we can avoid all the allocations associated with
4035 // creating the class. This can happen with (eg) jit threads.
4036 if (!self->CanLoadClasses()) {
4037 // Make sure we don't try to load anything, potentially causing an infinite loop.
4038 ObjPtr<mirror::Throwable> pre_allocated =
4039 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4040 self->SetException(pre_allocated);
4041 return nullptr;
4042 }
4043
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004044 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4045 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004046 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004047 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004048 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004049 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4050 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004051 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004052 DCHECK(self->IsExceptionPending());
4053 return nullptr;
4054 } else {
4055 self->ClearException();
4056 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004057 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004058 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4059 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4060 return nullptr;
4061 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004062 // See if the component type is already loaded. Array classes are
4063 // always associated with the class loader of their underlying
4064 // element type -- an array of Strings goes with the loader for
4065 // java/lang/String -- so we need to look for it there. (The
4066 // caller should have checked for the existence of the class
4067 // before calling here, but they did so with *their* class loader,
4068 // not the component type's loader.)
4069 //
4070 // If we find it, the caller adds "loader" to the class' initiating
4071 // loader list, which should prevent us from going through this again.
4072 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004073 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004074 // are the same, because our caller (FindClass) just did the
4075 // lookup. (Even if we get this wrong we still have correct behavior,
4076 // because we effectively do this lookup again when we add the new
4077 // class to the hash table --- necessary because of possible races with
4078 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004079 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004080 ObjPtr<mirror::Class> new_class =
4081 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004082 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004083 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004084 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004085 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004086
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004087 // Fill out the fields in the Class.
4088 //
4089 // It is possible to execute some methods against arrays, because
4090 // all arrays are subclasses of java_lang_Object_, so we need to set
4091 // up a vtable. We can just point at the one in java_lang_Object_.
4092 //
4093 // Array classes are simple enough that we don't need to do a full
4094 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004095 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004096 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004097 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004098 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004099 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004100 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004101 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4102 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4103 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004104 } else if (strcmp(descriptor, "[Z") == 0) {
4105 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4106 } else if (strcmp(descriptor, "[B") == 0) {
4107 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4108 } else if (strcmp(descriptor, "[C") == 0) {
4109 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4110 } else if (strcmp(descriptor, "[S") == 0) {
4111 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004112 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004113 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004114 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004115 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004116 } else if (strcmp(descriptor, "[F") == 0) {
4117 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4118 } else if (strcmp(descriptor, "[D") == 0) {
4119 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004120 }
4121 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004122 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004123 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004124 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004125 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004126 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004127 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004128 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004129 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004130 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004131 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004132 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004133 new_class->SetSuperClass(java_lang_Object);
4134 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004135 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004136 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004137 if (component_type->IsPrimitive()) {
4138 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4139 } else {
4140 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4141 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004142 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004143 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4144 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4145 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004146 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004147 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004148 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004149 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004150
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004151 // All arrays have java/lang/Cloneable and java/io/Serializable as
4152 // interfaces. We need to set that up here, so that stuff like
4153 // "instanceof" works right.
4154 //
4155 // Note: The GC could run during the call to FindSystemClass,
4156 // so we need to make sure the class object is GC-valid while we're in
4157 // there. Do this by clearing the interface list so the GC will just
4158 // think that the entries are null.
4159
4160
4161 // Use the single, global copies of "interfaces" and "iftable"
4162 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004163 {
Vladimir Marko02610552018-06-04 14:38:00 +01004164 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004165 CHECK(array_iftable != nullptr);
4166 new_class->SetIfTable(array_iftable);
4167 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004168
Elliott Hughes00626c22013-06-14 15:04:14 -07004169 // Inherit access flags from the component type.
4170 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4171 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4172 access_flags &= kAccJavaFlagsMask;
4173 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004174 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004175 access_flags |= kAccAbstract | kAccFinal;
4176 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004177 // Arrays are access-checks-clean and preverified.
4178 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004179
4180 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004181
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004182 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004183 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004184 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4185 // duplicate events in case of races. Array classes don't really follow dedicated
4186 // load and prepare, anyways.
4187 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4188 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4189
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004190 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004191 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004192 }
4193 // Another thread must have loaded the class after we
4194 // started but before we finished. Abandon what we've
4195 // done.
4196 //
4197 // (Yes, this happens.)
4198
Vladimir Markobcf17522018-06-01 13:14:32 +01004199 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004200}
4201
Vladimir Marko9186b182018-11-06 14:55:54 +00004202ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4203 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004204 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004205 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4206 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4207 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4208 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4209 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4210 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4211 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4212 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4213 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004214 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004215 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004216 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004217 return GetClassRoot(class_root, this);
4218}
4219
4220ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4221 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4222 if (UNLIKELY(result == nullptr)) {
4223 std::string printable_type(PrintableChar(type));
4224 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4225 }
4226 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004227}
4228
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004229ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4230 ObjPtr<mirror::Class> klass,
4231 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004232 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004233 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004234 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004235 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004236 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004237 source += " from ";
4238 source += dex_cache->GetLocation()->ToModifiedUtf8();
4239 }
4240 LOG(INFO) << "Loaded class " << descriptor << source;
4241 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004242 {
4243 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004244 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004245 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004246 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004247 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004248 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004249 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004250 VerifyObject(klass);
4251 class_table->InsertWithHash(klass, hash);
4252 if (class_loader != nullptr) {
4253 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004254 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004255 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004256 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004257 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004258 }
4259 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004260 if (kIsDebugBuild) {
4261 // Test that copied methods correctly can find their holder.
4262 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4263 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4264 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004265 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004266 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004267}
4268
Vladimir Marko1998cd02017-01-13 13:02:58 +00004269void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004270 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4271 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4272 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4273 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004274 }
4275}
4276
Alex Lighte64300b2015-12-15 15:02:47 -08004277// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004278void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004279 LengthPrefixedArray<ArtMethod>* new_methods) {
4280 klass->SetMethodsPtrUnchecked(new_methods,
4281 klass->NumDirectMethods(),
4282 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004283 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004284 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004285}
4286
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004287ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4288 const char* descriptor,
4289 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004290 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4291}
4292
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004293ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4294 const char* descriptor,
4295 size_t hash,
4296 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004297 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4298 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4299 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004300 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004301 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004302 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004303 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004304 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004305 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004306}
4307
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004308class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4309 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004310 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004311
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004312 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004313 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004314 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004315 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004316 if (class_table != nullptr) {
4317 class_table->FreezeSnapshot();
4318 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004319 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004320};
4321
4322void ClassLinker::MoveClassTableToPreZygote() {
4323 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004324 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004325 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004326 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004327}
4328
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004329// Look up classes by hash and descriptor and put all matching ones in the result array.
4330class LookupClassesVisitor : public ClassLoaderVisitor {
4331 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004332 LookupClassesVisitor(const char* descriptor,
4333 size_t hash,
4334 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004335 : descriptor_(descriptor),
4336 hash_(hash),
4337 result_(result) {}
4338
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004339 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004340 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004341 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004342 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004343 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4344 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004345 result_->push_back(klass);
4346 }
4347 }
4348
4349 private:
4350 const char* const descriptor_;
4351 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004352 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004353};
4354
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004355void ClassLinker::LookupClasses(const char* descriptor,
4356 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004357 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004358 Thread* const self = Thread::Current();
4359 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004360 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004361 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004362 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004363 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004364 result.push_back(klass);
4365 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004366 LookupClassesVisitor visitor(descriptor, hash, &result);
4367 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004368}
4369
Alex Lightf1f10492015-10-07 16:08:36 -07004370bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4371 Handle<mirror::Class> klass,
4372 Handle<mirror::Class> supertype) {
4373 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004374 DCHECK(klass != nullptr);
4375 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004376
Alex Lightf1f10492015-10-07 16:08:36 -07004377 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4378 VerifyClass(self, supertype);
4379 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004380
4381 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4382 // The supertype is either verified, or we soft failed at AOT time.
4383 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004384 return true;
4385 }
4386 // If we got this far then we have a hard failure.
4387 std::string error_msg =
4388 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004389 klass->PrettyDescriptor().c_str(),
4390 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004391 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004392 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004393 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004394 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004395 // Set during VerifyClass call (if at all).
4396 self->ClearException();
4397 }
4398 // Change into a verify error.
4399 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004400 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004401 self->GetException()->SetCause(cause.Get());
4402 }
4403 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4404 if (Runtime::Current()->IsAotCompiler()) {
4405 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4406 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004407 // Need to grab the lock to change status.
4408 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004409 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004410 return false;
4411}
4412
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004413verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004414 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004415 {
4416 // TODO: assert that the monitor on the Class is held
4417 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004418
Andreas Gampe884f3b82016-03-30 19:52:58 -07004419 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004420 ClassStatus old_status = klass->GetStatus();
4421 while (old_status == ClassStatus::kVerifying ||
4422 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004423 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004424 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4425 // case we may see the same status again. b/62912904. This is why the check is
4426 // greater or equal.
4427 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004428 << "Class '" << klass->PrettyClass()
4429 << "' performed an illegal verification state transition from " << old_status
4430 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004431 old_status = klass->GetStatus();
4432 }
jeffhao98eacac2011-09-14 16:11:53 -07004433
Andreas Gampe884f3b82016-03-30 19:52:58 -07004434 // The class might already be erroneous, for example at compile time if we attempted to verify
4435 // this class as a parent to another.
4436 if (klass->IsErroneous()) {
4437 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004438 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004439 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004440
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004441 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004442 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004443 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004444 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004445 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004446
4447 // For AOT, don't attempt to re-verify if we have already found we should
4448 // verify at runtime.
4449 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004450 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004451 }
jeffhao98eacac2011-09-14 16:11:53 -07004452
Vladimir Marko2c64a832018-01-04 11:31:56 +00004453 if (klass->GetStatus() == ClassStatus::kResolved) {
4454 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004455 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004456 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004457 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004458 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004459 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004460 }
4461
4462 // Skip verification if disabled.
4463 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004464 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004465 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004466 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004467 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004468 }
4469
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004470 VLOG(class_linker) << "Beginning verification for class: "
4471 << klass->PrettyDescriptor()
4472 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4473
Ian Rogers9ffb0392012-09-10 11:56:50 -07004474 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004475 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004476 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4477 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004478 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004479 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004480 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004481 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004482
Alex Lightf1f10492015-10-07 16:08:36 -07004483 // Verify all default super-interfaces.
4484 //
4485 // (1) Don't bother if the superclass has already had a soft verification failure.
4486 //
4487 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4488 // recursive initialization by themselves. This is because when an interface is initialized
4489 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4490 // but choose not to for an optimization. If the interfaces is being verified due to a class
4491 // initialization (which would need all the default interfaces to be verified) the class code
4492 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004493 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004494 && !klass->IsInterface()) { // See (2)
4495 int32_t iftable_count = klass->GetIfTableCount();
4496 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4497 // Loop through all interfaces this class has defined. It doesn't matter the order.
4498 for (int32_t i = 0; i < iftable_count; i++) {
4499 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004500 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004501 // We only care if we have default interfaces and can skip if we are already verified...
4502 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4503 continue;
4504 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4505 // We had a hard failure while verifying this interface. Just return immediately.
4506 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004507 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004508 } else if (UNLIKELY(!iface->IsVerified())) {
4509 // We softly failed to verify the iface. Stop checking and clean up.
4510 // Put the iface into the supertype handle so we know what caused us to fail.
4511 supertype.Assign(iface.Get());
4512 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004513 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004514 }
4515 }
4516
Alex Lightf1f10492015-10-07 16:08:36 -07004517 // At this point if verification failed, then supertype is the "first" supertype that failed
4518 // verification (without a specific order). If verification succeeded, then supertype is either
4519 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004520 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004521 supertype.Get() == klass->GetSuperClass() ||
4522 !supertype->IsVerified());
4523
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004524 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004525 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004526 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004527 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004528
4529 VLOG(class_linker) << "Class preverified status for class "
4530 << klass->PrettyDescriptor()
4531 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4532 << ": "
4533 << preverified;
4534
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004535 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4536 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004537 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4538 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004539
Ian Rogers62d6c772013-02-27 08:32:07 -08004540 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004541 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004542 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004543 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004544 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004545
4546 // Verification is done, grab the lock again.
4547 ObjectLock<mirror::Class> lock(self, klass);
4548
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004549 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4550 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004551 VLOG(class_linker) << "Soft verification failure in class "
4552 << klass->PrettyDescriptor()
4553 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4554 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004555 }
Ian Rogers1f539342012-10-03 21:09:42 -07004556 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004557 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004558 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004559 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004560 // Even though there were no verifier failures we need to respect whether the super-class and
4561 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004562 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004563 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004564 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004565 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4566 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004567 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004568 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004569 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004570 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004571 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004572 // Soft failures at compile time should be retried at runtime. Soft
4573 // failures at runtime will be handled by slow paths in the generated
4574 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004575 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004576 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004577 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004578 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004579 // As this is a fake verified status, make sure the methods are _not_ marked
4580 // kAccSkipAccessChecks later.
4581 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004582 }
4583 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004584 } else {
David Sehr709b0702016-10-13 09:12:37 -07004585 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004586 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4587 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004588 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004589 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004590 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004591 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004592 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004593 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004594 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004595 // method.
4596 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004597 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004598 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004599
4600 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4601 // Never skip access checks if the verification soft fail is forced.
4602 // Mark the class as having a verification attempt to avoid re-running the verifier.
4603 klass->SetVerificationAttempted();
4604 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004605 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004606 }
Andreas Gampe48498592014-09-10 19:48:05 -07004607 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004608 // Done verifying. Notify the compiler about the verification status, in case the class
4609 // was verified implicitly (eg super class of a compiled class).
4610 if (Runtime::Current()->IsAotCompiler()) {
4611 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4612 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4613 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004614 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004615}
4616
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004617verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4618 Handle<mirror::Class> klass,
4619 verifier::HardFailLogMode log_level,
4620 std::string* error_msg) {
4621 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004622 return verifier::ClassVerifier::VerifyClass(self,
4623 klass.Get(),
4624 runtime->GetCompilerCallbacks(),
4625 runtime->IsAotCompiler(),
4626 log_level,
4627 Runtime::Current()->GetTargetSdkVersion(),
4628 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004629}
4630
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004631bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004632 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004633 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004634 // If we're compiling, we can only verify the class using the oat file if
4635 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004636 // the compilation unit (app - dependencies). We will let the compiler callback
4637 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004638 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004639 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004640 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004641 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004642 return false;
4643 }
4644 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004645 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004646 return false;
4647 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004648 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004649
Andreas Gampeb40d3612018-06-26 15:49:42 -07004650 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004651 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004652 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004653 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4654 // For boot classpath classes in the case we're not using a default boot image:
4655 // we don't have the infrastructure yet to query verification data on individual
4656 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4657 // verified. This should be taken into account when measuring boot time and app
4658 // startup compare to the (current) production system where both:
4659 // 1) updatable boot classpath classes, and
4660 // 2) classes in /system referencing updatable classes
4661 // will be verified at runtime.
4662 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4663 oat_file_class_status = ClassStatus::kVerified;
4664 return true;
4665 }
4666 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004667 return false;
4668 }
4669
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004670 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004671 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004672 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004673 return true;
4674 }
4675 // If we only verified a subset of the classes at compile time, we can end up with classes that
4676 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004677 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004678 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004679 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004680 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004681 // Compile time verification failed with a soft error. Compile time verification can fail
4682 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004683 // class ... {
4684 // Foo x;
4685 // .... () {
4686 // if (...) {
4687 // v1 gets assigned a type of resolved class Foo
4688 // } else {
4689 // v1 gets assigned a type of unresolved class Bar
4690 // }
4691 // iput x = v1
4692 // } }
4693 // when we merge v1 following the if-the-else it results in Conflict
4694 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4695 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4696 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4697 // at compile time).
4698 return false;
4699 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004700 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004701 // Compile time verification failed with a hard error. This is caused by invalid instructions
4702 // in the class. These errors are unrecoverable.
4703 return false;
4704 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004705 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004706 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4707 // not loading the class.
4708 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4709 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004710 return false;
4711 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004712 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004713 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004714 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004715 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004716 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004717}
4718
Alex Light5a559862016-01-29 12:24:48 -08004719void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004720 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004721 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004722 }
4723}
4724
Alex Light5a559862016-01-29 12:24:48 -08004725void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004726 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004727 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004728 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004729 return; // native or abstract method
4730 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004731 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004732 return; // nothing to process
4733 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004734 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004735 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004736 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4737 CatchHandlerIterator iterator(handlers_ptr);
4738 for (; iterator.HasNext(); iterator.Next()) {
4739 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4740 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004741 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004742 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004743 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004744 DCHECK(Thread::Current()->IsExceptionPending());
4745 Thread::Current()->ClearException();
4746 }
4747 }
4748 }
4749 handlers_ptr = iterator.EndDataPointer();
4750 }
4751}
4752
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004753ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4754 jstring name,
4755 jobjectArray interfaces,
4756 jobject loader,
4757 jobjectArray methods,
4758 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004759 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004760
4761 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4762 // code to be executed. We put it up here so we can avoid all the allocations associated with
4763 // creating the class. This can happen with (eg) jit-threads.
4764 if (!self->CanLoadClasses()) {
4765 // Make sure we don't try to load anything, potentially causing an infinite loop.
4766 ObjPtr<mirror::Throwable> pre_allocated =
4767 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4768 self->SetException(pre_allocated);
4769 return nullptr;
4770 }
4771
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004772 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004773 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004774 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004775 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004776 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004777 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004778 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004779 DCHECK(temp_klass->GetClass() != nullptr);
4780 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004781 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4782 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004783 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4784 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4785 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4786 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004787 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004788 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004789 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004790 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004791 std::string storage;
4792 const char* descriptor = temp_klass->GetDescriptor(&storage);
4793 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004794
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004795 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004796 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004797
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004798 // Insert the class before loading the fields as the field roots
4799 // (ArtField::declaring_class_) are only visited from the class
4800 // table. There can't be any suspend points between inserting the
4801 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004802 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004803 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004804
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004805 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004806 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004807 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004808 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004809
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004810 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4811 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004812 ArtField& interfaces_sfield = sfields->At(0);
4813 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004814 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004815 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004816
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004817 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004818 ArtField& throws_sfield = sfields->At(1);
4819 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004820 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004821 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004822
Ian Rogers466bb252011-10-14 03:29:56 -07004823 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004824 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004825
Alex Lighte64300b2015-12-15 15:02:47 -08004826 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004827 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004828 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004829 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004830 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004831
4832 // Create the methods array.
4833 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4834 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004835 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4836 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004837 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004838 self->AssertPendingOOMException();
4839 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004840 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004841 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004842
4843 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004844 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004845
4846 // Create virtual method using specified prototypes.
4847 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004848 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004849 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004850 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004851 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004852 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4853 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004854 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004855
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004856 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004857 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004858 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004859 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004860 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004861
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004862 // At this point the class is loaded. Publish a ClassLoad event.
4863 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4864 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4865
4866 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004867 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004868 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004869 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004870 // Link the fields and virtual methods, creating vtable and iftables.
4871 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004872 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004873 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004874 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004875 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004876 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004877 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004878 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004879 CHECK(temp_klass->IsRetired());
4880 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004881
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004882 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004883 interfaces_sfield.SetObject<false>(
4884 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004885 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004886 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4887 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004888 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004889 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004890
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004891 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4892
Vladimir Marko305c38b2018-02-14 11:50:07 +00004893 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4894 // See also ClassLinker::EnsureInitialized().
4895 if (kBitstringSubtypeCheckEnabled) {
4896 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4897 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4898 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4899 }
4900
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004901 {
4902 // Lock on klass is released. Lock new class object.
4903 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004904 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004905 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004906 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004907
4908 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004909 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004910 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004911 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4912
Ian Rogersc2b44472011-12-14 21:17:17 -08004913 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004914 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4915 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004916 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004917 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004918
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004919 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004920 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004921 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004922 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004923 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004924
4925 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004926 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004927 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004928
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004929 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004930 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004931 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004932 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004933 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004934 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004935}
4936
Mathieu Chartiere401d142015-04-22 13:56:20 -07004937void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4938 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004939 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4940 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004941
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004942 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4943 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004944 ArtMethod* proxy_constructor =
4945 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004946 DCHECK(proxy_constructor != nullptr)
4947 << "Could not find <init> method in java.lang.reflect.Proxy";
4948
Jeff Haodb8a6642014-08-14 17:18:52 -07004949 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4950 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004951 DCHECK(out != nullptr);
4952 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004953 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004954 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004955 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004956 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4957 kAccPublic |
4958 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004959 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004960
4961 // Set the original constructor method.
4962 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004963}
4964
Mathieu Chartiere401d142015-04-22 13:56:20 -07004965void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004966 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004967 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4968 CHECK_STREQ(np->GetName(), "<init>");
4969 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004970 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004971}
4972
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004973void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004974 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004975 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004976 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004977 DCHECK(out != nullptr);
4978 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004979
Alex Lighte9dd04f2016-03-16 16:09:45 -07004980 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004981 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004982 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4983 // preference to the invocation handler.
4984 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4985 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004986 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4987 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004988 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4989
4990 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4991 // method they copy might (if it's a default method).
4992 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004993
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004994 // Set the original interface method.
4995 out->SetDataPtrSize(prototype, image_pointer_size_);
4996
Ian Rogers466bb252011-10-14 03:29:56 -07004997 // At runtime the method looks like a reference and argument saving method, clone the code
4998 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004999 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005000}
Jesse Wilson95caa792011-10-12 18:14:17 -04005001
Mathieu Chartiere401d142015-04-22 13:56:20 -07005002void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005003 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005004 CHECK(!prototype->IsFinal());
5005 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005006 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005007
5008 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5009 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005010 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005011 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005012}
5013
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005014bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005015 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005016 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005017 return true;
5018 }
5019 if (!can_init_statics) {
5020 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005021 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005022 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005023 return false;
5024 }
5025 // Check if there are encoded static values needing initialization.
5026 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005027 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005028 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005029 if (dex_class_def->static_values_off_ != 0) {
5030 return false;
5031 }
5032 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005033 // If we are a class we need to initialize all interfaces with default methods when we are
5034 // initialized. Check all of them.
5035 if (!klass->IsInterface()) {
5036 size_t num_interfaces = klass->GetIfTableCount();
5037 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005038 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005039 if (iface->HasDefaultMethods() &&
5040 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5041 return false;
5042 }
5043 }
5044 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005045 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005046 if (klass->IsInterface() || !klass->HasSuperClass()) {
5047 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005048 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005049 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005050 if (!can_init_parents && !super_class->IsInitialized()) {
5051 return false;
5052 }
5053 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005054}
5055
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005056bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5057 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005058 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5059
5060 // Are we already initialized and therefore done?
5061 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5062 // an initialized class will never change its state.
5063 if (klass->IsInitialized()) {
5064 return true;
5065 }
5066
5067 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005068 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005069 return false;
5070 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005071
Ian Rogers7b078e82014-09-10 14:44:24 -07005072 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005073 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005074 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005075 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005076
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005077 // Re-check under the lock in case another thread initialized ahead of us.
5078 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005079 return true;
5080 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005081
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005082 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005083 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005084 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005085 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005086 return false;
5087 }
5088
Vladimir Marko72ab6842017-01-20 19:32:50 +00005089 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5090 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005091
5092 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005093 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005094 if (!klass->IsVerified()) {
5095 // We failed to verify, expect either the klass to be erroneous or verification failed at
5096 // compile time.
5097 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005098 // The class is erroneous. This may be a verifier error, or another thread attempted
5099 // verification and/or initialization and failed. We can distinguish those cases by
5100 // whether an exception is already pending.
5101 if (self->IsExceptionPending()) {
5102 // Check that it's a VerifyError.
5103 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005104 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005105 } else {
5106 // Check that another thread attempted initialization.
5107 DCHECK_NE(0, klass->GetClinitThreadId());
5108 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5109 // Need to rethrow the previous failure now.
5110 ThrowEarlierClassFailure(klass.Get(), true);
5111 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005112 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005113 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005114 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005115 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005116 self->AssertNoPendingException();
5117 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005118 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005119 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005120 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005121 } else {
5122 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005123 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005124
5125 // A separate thread could have moved us all the way to initialized. A "simple" example
5126 // involves a subclass of the current class being initialized at the same time (which
5127 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005128 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005129 if (klass->IsInitialized()) {
5130 return true;
5131 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005132 }
5133
Vladimir Marko2c64a832018-01-04 11:31:56 +00005134 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005135 // initializing higher up the stack or another thread has beat us
5136 // to initializing and we need to wait. Either way, this
5137 // invocation of InitializeClass will not be responsible for
5138 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005139 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005140 // Could have got an exception during verification.
5141 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005142 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005143 return false;
5144 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005145 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005146 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005147 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005148 return true;
5149 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005150 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005151 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005152 }
5153
Jeff Haoe2e40342017-07-19 10:45:18 -07005154 // Try to get the oat class's status for this class if the oat file is present. The compiler
5155 // tries to validate superclass descriptors, and writes the result into the oat file.
5156 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5157 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5158 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005159 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005160 const Runtime* runtime = Runtime::Current();
5161 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5162 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5163 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005164 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005165 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005166 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005167 return false;
5168 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005169 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005170
Vladimir Marko2c64a832018-01-04 11:31:56 +00005171 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005172 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005173
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005174 // From here out other threads may observe that we're initializing and so changes of state
5175 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005176 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005177 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005178
5179 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005180 }
5181
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005182 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005183 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005184 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005185 if (!super_class->IsInitialized()) {
5186 CHECK(!super_class->IsInterface());
5187 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005188 StackHandleScope<1> hs(self);
5189 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005190 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005191 if (!super_initialized) {
5192 // The super class was verified ahead of entering initializing, we should only be here if
5193 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005194 // For the case of aot compiler, the super class might also be initializing but we don't
5195 // want to process circular dependencies in pre-compile.
5196 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005197 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005198 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005199 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005200 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005201 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005202 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005203 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005204 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005205 return false;
5206 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005207 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005208 }
5209
Alex Lighteb7c1442015-08-31 13:17:42 -07005210 if (!klass->IsInterface()) {
5211 // Initialize interfaces with default methods for the JLS.
5212 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005213 // Only setup the (expensive) handle scope if we actually need to.
5214 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005215 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005216 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5217 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005218 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005219 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005220 CHECK(handle_scope_iface->IsInterface());
5221 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5222 // We have already done this for this interface. Skip it.
5223 continue;
5224 }
5225 // We cannot just call initialize class directly because we need to ensure that ALL
5226 // interfaces with default methods are initialized. Non-default interface initialization
5227 // will not affect other non-default super-interfaces.
5228 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5229 handle_scope_iface,
5230 can_init_statics,
5231 can_init_parents);
5232 if (!iface_initialized) {
5233 ObjectLock<mirror::Class> lock(self, klass);
5234 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005235 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005236 return false;
5237 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005238 }
5239 }
5240 }
5241
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005242 const size_t num_static_fields = klass->NumStaticFields();
5243 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005244 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005245 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005246 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005247 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005248 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005249
5250 // Eagerly fill in static fields so that the we don't have to do as many expensive
5251 // Class::FindStaticField in ResolveField.
5252 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005253 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005254 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005255 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005256 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005257 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005258 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5259 field,
5260 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5261 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005262 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005263 } else {
5264 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005265 }
5266 }
5267
Vladimir Markoe11dd502017-12-08 14:09:45 +00005268 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5269 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005270 this,
5271 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005272 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005273
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005274 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005275 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005276 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005277 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5278 if (!value_it.HasNext()) {
5279 break;
5280 }
5281 ArtField* art_field = ResolveField(field.GetIndex(),
5282 dex_cache,
5283 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005284 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005285 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005286 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005287 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005288 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005289 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005290 if (self->IsExceptionPending()) {
5291 break;
5292 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005293 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005294 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005295 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005296 }
5297 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005298
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005299
Mathieu Chartierda595be2016-08-10 13:57:39 -07005300 if (!self->IsExceptionPending()) {
5301 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5302 if (clinit != nullptr) {
5303 CHECK(can_init_statics);
5304 JValue result;
5305 clinit->Invoke(self, nullptr, 0, &result, "V");
5306 }
5307 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005308 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005309 uint64_t t1 = NanoTime();
5310
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005311 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005312 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005313 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005314
5315 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005316 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005317 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005318 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005319 } else if (Runtime::Current()->IsTransactionAborted()) {
5320 // The exception thrown when the transaction aborted has been caught and cleared
5321 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005322 VLOG(compiler) << "Return from class initializer of "
5323 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005324 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005325 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005326 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005327 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005328 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005329 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5330 RuntimeStats* thread_stats = self->GetStats();
5331 ++global_stats->class_init_count;
5332 ++thread_stats->class_init_count;
5333 global_stats->class_init_time_ns += (t1 - t0);
5334 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005335 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005336 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005337 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005338 std::string temp;
5339 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005340 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005341 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005342 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005343 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005344 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005345 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005346 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005347}
5348
Alex Lighteb7c1442015-08-31 13:17:42 -07005349// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5350// and perform the initialization only on those interfaces that contain default methods.
5351bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5352 Handle<mirror::Class> iface,
5353 bool can_init_statics,
5354 bool can_init_parents) {
5355 CHECK(iface->IsInterface());
5356 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005357 // Only create the (expensive) handle scope if we need it.
5358 if (UNLIKELY(num_direct_ifaces > 0)) {
5359 StackHandleScope<1> hs(self);
5360 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5361 // First we initialize all of iface's super-interfaces recursively.
5362 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005363 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005364 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005365 if (!super_iface->HasBeenRecursivelyInitialized()) {
5366 // Recursive step
5367 handle_super_iface.Assign(super_iface);
5368 if (!InitializeDefaultInterfaceRecursive(self,
5369 handle_super_iface,
5370 can_init_statics,
5371 can_init_parents)) {
5372 return false;
5373 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005374 }
5375 }
5376 }
5377
5378 bool result = true;
5379 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5380 // initialize if we don't have default methods.
5381 if (iface->HasDefaultMethods()) {
5382 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5383 }
5384
5385 // Mark that this interface has undergone recursive default interface initialization so we know we
5386 // can skip it on any later class initializations. We do this even if we are not a default
5387 // interface since we can still avoid the traversal. This is purely a performance optimization.
5388 if (result) {
5389 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005390 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5391 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5392 // initialization is a performance optimization (to avoid another idempotent visit
5393 // for other implementing classes/interfaces), and can be revisited later.
5394 ObjectTryLock<mirror::Class> lock(self, iface);
5395 if (lock.Acquired()) {
5396 iface->SetRecursivelyInitialized();
5397 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005398 }
5399 return result;
5400}
5401
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005402bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5403 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005404 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005405 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005406 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005407 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005408 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005409 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005410
5411 // When we wake up, repeat the test for init-in-progress. If
5412 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005413 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005414 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005415 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005416 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005417 return false;
5418 }
5419 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005420 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005421 continue;
5422 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005423 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005424 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005425 // Compile time initialization failed.
5426 return false;
5427 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005428 if (klass->IsErroneous()) {
5429 // The caller wants an exception, but it was thrown in a
5430 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005431 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005432 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005433 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005434 return false;
5435 }
5436 if (klass->IsInitialized()) {
5437 return true;
5438 }
David Sehr709b0702016-10-13 09:12:37 -07005439 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005440 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005441 }
Ian Rogers07140832014-09-30 15:43:59 -07005442 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005443}
5444
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005445static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5446 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005447 ArtMethod* method,
5448 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005449 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005450 DCHECK(Thread::Current()->IsExceptionPending());
5451 DCHECK(!m->IsProxyMethod());
5452 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005453 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5454 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005455 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005456 std::string return_type = dex_file->PrettyType(return_type_idx);
5457 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005458 ThrowWrappedLinkageError(klass.Get(),
5459 "While checking class %s method %s signature against %s %s: "
5460 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005461 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5462 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005463 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005464 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005465 return_type.c_str(), class_loader.c_str());
5466}
5467
5468static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5469 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005470 ArtMethod* method,
5471 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005472 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005473 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005474 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005475 DCHECK(Thread::Current()->IsExceptionPending());
5476 DCHECK(!m->IsProxyMethod());
5477 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005478 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5479 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005480 ThrowWrappedLinkageError(klass.Get(),
5481 "While checking class %s method %s signature against %s %s: "
5482 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005483 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5484 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005485 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005486 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005487 index, arg_type.c_str(), class_loader.c_str());
5488}
5489
5490static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5491 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005492 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005493 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005494 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005495 ThrowLinkageError(klass.Get(),
5496 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005497 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5498 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005499 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005500 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005501 error_msg.c_str());
5502}
5503
Ian Rogersb5fb2072014-12-02 17:22:02 -08005504static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005505 Handle<mirror::Class> klass,
5506 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005507 ArtMethod* method1,
5508 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005509 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005510 {
5511 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005512 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005513 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005514 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005515 return false;
5516 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005517 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005518 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005519 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005520 return false;
5521 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005522 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005523 ThrowSignatureMismatch(klass, super_klass, method1,
5524 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005525 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005526 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005527 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005528 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005529 return false;
5530 }
5531 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005532 const dex::TypeList* types1 = method1->GetParameterTypeList();
5533 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005534 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005535 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005536 ThrowSignatureMismatch(klass, super_klass, method1,
5537 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005538 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005539 return false;
5540 }
5541 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005542 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005543 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005544 ThrowSignatureMismatch(klass, super_klass, method1,
5545 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005546 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005547 return false;
5548 }
5549 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005550 }
5551 uint32_t num_types = types1->Size();
5552 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005553 ThrowSignatureMismatch(klass, super_klass, method1,
5554 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005555 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005556 return false;
5557 }
5558 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005559 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005560 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005561 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005562 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005563 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005564 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005565 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005566 return false;
5567 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005568 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005569 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005570 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005571 if (UNLIKELY(other_param_type == nullptr)) {
5572 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005573 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005574 return false;
5575 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005576 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005577 ThrowSignatureMismatch(klass, super_klass, method1,
5578 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5579 i,
David Sehr709b0702016-10-13 09:12:37 -07005580 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005581 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005582 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005583 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005584 return false;
5585 }
5586 }
5587 return true;
5588}
5589
5590
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005591bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005592 if (klass->IsInterface()) {
5593 return true;
5594 }
Ian Rogers151f2212014-05-06 11:27:27 -07005595 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005596 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005597 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005598 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005599 if (klass->HasSuperClass() &&
5600 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005601 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005602 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005603 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5604 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5605 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005606 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5607 klass,
5608 super_klass,
5609 m,
5610 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005611 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005612 return false;
5613 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005614 }
5615 }
5616 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005617 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005618 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5619 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5620 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005621 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005622 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5623 j, image_pointer_size_);
5624 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5625 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005626 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5627 klass,
5628 super_klass,
5629 m,
5630 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005631 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005632 return false;
5633 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005634 }
5635 }
5636 }
5637 }
5638 return true;
5639}
5640
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005641bool ClassLinker::EnsureInitialized(Thread* self,
5642 Handle<mirror::Class> c,
5643 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005644 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005645 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005646
Mathieu Chartier524507a2014-08-27 15:28:28 -07005647 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005648 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005649 return true;
5650 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005651 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5652 //
5653 // Ensure the bitstring is initialized before any of the class initialization
5654 // logic occurs. Once a class initializer starts running, objects can
5655 // escape into the heap and use the subtype checking code.
5656 //
5657 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5658 // can be used as a source for the IsSubClass check, and that all ancestors
5659 // of the class are Assigned (can be used as a target for IsSubClass check)
5660 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005661 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005662 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005663 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005664 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5665 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005666 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005667 if (!success) {
5668 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005669 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005670 }
5671 } else {
5672 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005673 }
5674 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005675}
5676
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005677void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5678 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005679 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005680 for (ArtField& field : new_class->GetIFields()) {
5681 if (field.GetDeclaringClass() == temp_class) {
5682 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005683 }
5684 }
5685
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005686 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005687 for (ArtField& field : new_class->GetSFields()) {
5688 if (field.GetDeclaringClass() == temp_class) {
5689 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005690 }
5691 }
5692
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005693 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005694 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005695 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005696 if (method.GetDeclaringClass() == temp_class) {
5697 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005698 }
5699 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005700
5701 // Make sure the remembered set and mod-union tables know that we updated some of the native
5702 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005703 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005704}
5705
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005706void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005707 CHECK(class_loader->GetAllocator() == nullptr);
5708 CHECK(class_loader->GetClassTable() == nullptr);
5709 Thread* const self = Thread::Current();
5710 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005711 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005712 // Create and set the class table.
5713 data.class_table = new ClassTable;
5714 class_loader->SetClassTable(data.class_table);
5715 // Create and set the linear allocator.
5716 data.allocator = Runtime::Current()->CreateLinearAlloc();
5717 class_loader->SetAllocator(data.allocator);
5718 // Add to the list so that we know to free the data later.
5719 class_loaders_.push_back(data);
5720}
5721
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005722ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005723 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005724 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005725 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005726 ClassTable* class_table = class_loader->GetClassTable();
5727 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005728 RegisterClassLoader(class_loader);
5729 class_table = class_loader->GetClassTable();
5730 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005731 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005732 return class_table;
5733}
5734
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005735ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005736 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005737}
5738
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005739static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005740 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005741 while (klass->HasSuperClass()) {
5742 klass = klass->GetSuperClass();
5743 if (klass->ShouldHaveImt()) {
5744 return klass->GetImt(pointer_size);
5745 }
5746 }
5747 return nullptr;
5748}
5749
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005750bool ClassLinker::LinkClass(Thread* self,
5751 const char* descriptor,
5752 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005753 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005754 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005755 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005756
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005757 if (!LinkSuperClass(klass)) {
5758 return false;
5759 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005760 ArtMethod* imt_data[ImTable::kSize];
5761 // If there are any new conflicts compared to super class.
5762 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005763 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005764 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005765 return false;
5766 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005767 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005768 return false;
5769 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005770 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005771 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005772 return false;
5773 }
5774 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005775 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005776
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005777 ImTable* imt = nullptr;
5778 if (klass->ShouldHaveImt()) {
5779 // If there are any new conflicts compared to the super class we can not make a copy. There
5780 // can be cases where both will have a conflict method at the same slot without having the same
5781 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5782 // will possibly create a table that is incorrect for either of the classes.
5783 // Same IMT with new_conflict does not happen very often.
5784 if (!new_conflict) {
5785 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5786 if (super_imt != nullptr) {
5787 bool imt_equals = true;
5788 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5789 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5790 }
5791 if (imt_equals) {
5792 imt = super_imt;
5793 }
5794 }
5795 }
5796 if (imt == nullptr) {
5797 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5798 imt = reinterpret_cast<ImTable*>(
5799 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5800 if (imt == nullptr) {
5801 return false;
5802 }
5803 imt->Populate(imt_data, image_pointer_size_);
5804 }
5805 }
5806
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005807 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5808 // We don't need to retire this class as it has no embedded tables or it was created the
5809 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005810 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005811
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005812 if (klass->ShouldHaveEmbeddedVTable()) {
5813 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005814 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005815 if (klass->ShouldHaveImt()) {
5816 klass->SetImt(imt, image_pointer_size_);
5817 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005818
5819 // Update CHA info based on whether we override methods.
5820 // Have to do this before setting the class as resolved which allows
5821 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005822 if (cha_ != nullptr) {
5823 cha_->UpdateAfterLoadingOf(klass);
5824 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005825
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005826 // This will notify waiters on klass that saw the not yet resolved
5827 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005828 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005829 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005830 } else {
5831 CHECK(!klass->IsResolved());
5832 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005833 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005834 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005835 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5836 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5837 // may not see any references to the target space and clean the card for a class if another
5838 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005839 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005840 klass->SetSFieldsPtrUnchecked(nullptr);
5841 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005842 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005843 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005844 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005845 return false;
5846 }
5847
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005848 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5849 ObjectLock<mirror::Class> lock(self, h_new_class);
5850 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005851
5852 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005853 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005854 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005855 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005856 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005857 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005858 if (class_loader != nullptr) {
5859 // We updated the class in the class table, perform the write barrier so that the GC knows
5860 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005861 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005862 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005863 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005864 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005865 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5866 }
5867 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005868
Mingyao Yang063fc772016-08-02 11:02:54 -07005869 // Update CHA info based on whether we override methods.
5870 // Have to do this before setting the class as resolved which allows
5871 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005872 if (cha_ != nullptr) {
5873 cha_->UpdateAfterLoadingOf(h_new_class);
5874 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005875
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005876 // This will notify waiters on temp class that saw the not yet resolved class in the
5877 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005878 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005879
Vladimir Marko2c64a832018-01-04 11:31:56 +00005880 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005881 // This will notify waiters on new_class that saw the not yet resolved
5882 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005883 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005884 // Return the new class.
5885 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005886 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005887 return true;
5888}
5889
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005890bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005891 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005892 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005893 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5894 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005895 // Check that a class does not inherit from itself directly.
5896 //
5897 // TODO: This is a cheap check to detect the straightforward case
5898 // of a class extending itself (b/28685551), but we should do a
5899 // proper cycle detection on loaded classes, to detect all cases
5900 // of class circularity errors (b/28830038).
5901 if (super_class_idx == class_def.class_idx_) {
5902 ThrowClassCircularityError(klass.Get(),
5903 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005904 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005905 return false;
5906 }
5907
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005908 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005909 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005910 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005911 return false;
5912 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005913 // Verify
5914 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005915 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005916 super_class->PrettyDescriptor().c_str(),
5917 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005918 return false;
5919 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005920 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005921 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005922 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005923 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005924 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005925 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005926 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005927 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005928 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005929 DCHECK(Thread::Current()->IsExceptionPending());
5930 return false;
5931 }
5932 // Verify
5933 if (!klass->CanAccess(interface)) {
5934 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005935 ThrowIllegalAccessError(klass.Get(),
5936 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005937 interface->PrettyDescriptor().c_str(),
5938 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005939 return false;
5940 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005941 }
5942 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005943 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005944 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005945 return true;
5946}
5947
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005948bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005949 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005950 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005951 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5952 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005953 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005954 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005955 return false;
5956 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005957 return true;
5958 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005959 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005960 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005961 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005962 return false;
5963 }
5964 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005965 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005966 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5967 return false;
5968 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005969 if (super->IsFinal()) {
5970 ThrowVerifyError(klass.Get(),
5971 "Superclass %s of %s is declared final",
5972 super->PrettyDescriptor().c_str(),
5973 klass->PrettyDescriptor().c_str());
5974 return false;
5975 }
5976 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005977 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005978 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005979 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005980 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005981 return false;
5982 }
5983 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005984 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005985 super->PrettyDescriptor().c_str(),
5986 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005987 return false;
5988 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005989
Brian Carlstromf3632832014-05-20 15:36:53 -07005990 // Inherit kAccClassIsFinalizable from the superclass in case this
5991 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005992 if (super->IsFinalizable()) {
5993 klass->SetFinalizable();
5994 }
5995
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005996 // Inherit class loader flag form super class.
5997 if (super->IsClassLoaderClass()) {
5998 klass->SetClassLoaderClass();
5999 }
6000
Elliott Hughes2da50362011-10-10 16:57:08 -07006001 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006002 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006003 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006004 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006005 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006006 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006007 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006008 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006009 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006010 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006011 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006012 return false;
6013 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006014
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006015 if (kIsDebugBuild) {
6016 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006017 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006018 CHECK(super->IsResolved());
6019 super = super->GetSuperClass();
6020 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006021 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006022 return true;
6023}
6024
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006025// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006026bool ClassLinker::LinkMethods(Thread* self,
6027 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006028 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006029 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006030 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006031 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006032 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6033 // need to have default methods be in the virtuals array of each class but we don't set that up
6034 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006035 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006036 // Link virtual methods then interface methods.
6037 // We set up the interface lookup table first because we need it to determine if we need to update
6038 // any vtable entries with new default method implementations.
6039 return SetupInterfaceLookupTable(self, klass, interfaces)
6040 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006041 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006042}
6043
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006044// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6045// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6046// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006047class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006048 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006049 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006050 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006051 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6052 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006053 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006054 }
6055
6056 const char* GetName() {
6057 if (name_ == nullptr) {
6058 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6059 }
6060 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006061 }
6062
Mathieu Chartiere401d142015-04-22 13:56:20 -07006063 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006064 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006065 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006066 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006067 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006068 if (dex_file_ == other_dex_file) {
6069 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6070 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006071 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006072 uint32_t other_name_len;
6073 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6074 &other_name_len);
6075 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6076 return false;
6077 }
6078 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6079 }
6080
6081 private:
6082 // Dex file for the method to compare against.
6083 const DexFile* const dex_file_;
6084 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006085 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006086 // Lazily computed name from the dex file's strings.
6087 const char* name_;
6088 // Lazily computed name length.
6089 uint32_t name_len_;
6090};
6091
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006092class LinkVirtualHashTable {
6093 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006094 LinkVirtualHashTable(Handle<mirror::Class> klass,
6095 size_t hash_size,
6096 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006097 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006098 : klass_(klass),
6099 hash_size_(hash_size),
6100 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006101 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006102 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6103 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006104
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006105 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006106 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6107 virtual_method_index, image_pointer_size_);
6108 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006109 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006110 uint32_t index = hash % hash_size_;
6111 // Linear probe until we have an empty slot.
6112 while (hash_table_[index] != invalid_index_) {
6113 if (++index == hash_size_) {
6114 index = 0;
6115 }
6116 }
6117 hash_table_[index] = virtual_method_index;
6118 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006119
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006120 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006121 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006122 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006123 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006124 size_t index = hash % hash_size_;
6125 while (true) {
6126 const uint32_t value = hash_table_[index];
6127 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6128 // the block and can safely assume not found.
6129 if (value == invalid_index_) {
6130 break;
6131 }
6132 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006133 ArtMethod* virtual_method =
6134 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6135 if (comparator->HasSameNameAndSignature(
6136 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006137 hash_table_[index] = removed_index_;
6138 return value;
6139 }
6140 }
6141 if (++index == hash_size_) {
6142 index = 0;
6143 }
6144 }
6145 return GetNotFoundIndex();
6146 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006147
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006148 static uint32_t GetNotFoundIndex() {
6149 return invalid_index_;
6150 }
6151
6152 private:
6153 static const uint32_t invalid_index_;
6154 static const uint32_t removed_index_;
6155
6156 Handle<mirror::Class> klass_;
6157 const size_t hash_size_;
6158 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006159 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006160};
6161
6162const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6163const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6164
Stephen Hines1ddd9132017-02-08 01:51:18 -08006165bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006166 Thread* self,
6167 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006168 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006169 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006170 if (klass->IsInterface()) {
6171 // No vtable.
6172 if (!IsUint<16>(num_virtual_methods)) {
6173 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6174 return false;
6175 }
6176 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006177 // Assign each method an IMT index and set the default flag.
6178 for (size_t i = 0; i < num_virtual_methods; ++i) {
6179 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6180 m->SetMethodIndex(i);
6181 if (!m->IsAbstract()) {
6182 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6183 has_defaults = true;
6184 }
6185 }
6186 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6187 // during initialization. This is a performance optimization. We could simply traverse the
6188 // virtual_methods_ array again during initialization.
6189 if (has_defaults) {
6190 klass->SetHasDefaultMethods();
6191 }
6192 return true;
6193 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006194 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6195 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006196 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006197 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006198 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006199 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006200 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006201 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006202 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006203 return false;
6204 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006205 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006206 vtable->SetElementPtrSize(
6207 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006208 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006209 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6210 // might give us new default methods). If no new interfaces then we can skip the rest since
6211 // the class cannot override any of the super-class's methods. This is required for
6212 // correctness since without it we might not update overridden default method vtable entries
6213 // correctly.
6214 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006215 klass->SetVTable(vtable.Get());
6216 return true;
6217 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006218 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006219 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Markoc524e9e2019-03-26 10:54:50 +00006220 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006221 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006222 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6223 // might give us new default methods). See comment above.
6224 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006225 klass->SetVTable(super_vtable);
6226 return true;
6227 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006228 vtable = hs.NewHandle(
6229 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006230 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006231 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006232 return false;
6233 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006234 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006235 // How the algorithm works:
6236 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6237 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6238 // method which has not been matched to a vtable method, and j if the virtual method at the
6239 // index overrode the super virtual method at index j.
6240 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6241 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6242 // the need for the initial vtable which we later shrink back down).
6243 // 3. Add non overridden methods to the end of the vtable.
6244 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006245 // + 1 so that even if we only have new default methods we will still be able to use this hash
6246 // table (i.e. it will never have 0 size).
6247 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006248 uint32_t* hash_table_ptr;
6249 std::unique_ptr<uint32_t[]> hash_heap_storage;
6250 if (hash_table_size <= kMaxStackHash) {
6251 hash_table_ptr = reinterpret_cast<uint32_t*>(
6252 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6253 } else {
6254 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6255 hash_table_ptr = hash_heap_storage.get();
6256 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006257 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006258 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006259 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006260 DCHECK(klass->GetVirtualMethodDuringLinking(
6261 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006262 hash_table.Add(i);
6263 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006264 // 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 -07006265 // the hash table.
6266 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006267 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006268 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006269 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6270 super_method->GetAccessFlags())) {
6271 // Continue on to the next method since this one is package private and canot be overridden.
6272 // Before Android 4.1, the package-private method super_method might have been incorrectly
6273 // overridden.
6274 continue;
6275 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006276 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006277 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006278 // We remove the method so that subsequent lookups will be faster by making the hash-map
6279 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006280 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6281 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006282 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6283 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006284 if (super_method->IsFinal()) {
6285 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6286 virtual_method->PrettyMethod().c_str(),
6287 super_method->GetDeclaringClassDescriptor());
6288 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006289 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006290 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6291 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006292 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006293 // We didn't directly override this method but we might through default methods...
6294 // Check for default method update.
6295 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006296 switch (FindDefaultMethodImplementation(self,
6297 super_method,
6298 klass,
6299 /*out*/&default_method)) {
6300 case DefaultMethodSearchResult::kDefaultConflict: {
6301 // A conflict was found looking for default methods. Note this (assuming it wasn't
6302 // pre-existing) in the translations map.
6303 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6304 // Don't generate another conflict method to reduce memory use as an optimization.
6305 default_translations->insert(
6306 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6307 }
6308 break;
6309 }
6310 case DefaultMethodSearchResult::kAbstractFound: {
6311 // No conflict but method is abstract.
6312 // We note that this vtable entry must be made abstract.
6313 if (UNLIKELY(!super_method->IsAbstract())) {
6314 default_translations->insert(
6315 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6316 }
6317 break;
6318 }
6319 case DefaultMethodSearchResult::kDefaultFound: {
6320 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6321 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6322 // Found a default method implementation that is new.
6323 // TODO Refactor this add default methods to virtuals here and not in
6324 // LinkInterfaceMethods maybe.
6325 // The problem is default methods might override previously present
6326 // default-method or miranda-method vtable entries from the superclass.
6327 // Unfortunately we need these to be entries in this class's virtuals. We do not
6328 // give these entries there until LinkInterfaceMethods so we pass this map around
6329 // to let it know which vtable entries need to be updated.
6330 // Make a note that vtable entry j must be updated, store what it needs to be updated
6331 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6332 // then.
6333 default_translations->insert(
6334 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006335 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6336 << " overridden by default "
6337 << default_method->PrettyMethod()
6338 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006339 }
6340 break;
6341 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006342 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006343 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006344 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006345 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006346 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006347 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006348 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006349 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6350 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006351 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006352 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006353 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006354 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006355 local_method->SetMethodIndex(actual_count);
6356 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006357 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006358 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006359 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006360 return false;
6361 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006362 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006363 CHECK_LE(actual_count, max_count);
6364 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006365 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006366 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006367 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006368 return false;
6369 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006370 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006371 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006372 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006373 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006374 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006375 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6376 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006377 return false;
6378 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006379 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006380 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006381 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006382 return false;
6383 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006384 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006385 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6386 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006387 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006388 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006389 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006390 }
6391 return true;
6392}
6393
Alex Light9139e002015-10-09 15:59:48 -07006394// Determine if the given iface has any subinterface in the given list that declares the method
6395// specified by 'target'.
6396//
6397// Arguments
6398// - self: The thread we are running on
6399// - target: A comparator that will match any method that overrides the method we are checking for
6400// - iftable: The iftable we are searching for an overriding method on.
6401// - ifstart: The index of the interface we are checking to see if anything overrides
6402// - iface: The interface we are checking to see if anything overrides.
6403// - image_pointer_size:
6404// The image pointer size.
6405//
6406// Returns
6407// - True: There is some method that matches the target comparator defined in an interface that
6408// is a subtype of iface.
6409// - False: There is no method that matches the target comparator in any interface that is a subtype
6410// of iface.
6411static bool ContainsOverridingMethodOf(Thread* self,
6412 MethodNameAndSignatureComparator& target,
6413 Handle<mirror::IfTable> iftable,
6414 size_t ifstart,
6415 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006416 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006417 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006418 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006419 DCHECK(iface != nullptr);
6420 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006421 DCHECK_GE(ifstart, 0u);
6422 DCHECK_LT(ifstart, iftable->Count());
6423 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6424 DCHECK(iface->IsInterface());
6425
6426 size_t iftable_count = iftable->Count();
6427 StackHandleScope<1> hs(self);
6428 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6429 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6430 // Skip ifstart since our current interface obviously cannot override itself.
6431 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006432 // Iterate through every method on this interface. The order does not matter.
6433 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006434 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006435 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006436 // Check if the i'th interface is a subtype of this one.
6437 if (iface->IsAssignableFrom(current_iface.Get())) {
6438 return true;
6439 }
6440 break;
6441 }
6442 }
6443 }
6444 return false;
6445}
6446
Alex Lighteb7c1442015-08-31 13:17:42 -07006447// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006448// out_default_method and returns kDefaultFound on success. If no default method was found return
6449// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6450// default_method conflict) it will return kDefaultConflict.
6451ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6452 Thread* self,
6453 ArtMethod* target_method,
6454 Handle<mirror::Class> klass,
6455 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006456 DCHECK(self != nullptr);
6457 DCHECK(target_method != nullptr);
6458 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006459
6460 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006461
6462 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6463 // table. This lets us walk the table backwards when searching for default methods. The first one
6464 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6465 // track of it and then continue checking all other interfaces, since we need to throw an error if
6466 // we encounter conflicting default method implementations (one is not a subtype of the other).
6467 //
6468 // The order of unrelated interfaces does not matter and is not defined.
6469 size_t iftable_count = klass->GetIfTableCount();
6470 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006471 // No interfaces. We have already reset out to null so just return kAbstractFound.
6472 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006473 }
6474
Alex Light9139e002015-10-09 15:59:48 -07006475 StackHandleScope<3> hs(self);
6476 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006477 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006478 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006479 MethodNameAndSignatureComparator target_name_comparator(
6480 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6481 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006482 for (size_t k = iftable_count; k != 0; ) {
6483 --k;
6484
Alex Lighteb7c1442015-08-31 13:17:42 -07006485 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006486
6487 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006488 // Iterate through every declared method on this interface. The order does not matter.
6489 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6490 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006491 // Skip abstract methods and methods with different names.
6492 if (current_method->IsAbstract() ||
6493 !target_name_comparator.HasSameNameAndSignature(
6494 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6495 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006496 } else if (!current_method->IsPublic()) {
6497 // The verifier should have caught the non-public method for dex version 37. Just warn and
6498 // skip it since this is from before default-methods so we don't really need to care that it
6499 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006500 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6501 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006502 << "This will be a fatal error in subsequent versions of android. "
6503 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006504 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006505 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006506 // We have multiple default impls of the same method. This is a potential default conflict.
6507 // We need to check if this possibly conflicting method is either a superclass of the chosen
6508 // default implementation or is overridden by a non-default interface method. In either case
6509 // there is no conflict.
6510 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6511 !ContainsOverridingMethodOf(self,
6512 target_name_comparator,
6513 iftable,
6514 k,
6515 iface,
6516 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006517 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006518 << current_method->PrettyMethod() << " and "
6519 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6520 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006521 *out_default_method = nullptr;
6522 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006523 } else {
6524 break; // Continue checking at the next interface.
6525 }
6526 } else {
Alex Light9139e002015-10-09 15:59:48 -07006527 // chosen_iface == null
6528 if (!ContainsOverridingMethodOf(self,
6529 target_name_comparator,
6530 iftable,
6531 k,
6532 iface,
6533 image_pointer_size_)) {
6534 // Don't set this as the chosen interface if something else is overriding it (because that
6535 // other interface would be potentially chosen instead if it was default). If the other
6536 // interface was abstract then we wouldn't select this interface as chosen anyway since
6537 // the abstract method masks it.
6538 *out_default_method = current_method;
6539 chosen_iface.Assign(iface.Get());
6540 // We should now finish traversing the graph to find if we have default methods that
6541 // conflict.
6542 } else {
David Sehr709b0702016-10-13 09:12:37 -07006543 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6544 << "' was "
6545 << "skipped because it was overridden by an abstract method in a "
6546 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006547 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006548 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006549 break;
6550 }
6551 }
Alex Light9139e002015-10-09 15:59:48 -07006552 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006553 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6554 << "' selected "
6555 << "as the implementation for '" << target_method->PrettyMethod()
6556 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006557 return DefaultMethodSearchResult::kDefaultFound;
6558 } else {
6559 return DefaultMethodSearchResult::kAbstractFound;
6560 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006561}
6562
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006563ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006564 ArtMethod* conflict_method,
6565 ArtMethod* interface_method,
6566 ArtMethod* method,
6567 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006568 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006569 Runtime* const runtime = Runtime::Current();
6570 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6571 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6572
6573 // Create a new entry if the existing one is the shared conflict method.
6574 ArtMethod* new_conflict_method = new_entry
6575 ? runtime->CreateImtConflictMethod(linear_alloc)
6576 : conflict_method;
6577
6578 // Allocate a new table. Note that we will leak this table at the next conflict,
6579 // but that's a tradeoff compared to making the table fixed size.
6580 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006581 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6582 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006583 if (data == nullptr) {
6584 LOG(ERROR) << "Failed to allocate conflict table";
6585 return conflict_method;
6586 }
6587 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6588 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006589 method,
6590 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006591
6592 // Do a fence to ensure threads see the data in the table before it is assigned
6593 // to the conflict method.
6594 // Note that there is a race in the presence of multiple threads and we may leak
6595 // memory from the LinearAlloc, but that's a tradeoff compared to using
6596 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006597 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006598 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006599 return new_conflict_method;
6600}
6601
Vladimir Marko921094a2017-01-12 18:37:06 +00006602bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6603 Handle<mirror::Class> klass,
6604 Handle<mirror::IfTable> iftable) {
6605 DCHECK(!klass->IsInterface());
6606 const bool has_superclass = klass->HasSuperClass();
6607 const bool extend_super_iftable = has_superclass;
6608 const size_t ifcount = klass->GetIfTableCount();
6609 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6610 for (size_t i = 0; i < ifcount; ++i) {
6611 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6612 if (num_methods > 0) {
6613 const bool is_super = i < super_ifcount;
6614 // This is an interface implemented by a super-class. Therefore we can just copy the method
6615 // array from the superclass.
6616 const bool super_interface = is_super && extend_super_iftable;
6617 ObjPtr<mirror::PointerArray> method_array;
6618 if (super_interface) {
6619 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6620 DCHECK(if_table != nullptr);
6621 DCHECK(if_table->GetMethodArray(i) != nullptr);
6622 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006623 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6624 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006625 } else {
6626 method_array = AllocPointerArray(self, num_methods);
6627 }
6628 if (UNLIKELY(method_array == nullptr)) {
6629 self->AssertPendingOOMException();
6630 return false;
6631 }
6632 iftable->SetMethodArray(i, method_array);
6633 }
6634 }
6635 return true;
6636}
6637
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006638void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6639 ArtMethod* imt_conflict_method,
6640 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006641 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006642 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006643 // Place method in imt if entry is empty, place conflict otherwise.
6644 if (*imt_ref == unimplemented_method) {
6645 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006646 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006647 // If we are not a conflict and we have the same signature and name as the imt
6648 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006649 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6650 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006651 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006652 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006653 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006654 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006655 *imt_ref = current_method;
6656 } else {
Alex Light9139e002015-10-09 15:59:48 -07006657 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006658 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006659 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006660 } else {
6661 // Place the default conflict method. Note that there may be an existing conflict
6662 // method in the IMT, but it could be one tailored to the super class, with a
6663 // specific ImtConflictTable.
6664 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006665 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006666 }
6667}
6668
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006669void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006670 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6671 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006672 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006673 Runtime* const runtime = Runtime::Current();
6674 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6675 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006676 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006677 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006678 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006679 FillIMTFromIfTable(klass->GetIfTable(),
6680 unimplemented_method,
6681 conflict_method,
6682 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006683 /*create_conflict_tables=*/true,
6684 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006685 &new_conflict,
6686 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006687 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006688 if (!klass->ShouldHaveImt()) {
6689 return;
6690 }
6691 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6692 // we can just use the same pointer.
6693 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006694 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006695 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6696 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6697 bool same = true;
6698 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6699 ArtMethod* method = imt_data[i];
6700 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6701 if (method != super_method) {
6702 bool is_conflict_table = method->IsRuntimeMethod() &&
6703 method != unimplemented_method &&
6704 method != conflict_method;
6705 // Verify conflict contents.
6706 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6707 super_method != unimplemented_method &&
6708 super_method != conflict_method;
6709 if (!is_conflict_table || !super_conflict_table) {
6710 same = false;
6711 } else {
6712 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6713 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6714 same = same && table1->Equals(table2, image_pointer_size_);
6715 }
6716 }
6717 }
6718 if (same) {
6719 imt = super_imt;
6720 }
6721 }
6722 if (imt == nullptr) {
6723 imt = klass->GetImt(image_pointer_size_);
6724 DCHECK(imt != nullptr);
6725 imt->Populate(imt_data, image_pointer_size_);
6726 } else {
6727 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006728 }
6729}
6730
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006731ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6732 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006733 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006734 void* data = linear_alloc->Alloc(Thread::Current(),
6735 ImtConflictTable::ComputeSize(count,
6736 image_pointer_size));
6737 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6738}
6739
6740ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6741 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6742}
6743
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006744void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006745 ArtMethod* unimplemented_method,
6746 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006747 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006748 bool create_conflict_tables,
6749 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006750 /*out*/bool* new_conflict,
6751 /*out*/ArtMethod** imt) {
6752 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006753 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006754 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006755 const size_t num_virtuals = interface->NumVirtualMethods();
6756 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6757 // Virtual methods can be larger than the if table methods if there are default methods.
6758 DCHECK_GE(num_virtuals, method_array_count);
6759 if (kIsDebugBuild) {
6760 if (klass->IsInterface()) {
6761 DCHECK_EQ(method_array_count, 0u);
6762 } else {
6763 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6764 }
6765 }
6766 if (method_array_count == 0) {
6767 continue;
6768 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006769 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006770 for (size_t j = 0; j < method_array_count; ++j) {
6771 ArtMethod* implementation_method =
6772 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6773 if (ignore_copied_methods && implementation_method->IsCopied()) {
6774 continue;
6775 }
6776 DCHECK(implementation_method != nullptr);
6777 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6778 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6779 // or interface methods in the IMT here they will not create extra conflicts since we compare
6780 // names and signatures in SetIMTRef.
6781 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006782 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006783
6784 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6785 // the same implementation method, keep track of this to avoid creating a conflict table in
6786 // this case.
6787
6788 // Conflict table size for each IMT slot.
6789 ++conflict_counts[imt_index];
6790
6791 SetIMTRef(unimplemented_method,
6792 imt_conflict_method,
6793 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006794 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006795 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006796 }
6797 }
6798
6799 if (create_conflict_tables) {
6800 // Create the conflict tables.
6801 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006802 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006803 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006804 if (imt[i] == imt_conflict_method) {
6805 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6806 if (new_table != nullptr) {
6807 ArtMethod* new_conflict_method =
6808 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6809 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6810 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006811 } else {
6812 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006813 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006814 }
6815 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006816 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006817 }
6818 }
6819
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006820 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006821 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006822 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6823 // Virtual methods can be larger than the if table methods if there are default methods.
6824 if (method_array_count == 0) {
6825 continue;
6826 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006827 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006828 for (size_t j = 0; j < method_array_count; ++j) {
6829 ArtMethod* implementation_method =
6830 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6831 if (ignore_copied_methods && implementation_method->IsCopied()) {
6832 continue;
6833 }
6834 DCHECK(implementation_method != nullptr);
6835 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006836 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006837 if (!imt[imt_index]->IsRuntimeMethod() ||
6838 imt[imt_index] == unimplemented_method ||
6839 imt[imt_index] == imt_conflict_method) {
6840 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006841 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006842 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6843 const size_t num_entries = table->NumEntries(image_pointer_size_);
6844 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6845 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006846 }
6847 }
6848 }
6849}
6850
Alex Lighteb7c1442015-08-31 13:17:42 -07006851// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6852// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006853static bool NotSubinterfaceOfAny(
6854 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6855 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006856 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006857 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006858 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006859 for (ObjPtr<mirror::Class> c : classes) {
6860 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006861 return false;
6862 }
6863 }
6864 return true;
6865}
6866
6867// Fills in and flattens the interface inheritance hierarchy.
6868//
6869// By the end of this function all interfaces in the transitive closure of to_process are added to
6870// the iftable and every interface precedes all of its sub-interfaces in this list.
6871//
6872// all I, J: Interface | I <: J implies J precedes I
6873//
6874// (note A <: B means that A is a subtype of B)
6875//
6876// This returns the total number of items in the iftable. The iftable might be resized down after
6877// this call.
6878//
6879// We order this backwards so that we do not need to reorder superclass interfaces when new
6880// interfaces are added in subclass's interface tables.
6881//
6882// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6883// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6884// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6885// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006886static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006887 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006888 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006889 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006890 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006891 // This is the set of all class's already in the iftable. Used to make checking if a class has
6892 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006893 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006894 // The first super_ifcount elements are from the superclass. We note that they are already added.
6895 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006896 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006897 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6898 classes_in_iftable.insert(iface);
6899 }
6900 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006901 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006902 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6903 // At this point in the loop current-iface-list has the invariant that:
6904 // for every pair of interfaces I,J within it:
6905 // if index_of(I) < index_of(J) then I is not a subtype of J
6906
6907 // If we have already seen this element then all of its super-interfaces must already be in the
6908 // current-iface-list so we can skip adding it.
6909 if (!ContainsElement(classes_in_iftable, interface)) {
6910 // We haven't seen this interface so add all of its super-interfaces onto the
6911 // current-iface-list, skipping those already on it.
6912 int32_t ifcount = interface->GetIfTableCount();
6913 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006914 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006915 if (!ContainsElement(classes_in_iftable, super_interface)) {
6916 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6917 classes_in_iftable.insert(super_interface);
6918 iftable->SetInterface(filled_ifcount, super_interface);
6919 filled_ifcount++;
6920 }
6921 }
6922 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6923 // Place this interface onto the current-iface-list after all of its super-interfaces.
6924 classes_in_iftable.insert(interface);
6925 iftable->SetInterface(filled_ifcount, interface);
6926 filled_ifcount++;
6927 } else if (kIsDebugBuild) {
6928 // Check all super-interfaces are already in the list.
6929 int32_t ifcount = interface->GetIfTableCount();
6930 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006931 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006932 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006933 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6934 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006935 }
6936 }
6937 }
6938 if (kIsDebugBuild) {
6939 // Check that the iftable is ordered correctly.
6940 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006941 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006942 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006943 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006944 // !(if_a <: if_b)
6945 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006946 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6947 << ") extends "
6948 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006949 << "interface list.";
6950 }
6951 }
6952 }
6953 return filled_ifcount;
6954}
6955
6956bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6957 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6958 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006959 const bool has_superclass = klass->HasSuperClass();
6960 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006961 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006962 const size_t num_interfaces =
6963 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006964 if (num_interfaces == 0) {
6965 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006966 if (LIKELY(has_superclass)) {
6967 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6968 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006969 // Class implements no interfaces.
6970 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006971 return true;
6972 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006973 // Class implements same interfaces as parent, are any of these not marker interfaces?
6974 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006975 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006976 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006977 if (super_iftable->GetMethodArrayCount(i) > 0) {
6978 has_non_marker_interface = true;
6979 break;
6980 }
6981 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006982 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006983 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006984 klass->SetIfTable(super_iftable);
6985 return true;
6986 }
6987 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006988 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006989 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006990 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006991 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006992 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006993 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006994 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006995 if (UNLIKELY(!interface->IsInterface())) {
6996 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006997 ThrowIncompatibleClassChangeError(klass.Get(),
6998 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006999 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007000 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7001 return false;
7002 }
7003 ifcount += interface->GetIfTableCount();
7004 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007005 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007006 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007007 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007008 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007009 return false;
7010 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007011 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007012 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007013 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007014 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007015 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007016 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007017 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007018 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007019
7020 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7021 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7022 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007023 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007024
7025 size_t new_ifcount;
7026 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007027 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007028 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007029 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007030 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007031 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007032 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007033 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007034
7035 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007036 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007037
Ian Rogers7b078e82014-09-10 14:44:24 -07007038 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007039
Ian Rogersb52b01a2012-01-12 17:01:38 -08007040 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007041 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007042 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007043 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007044 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007045 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007046 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007047 return false;
7048 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007049 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007050 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007051 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007052 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007053 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007054 return true;
7055}
7056
Alex Light1f3925d2016-09-07 12:04:20 -07007057// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7058// of methods must be unique.
7059static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7060 return nullptr;
7061}
7062
7063template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007064static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007065 const ScopedArenaVector<ArtMethod*>& list,
7066 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007067 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007068 for (ArtMethod* method : list) {
7069 if (cmp.HasSameNameAndSignature(method)) {
7070 return method;
7071 }
7072 }
Alex Light1f3925d2016-09-07 12:04:20 -07007073 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007074}
7075
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007076namespace {
7077
Alex Light1f3925d2016-09-07 12:04:20 -07007078// Check that all vtable entries are present in this class's virtuals or are the same as a
7079// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007080void CheckClassOwnsVTableEntries(Thread* self,
7081 Handle<mirror::Class> klass,
7082 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007083 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007084 StackHandleScope<2> hs(self);
7085 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007086 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007087 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007088 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007089 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7090 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7091 CHECK(m != nullptr);
7092
Alex Lighta41a30782017-03-29 11:33:19 -07007093 if (m->GetMethodIndexDuringLinking() != i) {
7094 LOG(WARNING) << m->PrettyMethod()
7095 << " has an unexpected method index for its spot in the vtable for class"
7096 << klass->PrettyClass();
7097 }
Alex Lighte64300b2015-12-15 15:02:47 -08007098 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7099 auto is_same_method = [m] (const ArtMethod& meth) {
7100 return &meth == m;
7101 };
Alex Light3f980532017-03-17 15:10:32 -07007102 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7103 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7104 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7105 << klass->PrettyClass() << " or any of its superclasses!";
7106 }
Alex Lighte64300b2015-12-15 15:02:47 -08007107 }
7108}
7109
Alex Light1f3925d2016-09-07 12:04:20 -07007110// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7111// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007112template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007113void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007114 REQUIRES_SHARED(Locks::mutator_lock_) {
7115 StackHandleScope<1> hs(self);
7116 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7117 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007118
7119 // Observations:
7120 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7121 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7122 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7123 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7124 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7125 // * The single-pass algorithm will trade memory for speed, but that is OK.
7126
7127 CHECK_GT(num_entries, 0);
7128
7129 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7130 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7131 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7132 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7133 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7134 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7135 << m2->PrettyMethod() << " (0x" << std::hex
7136 << reinterpret_cast<uintptr_t>(m2) << ")";
7137 };
7138 struct BaseHashType {
7139 static size_t HashCombine(size_t seed, size_t val) {
7140 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7141 }
7142 };
7143
7144 // Check assuming all entries come from the same dex file.
7145 {
7146 // Find the first interesting method and its dex file.
7147 int32_t start = 0;
7148 for (; start < num_entries; ++start) {
7149 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7150 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7151 // maybe).
7152 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7153 vtable_entry->GetAccessFlags())) {
7154 continue;
7155 }
7156 break;
7157 }
7158 if (start == num_entries) {
7159 return;
7160 }
7161 const DexFile* dex_file =
7162 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7163 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7164
7165 // Helper function to avoid logging if we have to run the cross-file checks.
7166 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7167 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7168 using PairType = std::pair<uint32_t, uint16_t>;
7169 struct PairHash : BaseHashType {
7170 size_t operator()(const PairType& key) const {
7171 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7172 }
7173 };
7174 std::unordered_map<PairType, int32_t, PairHash> seen;
7175 seen.reserve(2 * num_entries);
7176 bool need_slow_path = false;
7177 bool found_dup = false;
7178 for (int i = start; i < num_entries; ++i) {
7179 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7180 // wrt/ kPointerSize.
7181 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7182 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7183 vtable_entry->GetAccessFlags())) {
7184 continue;
7185 }
7186 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7187 if (dex_file != m->GetDexFile()) {
7188 need_slow_path = true;
7189 break;
7190 }
7191 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7192 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7193 auto it = seen.find(pair);
7194 if (it != seen.end()) {
7195 found_dup = true;
7196 if (log_warn) {
7197 log_fn(it->second, i);
7198 }
7199 } else {
7200 seen.emplace(pair, i);
7201 }
7202 }
7203 return std::make_pair(need_slow_path, found_dup);
7204 };
7205 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7206 if (!result.first) {
7207 if (result.second) {
7208 check_fn(/* log_warn= */ true);
7209 }
7210 return;
7211 }
7212 }
7213
7214 // Need to check across dex files.
7215 struct Entry {
7216 size_t cached_hash = 0;
7217 const char* name = nullptr;
7218 Signature signature = Signature::NoSignature();
7219 uint32_t name_len = 0;
7220
7221 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7222 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7223 signature(dex_file->GetMethodSignature(mid)) {
7224 }
7225
7226 bool operator==(const Entry& other) const {
7227 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7228 return false;
7229 }
7230 return signature == other.signature;
7231 }
7232 };
7233 struct EntryHash {
7234 size_t operator()(const Entry& key) const {
7235 return key.cached_hash;
7236 }
7237 };
7238 std::unordered_map<Entry, int32_t, EntryHash> map;
7239 for (int32_t i = 0; i < num_entries; ++i) {
7240 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7241 // wrt/ kPointerSize.
7242 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7243 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7244 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007245 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7246 vtable_entry->GetAccessFlags())) {
7247 continue;
7248 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007249 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7250 const DexFile* dex_file = m->GetDexFile();
7251 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7252
7253 Entry e(dex_file, mid);
7254
7255 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7256 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7257 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7258 sig_hash);
7259
7260 auto it = map.find(e);
7261 if (it != map.end()) {
7262 log_fn(it->second, i);
7263 } else {
7264 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007265 }
7266 }
7267}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007268
7269void CheckVTableHasNoDuplicates(Thread* self,
7270 Handle<mirror::Class> klass,
7271 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007272 REQUIRES_SHARED(Locks::mutator_lock_) {
7273 switch (pointer_size) {
7274 case PointerSize::k64:
7275 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7276 break;
7277 case PointerSize::k32:
7278 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7279 break;
7280 }
7281}
Alex Light1f3925d2016-09-07 12:04:20 -07007282
7283static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7284 REQUIRES_SHARED(Locks::mutator_lock_) {
7285 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7286 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7287}
7288
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007289} // namespace
7290
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007291void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7292 ArtMethod* unimplemented_method,
7293 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007294 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007295 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007296 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007297 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007298 if (super_class->ShouldHaveImt()) {
7299 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7300 for (size_t i = 0; i < ImTable::kSize; ++i) {
7301 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007302 }
7303 } else {
7304 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007305 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007306 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007307 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007308 FillIMTFromIfTable(if_table,
7309 unimplemented_method,
7310 imt_conflict_method,
7311 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007312 /*create_conflict_tables=*/false,
7313 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007314 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007315 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007316 }
7317 }
7318}
7319
Vladimir Marko921094a2017-01-12 18:37:06 +00007320class ClassLinker::LinkInterfaceMethodsHelper {
7321 public:
7322 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7323 Handle<mirror::Class> klass,
7324 Thread* self,
7325 Runtime* runtime)
7326 : class_linker_(class_linker),
7327 klass_(klass),
7328 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7329 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7330 self_(self),
7331 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7332 allocator_(&stack_),
7333 default_conflict_methods_(allocator_.Adapter()),
7334 overriding_default_conflict_methods_(allocator_.Adapter()),
7335 miranda_methods_(allocator_.Adapter()),
7336 default_methods_(allocator_.Adapter()),
7337 overriding_default_methods_(allocator_.Adapter()),
7338 move_table_(allocator_.Adapter()) {
7339 }
7340
7341 ArtMethod* FindMethod(ArtMethod* interface_method,
7342 MethodNameAndSignatureComparator& interface_name_comparator,
7343 ArtMethod* vtable_impl)
7344 REQUIRES_SHARED(Locks::mutator_lock_);
7345
7346 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7347 MethodNameAndSignatureComparator& interface_name_comparator)
7348 REQUIRES_SHARED(Locks::mutator_lock_);
7349
7350 bool HasNewVirtuals() const {
7351 return !(miranda_methods_.empty() &&
7352 default_methods_.empty() &&
7353 overriding_default_methods_.empty() &&
7354 overriding_default_conflict_methods_.empty() &&
7355 default_conflict_methods_.empty());
7356 }
7357
7358 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7359
7360 ObjPtr<mirror::PointerArray> UpdateVtable(
7361 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7362 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7363
7364 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7365
7366 void UpdateIMT(ArtMethod** out_imt);
7367
7368 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7369 if (kIsDebugBuild) {
7370 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7371 // Check that there are no stale methods are in the dex cache array.
7372 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7373 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007374 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7375 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007376 CHECK(move_table_.find(m) == move_table_.end() ||
7377 // The original versions of copied methods will still be present so allow those too.
7378 // Note that if the first check passes this might fail to GetDeclaringClass().
7379 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7380 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7381 [m] (ArtMethod& meth) {
7382 return &meth == m;
7383 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7384 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7385 }
7386 }
7387 }
7388
7389 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7390 LengthPrefixedArray<ArtMethod>* methods) {
7391 if (kIsDebugBuild) {
7392 CHECK(methods != nullptr);
7393 // Put some random garbage in old methods to help find stale pointers.
7394 if (methods != old_methods && old_methods != nullptr) {
7395 // Need to make sure the GC is not running since it could be scanning the methods we are
7396 // about to overwrite.
7397 ScopedThreadStateChange tsc(self_, kSuspended);
7398 gc::ScopedGCCriticalSection gcs(self_,
7399 gc::kGcCauseClassLinker,
7400 gc::kCollectorTypeClassLinker);
7401 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7402 method_size_,
7403 method_alignment_);
7404 memset(old_methods, 0xFEu, old_size);
7405 }
7406 }
7407 }
7408
7409 private:
7410 size_t NumberOfNewVirtuals() const {
7411 return miranda_methods_.size() +
7412 default_methods_.size() +
7413 overriding_default_conflict_methods_.size() +
7414 overriding_default_methods_.size() +
7415 default_conflict_methods_.size();
7416 }
7417
7418 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7419 return !klass_->IsInterface();
7420 }
7421
7422 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7423 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7424 << "Interfaces should only have default-conflict methods appended to them.";
7425 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7426 << miranda_methods_.size()
7427 << " default_methods=" << default_methods_.size()
7428 << " overriding_default_methods=" << overriding_default_methods_.size()
7429 << " default_conflict_methods=" << default_conflict_methods_.size()
7430 << " overriding_default_conflict_methods="
7431 << overriding_default_conflict_methods_.size();
7432 }
7433
7434 ClassLinker* class_linker_;
7435 Handle<mirror::Class> klass_;
7436 size_t method_alignment_;
7437 size_t method_size_;
7438 Thread* const self_;
7439
7440 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7441 // the virtual methods array.
7442 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7443 // during cross compilation.
7444 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7445 ArenaStack stack_;
7446 ScopedArenaAllocator allocator_;
7447
7448 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7449 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7450 ScopedArenaVector<ArtMethod*> miranda_methods_;
7451 ScopedArenaVector<ArtMethod*> default_methods_;
7452 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7453
7454 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7455};
7456
7457ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7458 ArtMethod* interface_method,
7459 MethodNameAndSignatureComparator& interface_name_comparator,
7460 ArtMethod* vtable_impl) {
7461 ArtMethod* current_method = nullptr;
7462 switch (class_linker_->FindDefaultMethodImplementation(self_,
7463 interface_method,
7464 klass_,
7465 /*out*/&current_method)) {
7466 case DefaultMethodSearchResult::kDefaultConflict: {
7467 // Default method conflict.
7468 DCHECK(current_method == nullptr);
7469 ArtMethod* default_conflict_method = nullptr;
7470 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7471 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7472 default_conflict_method = vtable_impl;
7473 } else {
7474 // See if we already have a conflict method for this method.
7475 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7476 interface_name_comparator,
7477 default_conflict_methods_,
7478 overriding_default_conflict_methods_);
7479 if (LIKELY(preexisting_conflict != nullptr)) {
7480 // We already have another conflict we can reuse.
7481 default_conflict_method = preexisting_conflict;
7482 } else {
7483 // Note that we do this even if we are an interface since we need to create this and
7484 // cannot reuse another classes.
7485 // Create a new conflict method for this to use.
7486 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7487 new(default_conflict_method) ArtMethod(interface_method,
7488 class_linker_->GetImagePointerSize());
7489 if (vtable_impl == nullptr) {
7490 // Save the conflict method. We need to add it to the vtable.
7491 default_conflict_methods_.push_back(default_conflict_method);
7492 } else {
7493 // Save the conflict method but it is already in the vtable.
7494 overriding_default_conflict_methods_.push_back(default_conflict_method);
7495 }
7496 }
7497 }
7498 current_method = default_conflict_method;
7499 break;
7500 } // case kDefaultConflict
7501 case DefaultMethodSearchResult::kDefaultFound: {
7502 DCHECK(current_method != nullptr);
7503 // Found a default method.
7504 if (vtable_impl != nullptr &&
7505 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7506 // We found a default method but it was the same one we already have from our
7507 // superclass. Don't bother adding it to our vtable again.
7508 current_method = vtable_impl;
7509 } else if (LIKELY(FillTables())) {
7510 // Interfaces don't need to copy default methods since they don't have vtables.
7511 // Only record this default method if it is new to save space.
7512 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7513 // would make lookup for interface super much faster. (We would only need to scan
7514 // the iftable to find if there is a NSME or AME.)
7515 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7516 default_methods_,
7517 overriding_default_methods_);
7518 if (old == nullptr) {
7519 // We found a default method implementation and there were no conflicts.
7520 if (vtable_impl == nullptr) {
7521 // Save the default method. We need to add it to the vtable.
7522 default_methods_.push_back(current_method);
7523 } else {
7524 // Save the default method but it is already in the vtable.
7525 overriding_default_methods_.push_back(current_method);
7526 }
7527 } else {
7528 CHECK(old == current_method) << "Multiple default implementations selected!";
7529 }
7530 }
7531 break;
7532 } // case kDefaultFound
7533 case DefaultMethodSearchResult::kAbstractFound: {
7534 DCHECK(current_method == nullptr);
7535 // Abstract method masks all defaults.
7536 if (vtable_impl != nullptr &&
7537 vtable_impl->IsAbstract() &&
7538 !vtable_impl->IsDefaultConflicting()) {
7539 // We need to make this an abstract method but the version in the vtable already is so
7540 // don't do anything.
7541 current_method = vtable_impl;
7542 }
7543 break;
7544 } // case kAbstractFound
7545 }
7546 return current_method;
7547}
7548
7549ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7550 ArtMethod* interface_method,
7551 MethodNameAndSignatureComparator& interface_name_comparator) {
7552 // Find out if there is already a miranda method we can use.
7553 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7554 miranda_methods_);
7555 if (miranda_method == nullptr) {
7556 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7557 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7558 CHECK(miranda_method != nullptr);
7559 // Point the interface table at a phantom slot.
7560 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7561 miranda_methods_.push_back(miranda_method);
7562 }
7563 return miranda_method;
7564}
7565
7566void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7567 LogNewVirtuals();
7568
7569 const size_t old_method_count = klass_->NumMethods();
7570 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7571 DCHECK_NE(old_method_count, new_method_count);
7572
7573 // Attempt to realloc to save RAM if possible.
7574 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7575 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7576 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7577 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7578 // CopyFrom has internal read barriers.
7579 //
7580 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7581 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7582 method_size_,
7583 method_alignment_);
7584 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7585 method_size_,
7586 method_alignment_);
7587 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7588 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007589 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007590 self_, old_methods, old_methods_ptr_size, new_size));
7591 CHECK(methods != nullptr); // Native allocation failure aborts.
7592
7593 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7594 if (methods != old_methods) {
7595 // Maps from heap allocated miranda method to linear alloc miranda method.
7596 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7597 // Copy over the old methods.
7598 for (auto& m : klass_->GetMethods(pointer_size)) {
7599 move_table_.emplace(&m, &*out);
7600 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7601 // barriers when it copies.
7602 out->CopyFrom(&m, pointer_size);
7603 ++out;
7604 }
7605 }
7606 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7607 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7608 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007609 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7610 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007611 ArtMethod& new_method = *out;
7612 new_method.CopyFrom(mir_method, pointer_size);
7613 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7614 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7615 << "Miranda method should be abstract!";
7616 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007617 // Update the entry in the method array, as the array will be used for future lookups,
7618 // where thread suspension is allowed.
7619 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7620 // would not see them.
7621 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007622 ++out;
7623 }
7624 // We need to copy the default methods into our own method table since the runtime requires that
7625 // every method on a class's vtable be in that respective class's virtual method table.
7626 // NOTE This means that two classes might have the same implementation of a method from the same
7627 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7628 // default method found on a class with one found on the declaring interface directly and must
7629 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007630 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7631 &overriding_default_methods_}) {
7632 for (size_t i = 0; i < methods_vec->size(); ++i) {
7633 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007634 ArtMethod& new_method = *out;
7635 new_method.CopyFrom(def_method, pointer_size);
7636 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7637 // verified yet it shouldn't have methods that are skipping access checks.
7638 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7639 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007640 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007641 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7642 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7643 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7644 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007645 // Update the entry in the method array, as the array will be used for future lookups,
7646 // where thread suspension is allowed.
7647 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7648 // would not see them.
7649 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007650 ++out;
7651 }
7652 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007653 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7654 &overriding_default_conflict_methods_}) {
7655 for (size_t i = 0; i < methods_vec->size(); ++i) {
7656 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007657 ArtMethod& new_method = *out;
7658 new_method.CopyFrom(conf_method, pointer_size);
7659 // This is a type of default method (there are default method impls, just a conflict) so
7660 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7661 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7662 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007663 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7664 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007665 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007666 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007667 constexpr uint32_t kMaskFlags =
7668 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007669 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7670 DCHECK(new_method.IsDefaultConflicting());
7671 // The actual method might or might not be marked abstract since we just copied it from a
7672 // (possibly default) interface method. We need to set it entry point to be the bridge so
7673 // that the compiler will not invoke the implementation of whatever method we copied from.
7674 EnsureThrowsInvocationError(class_linker_, &new_method);
7675 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007676 // Update the entry in the method array, as the array will be used for future lookups,
7677 // where thread suspension is allowed.
7678 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7679 // would not see them.
7680 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007681 ++out;
7682 }
7683 }
7684 methods->SetSize(new_method_count);
7685 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7686}
7687
7688ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7689 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7690 ObjPtr<mirror::PointerArray> old_vtable) {
7691 // Update the vtable to the new method structures. We can skip this for interfaces since they
7692 // do not have vtables.
7693 const size_t old_vtable_count = old_vtable->GetLength();
7694 const size_t new_vtable_count = old_vtable_count +
7695 miranda_methods_.size() +
7696 default_methods_.size() +
7697 default_conflict_methods_.size();
7698
7699 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007700 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007701 if (UNLIKELY(vtable == nullptr)) {
7702 self_->AssertPendingOOMException();
7703 return nullptr;
7704 }
7705
7706 size_t vtable_pos = old_vtable_count;
7707 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7708 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7709 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7710 default_conflict_methods_,
7711 miranda_methods_}) {
7712 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007713 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007714 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7715 // fields are references into the dex file the method was defined in. Since the ArtMethod
7716 // does not store that information it uses declaring_class_->dex_cache_.
7717 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7718 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7719 ++vtable_pos;
7720 }
7721 }
7722 DCHECK_EQ(vtable_pos, new_vtable_count);
7723
7724 // Update old vtable methods. We use the default_translations map to figure out what each
7725 // vtable entry should be updated to, if they need to be at all.
7726 for (size_t i = 0; i < old_vtable_count; ++i) {
7727 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7728 // Try and find what we need to change this method to.
7729 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007730 if (translation_it != default_translations.end()) {
7731 if (translation_it->second.IsInConflict()) {
7732 // Find which conflict method we are to use for this method.
7733 MethodNameAndSignatureComparator old_method_comparator(
7734 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7735 // We only need to look through overriding_default_conflict_methods since this is an
7736 // overridden method we are fixing up here.
7737 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7738 old_method_comparator, overriding_default_conflict_methods_);
7739 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7740 translated_method = new_conflict_method;
7741 } else if (translation_it->second.IsAbstract()) {
7742 // Find which miranda method we are to use for this method.
7743 MethodNameAndSignatureComparator old_method_comparator(
7744 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7745 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7746 miranda_methods_);
7747 DCHECK(miranda_method != nullptr);
7748 translated_method = miranda_method;
7749 } else {
7750 // Normal default method (changed from an older default or abstract interface method).
7751 DCHECK(translation_it->second.IsTranslation());
7752 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007753 auto it = move_table_.find(translated_method);
7754 DCHECK(it != move_table_.end());
7755 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007756 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007757 } else {
7758 auto it = move_table_.find(translated_method);
7759 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007760 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007761
7762 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007763 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007764 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007765 if (kIsDebugBuild) {
7766 auto* methods = klass_->GetMethodsPtr();
7767 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007768 reinterpret_cast<uintptr_t>(translated_method));
7769 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007770 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7771 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007772 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007773 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007774 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007775 }
7776 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007777 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007778 return vtable;
7779}
7780
7781void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7782 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7783 const size_t ifcount = klass_->GetIfTableCount();
7784 // Go fix up all the stale iftable pointers.
7785 for (size_t i = 0; i < ifcount; ++i) {
7786 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007787 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7788 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007789 DCHECK(m != nullptr) << klass_->PrettyClass();
7790 auto it = move_table_.find(m);
7791 if (it != move_table_.end()) {
7792 auto* new_m = it->second;
7793 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7794 method_array->SetElementPtrSize(j, new_m, pointer_size);
7795 }
7796 }
7797 }
7798}
7799
7800void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7801 // Fix up IMT next.
7802 for (size_t i = 0; i < ImTable::kSize; ++i) {
7803 auto it = move_table_.find(out_imt[i]);
7804 if (it != move_table_.end()) {
7805 out_imt[i] = it->second;
7806 }
7807 }
7808}
7809
Alex Light705ad492015-09-21 11:36:30 -07007810// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007811bool ClassLinker::LinkInterfaceMethods(
7812 Thread* self,
7813 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007814 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007815 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007816 ArtMethod** out_imt) {
7817 StackHandleScope<3> hs(self);
7818 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007819
7820 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007821 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007822 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007823 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007824 const size_t ifcount = klass->GetIfTableCount();
7825
Vladimir Marko921094a2017-01-12 18:37:06 +00007826 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007827
7828 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7829 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007830 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007831 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007832 const bool extend_super_iftable = has_superclass;
7833 if (has_superclass && fill_tables) {
7834 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007835 unimplemented_method,
7836 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007837 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007838 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007839 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007840 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7841 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007842 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007843 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7844 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007845 }
7846 }
7847
Vladimir Marko921094a2017-01-12 18:37:06 +00007848 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7849
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007850 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007851 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007852 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7853 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7854 // they will already be null. This has the additional benefit that the declarer of a miranda
7855 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007856 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007857 --i;
Alex Light9139e002015-10-09 15:59:48 -07007858 DCHECK_LT(i, ifcount);
7859
Alex Light705ad492015-09-21 11:36:30 -07007860 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007861 if (num_methods > 0) {
7862 StackHandleScope<2> hs2(self);
7863 const bool is_super = i < super_ifcount;
7864 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007865 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7866 // conflict methods. Just set this as nullptr in those cases.
7867 Handle<mirror::PointerArray> method_array(fill_tables
7868 ? hs2.NewHandle(iftable->GetMethodArray(i))
7869 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007870
Alex Lighte64300b2015-12-15 15:02:47 -08007871 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007872 ScopedNullHandle<mirror::PointerArray> null_handle;
7873 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007874 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007875
Alex Light9139e002015-10-09 15:59:48 -07007876 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7877 // and confusing. Default methods should always look through all the superclasses
7878 // because they are the last choice of an implementation. We get around this by looking
7879 // at the super-classes iftable methods (copied into method_array previously) when we are
7880 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007881 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007882 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007883 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007884 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007885 using_virtuals = true;
7886 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7887 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007888 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007889 // For a new interface, however, we need the whole vtable in case a new
7890 // interface method is implemented in the whole superclass.
7891 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007892 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007893 input_vtable_array = vtable;
7894 input_array_length = input_vtable_array->GetLength();
7895 }
Alex Lighte64300b2015-12-15 15:02:47 -08007896
Alex Lighteb7c1442015-08-31 13:17:42 -07007897 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007898 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007899 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007900 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007901 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007902 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007903 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007904 // For each method listed in the interface's method list, find the
7905 // matching method in our class's method list. We want to favor the
7906 // subclass over the superclass, which just requires walking
7907 // back from the end of the vtable. (This only matters if the
7908 // superclass defines a private method and this class redefines
7909 // it -- otherwise it would use the same vtable slot. In .dex files
7910 // those don't end up in the virtual method table, so it shouldn't
7911 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007912 //
7913 // To find defaults we need to do the same but also go over interfaces.
7914 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007915 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007916 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007917 ArtMethod* vtable_method = using_virtuals ?
7918 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007919 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7920 ArtMethod* vtable_method_for_name_comparison =
7921 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007922 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007923 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007924 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007925 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7926 // allocations.
7927 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007928 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007929 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007930 vtable_method->PrettyMethod().c_str(),
7931 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007932 return false;
Alex Light9139e002015-10-09 15:59:48 -07007933 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007934 // We might have a newer, better, default method for this, so we just skip it. If we
7935 // are still using this we will select it again when scanning for default methods. To
7936 // obviate the need to copy the method again we will make a note that we already found
7937 // a default here.
7938 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007939 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007940 break;
7941 } else {
7942 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007943 if (LIKELY(fill_tables)) {
7944 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7945 // Place method in imt if entry is empty, place conflict otherwise.
7946 SetIMTRef(unimplemented_method,
7947 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007948 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007949 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007950 /*out*/imt_ptr);
7951 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007952 break;
7953 }
7954 }
Alex Light9139e002015-10-09 15:59:48 -07007955 }
7956 // Continue on to the next method if we are done.
7957 if (LIKELY(found_impl)) {
7958 continue;
7959 } else if (LIKELY(super_interface)) {
7960 // Don't look for a default implementation when the super-method is implemented directly
7961 // by the class.
7962 //
7963 // See if we can use the superclasses method and skip searching everything else.
7964 // Note: !found_impl && super_interface
7965 CHECK(extend_super_iftable);
7966 // If this is a super_interface method it is possible we shouldn't override it because a
7967 // superclass could have implemented it directly. We get the method the superclass used
7968 // to implement this to know if we can override it with a default method. Doing this is
7969 // safe since we know that the super_iftable is filled in so we can simply pull it from
7970 // there. We don't bother if this is not a super-classes interface since in that case we
7971 // have scanned the entire vtable anyway and would have found it.
7972 // TODO This is rather dirty but it is faster than searching through the entire vtable
7973 // every time.
7974 ArtMethod* supers_method =
7975 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7976 DCHECK(supers_method != nullptr);
7977 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007978 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007979 // The method is not overridable by a default method (i.e. it is directly implemented
7980 // in some class). Therefore move onto the next interface method.
7981 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007982 } else {
7983 // If the super-classes method is override-able by a default method we need to keep
7984 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7985 // 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 -07007986 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7987 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7988 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007989 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007990 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7991 << " and not 'nullptr' or "
7992 << supers_method->PrettyMethod()
7993 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007994 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007995 }
7996 }
7997 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007998 ArtMethod* current_method = helper.FindMethod(interface_method,
7999 interface_name_comparator,
8000 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008001 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008002 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008003 // We could not find an implementation for this method and since it is a brand new
8004 // interface we searched the entire vtable (and all default methods) for an
8005 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008006 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8007 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008008 }
8009
8010 if (current_method != nullptr) {
8011 // We found a default method implementation. Record it in the iftable and IMT.
8012 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8013 SetIMTRef(unimplemented_method,
8014 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008015 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008016 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008017 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008018 }
8019 }
Alex Light705ad492015-09-21 11:36:30 -07008020 } // For each method in interface end.
8021 } // if (num_methods > 0)
8022 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008023 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008024 if (helper.HasNewVirtuals()) {
8025 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8026 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8027 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8028
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008029 // 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 -07008030 // suspension assert.
8031 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008032
Alex Light705ad492015-09-21 11:36:30 -07008033 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008034 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008035 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008036 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008037 return false;
8038 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008039 helper.UpdateIfTable(iftable);
8040 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008041 }
Alex Light705ad492015-09-21 11:36:30 -07008042
Vladimir Marko921094a2017-01-12 18:37:06 +00008043 helper.CheckNoStaleMethodsInDexCache();
8044 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008045 } else {
8046 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008047 }
Alex Light705ad492015-09-21 11:36:30 -07008048 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008049 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008050 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008051 return true;
8052}
8053
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008054bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008055 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008056 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008057}
8058
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008059bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008060 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008061 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008062}
8063
Brian Carlstromdbc05252011-09-09 01:59:59 -07008064struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008065 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008066 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008067 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008068 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008069 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008070 // 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 -07008071 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8072 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008073 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008074 if (type1 == Primitive::kPrimNot) {
8075 // Reference always goes first.
8076 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008077 }
Vladimir Markod5777482014-11-12 17:02:02 +00008078 if (type2 == Primitive::kPrimNot) {
8079 // Reference always goes first.
8080 return false;
8081 }
8082 size_t size1 = Primitive::ComponentSize(type1);
8083 size_t size2 = Primitive::ComponentSize(type2);
8084 if (size1 != size2) {
8085 // Larger primitive types go first.
8086 return size1 > size2;
8087 }
8088 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8089 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008090 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008091 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8092 // by name and for equal names by type id index.
8093 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8094 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008095 }
8096};
8097
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008098bool ClassLinker::LinkFields(Thread* self,
8099 Handle<mirror::Class> klass,
8100 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008101 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008102 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008103 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008104 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8105 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008106
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008107 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008108 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008109 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008110 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008111 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008112 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008113 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008114 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008115 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008116 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008117 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008118 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008119
David Sehr709b0702016-10-13 09:12:37 -07008120 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008121
Brian Carlstromdbc05252011-09-09 01:59:59 -07008122 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008123 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008124 //
8125 // The overall sort order order is:
8126 // 1) All object reference fields, sorted alphabetically.
8127 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8128 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8129 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8130 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8131 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8132 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8133 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8134 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8135 //
8136 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8137 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008138 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008139 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008140 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008141 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008142 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008143 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008144 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8145 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008146
Fred Shih381e4ca2014-08-25 17:24:27 -07008147 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008148 size_t current_field = 0;
8149 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008150 FieldGaps gaps;
8151
Brian Carlstromdbc05252011-09-09 01:59:59 -07008152 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008153 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008154 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008155 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008156 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008157 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008158 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008159 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8160 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008161 MemberOffset old_offset = field_offset;
8162 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8163 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8164 }
Roland Levillain14d90572015-07-16 10:52:26 +01008165 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008166 grouped_and_sorted_fields.pop_front();
8167 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008168 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008169 field_offset = MemberOffset(field_offset.Uint32Value() +
8170 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008171 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008172 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8173 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008174 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8175 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8176 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8177 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008178 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8179 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008180 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008181
Elliott Hughesadb460d2011-10-05 17:02:34 -07008182 // 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 -07008183 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008184 // We know there are no non-reference fields in the Reference classes, and we know
8185 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008186 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008187 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008188 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008189 --num_reference_fields;
8190 }
8191
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008192 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008193 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008194 if (is_static) {
8195 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008196 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008197 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008198 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008199 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008200 if (num_reference_fields == 0 || super_class == nullptr) {
8201 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008202 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008203 if (super_class == nullptr ||
8204 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8205 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008206 }
8207 }
8208 if (kIsDebugBuild) {
8209 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8210 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008211 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008212 while (cur_super != nullptr) {
8213 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8214 cur_super = cur_super->GetSuperClass();
8215 }
8216 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008217 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008218 } else {
8219 // Check that there is at least num_reference_fields other than Object.class.
8220 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008221 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008222 }
8223 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008224 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008225 std::string temp;
8226 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8227 size_t previous_size = klass->GetObjectSize();
8228 if (previous_size != 0) {
8229 // Make sure that we didn't originally have an incorrect size.
8230 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008231 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008232 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008233 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008234 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008235
8236 if (kIsDebugBuild) {
8237 // Make sure that the fields array is ordered by name but all reference
8238 // offsets are at the beginning as far as alignment allows.
8239 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008240 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008241 : klass->GetFirstReferenceInstanceFieldOffset();
8242 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8243 num_reference_fields *
8244 sizeof(mirror::HeapReference<mirror::Object>));
8245 MemberOffset current_ref_offset = start_ref_offset;
8246 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008247 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008248 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008249 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8250 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008251 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008252 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008253 // NOTE: The field names can be the same. This is not possible in the Java language
8254 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008255 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008256 }
8257 Primitive::Type type = field->GetTypeAsPrimitiveType();
8258 bool is_primitive = type != Primitive::kPrimNot;
8259 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8260 strcmp("referent", field->GetName()) == 0) {
8261 is_primitive = true; // We lied above, so we have to expect a lie here.
8262 }
8263 MemberOffset offset = field->GetOffsetDuringLinking();
8264 if (is_primitive) {
8265 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8266 // Shuffled before references.
8267 size_t type_size = Primitive::ComponentSize(type);
8268 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8269 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8270 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8271 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8272 }
8273 } else {
8274 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8275 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8276 sizeof(mirror::HeapReference<mirror::Object>));
8277 }
8278 }
8279 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8280 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008281 return true;
8282}
8283
Vladimir Marko76649e82014-11-10 18:32:59 +00008284// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008285void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008286 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008287 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008288 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008289 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008290 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008291 // Compute reference offsets unless our superclass overflowed.
8292 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8293 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008294 if (num_reference_fields != 0u) {
8295 // All of the fields that contain object references are guaranteed be grouped in memory
8296 // starting at an appropriately aligned address after super class object data.
8297 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8298 sizeof(mirror::HeapReference<mirror::Object>));
8299 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008300 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008301 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008302 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008303 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008304 reference_offsets |= (0xffffffffu << start_bit) &
8305 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008306 }
8307 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008308 }
8309 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008310 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008311}
8312
Vladimir Marko18090d12018-06-01 16:53:12 +01008313ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8314 ObjPtr<mirror::DexCache> dex_cache) {
8315 StackHandleScope<1> hs(Thread::Current());
8316 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8317 return DoResolveString(string_idx, h_dex_cache);
8318}
8319
8320ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8321 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008322 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008323 uint32_t utf16_length;
8324 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008325 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008326 if (string != nullptr) {
8327 dex_cache->SetResolvedString(string_idx, string);
8328 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008329 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008330}
8331
Vladimir Marko18090d12018-06-01 16:53:12 +01008332ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8333 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008334 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008335 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008336 uint32_t utf16_length;
8337 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008338 ObjPtr<mirror::String> string =
8339 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008340 if (string != nullptr) {
8341 dex_cache->SetResolvedString(string_idx, string);
8342 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008343 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008344}
8345
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008346ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008347 ObjPtr<mirror::Class> referrer) {
8348 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8349}
8350
8351ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008352 ObjPtr<mirror::DexCache> dex_cache,
8353 ObjPtr<mirror::ClassLoader> class_loader) {
8354 const DexFile& dex_file = *dex_cache->GetDexFile();
8355 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8356 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8357 ObjPtr<mirror::Class> type = nullptr;
8358 if (descriptor[1] == '\0') {
8359 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8360 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008361 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008362 } else {
8363 Thread* const self = Thread::Current();
8364 DCHECK(self != nullptr);
8365 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8366 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008367 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008368 }
8369 if (type != nullptr) {
8370 if (type->IsResolved()) {
8371 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008372 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008373 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008374 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008375 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008376 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008377}
8378
Andreas Gampe4835d212018-11-21 14:55:10 -08008379template <typename T>
8380ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008381 StackHandleScope<2> hs(Thread::Current());
8382 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8383 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8384 return DoResolveType(type_idx, dex_cache, class_loader);
8385}
8386
Andreas Gampe4835d212018-11-21 14:55:10 -08008387// Instantiate the above.
8388template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8389 ArtField* referrer);
8390template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8391 ArtMethod* referrer);
8392template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8393 ObjPtr<mirror::Class> referrer);
8394
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008395ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008396 Handle<mirror::DexCache> dex_cache,
8397 Handle<mirror::ClassLoader> class_loader) {
8398 Thread* self = Thread::Current();
8399 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8400 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8401 if (resolved != nullptr) {
8402 // TODO: we used to throw here if resolved's class loader was not the
8403 // boot class loader. This was to permit different classes with the
8404 // same name to be loaded simultaneously by different loaders
8405 dex_cache->SetResolvedType(type_idx, resolved);
8406 } else {
8407 CHECK(self->IsExceptionPending())
8408 << "Expected pending exception for failed resolution of: " << descriptor;
8409 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8410 StackHandleScope<1> hs(self);
8411 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008412 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008413 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8414 self->ClearException();
8415 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8416 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008417 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008418 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008419 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008420 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008421 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008422}
8423
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008424ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8425 ObjPtr<mirror::DexCache> dex_cache,
8426 ObjPtr<mirror::ClassLoader> class_loader,
8427 uint32_t method_idx) {
8428 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8429 // functions can optimize the search if the dex_cache is the same as the DexCache
8430 // of the class, with fall-back to name and signature search otherwise.
8431 ArtMethod* resolved = nullptr;
8432 if (klass->IsInterface()) {
8433 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8434 } else {
8435 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8436 }
8437 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008438 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008439 hiddenapi::ShouldDenyAccessToMember(resolved,
8440 hiddenapi::AccessContext(class_loader, dex_cache),
8441 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008442 resolved = nullptr;
8443 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008444 if (resolved != nullptr) {
8445 // In case of jmvti, the dex file gets verified before being registered, so first
8446 // check if it's registered before checking class tables.
8447 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008448 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8449 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008450 << "DexFile referrer: " << dex_file.GetLocation()
8451 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8452 // Be a good citizen and update the dex cache to speed subsequent calls.
8453 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008454 // Disable the following invariant check as the verifier breaks it. b/73760543
8455 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8456 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8457 // << "Method: " << resolved->PrettyMethod() << ", "
8458 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8459 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008460 }
8461 return resolved;
8462}
8463
David Brazdil4525e0b2018-04-05 16:57:32 +01008464// Returns true if `method` is either null or hidden.
8465// Does not print any warnings if it is hidden.
8466static bool CheckNoSuchMethod(ArtMethod* method,
8467 ObjPtr<mirror::DexCache> dex_cache,
8468 ObjPtr<mirror::ClassLoader> class_loader)
8469 REQUIRES_SHARED(Locks::mutator_lock_) {
8470 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008471 hiddenapi::ShouldDenyAccessToMember(method,
8472 hiddenapi::AccessContext(class_loader, dex_cache),
8473 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008474}
8475
8476ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8477 ObjPtr<mirror::DexCache> dex_cache,
8478 ObjPtr<mirror::ClassLoader> class_loader,
8479 uint32_t method_idx) {
8480 if (klass->IsInterface()) {
8481 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8482 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8483 } else {
8484 // If there was an interface method with the same signature, we would have
8485 // found it in the "copied" methods. Only DCHECK that the interface method
8486 // really does not exist.
8487 if (kIsDebugBuild) {
8488 ArtMethod* method =
8489 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8490 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8491 }
8492 return nullptr;
8493 }
8494}
8495
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008496template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008497ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008498 Handle<mirror::DexCache> dex_cache,
8499 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008500 ArtMethod* referrer,
8501 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008502 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008503 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008504 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008505 PointerSize pointer_size = image_pointer_size_;
8506 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008507 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008508 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8509 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008510 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8511 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008512 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008513 return resolved;
8514 }
Vladimir Marko89011192017-12-11 13:45:05 +00008515 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008516 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008517 ObjPtr<mirror::Class> klass = nullptr;
8518 if (valid_dex_cache_method) {
8519 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8520 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008521 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008522 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008523 // We normaly should not end up here. However the verifier currently doesn't guarantee
8524 // the invariant of having the klass in the class table. b/73760543
8525 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008526 }
Vladimir Markoba118822017-06-12 15:41:56 +01008527 } else {
8528 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008529 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008530 if (klass == nullptr) {
8531 DCHECK(Thread::Current()->IsExceptionPending());
8532 return nullptr;
8533 }
8534 }
8535
8536 // Check if the invoke type matches the class type.
8537 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008538 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008539 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008540 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008541 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008542 }
Vladimir Markoba118822017-06-12 15:41:56 +01008543
8544 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008545 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008546 }
Vladimir Markoba118822017-06-12 15:41:56 +01008547
8548 // Note: We can check for IllegalAccessError only if we have a referrer.
8549 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8550 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8551 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8552 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8553 resolved,
8554 dex_cache.Get(),
8555 method_idx,
8556 type)) {
8557 DCHECK(Thread::Current()->IsExceptionPending());
8558 return nullptr;
8559 }
8560 }
8561
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008562 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008563 if (LIKELY(resolved != nullptr) &&
8564 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8565 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008566 return resolved;
8567 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008568 // If we had a method, or if we can find one with another lookup type,
8569 // it's an incompatible-class-change error.
8570 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008571 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008572 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008573 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008574 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008575 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008576 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008577 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8578 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008579 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008580 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008581 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008582 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008584}
8585
Vladimir Marko89011192017-12-11 13:45:05 +00008586ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008587 Handle<mirror::DexCache> dex_cache,
8588 Handle<mirror::ClassLoader> class_loader) {
8589 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008590 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008591 if (resolved != nullptr) {
8592 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008593 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8594 return resolved;
8595 }
8596 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008597 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008598 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008599 if (klass == nullptr) {
8600 Thread::Current()->AssertPendingException();
8601 return nullptr;
8602 }
8603 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008604 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8605 } else {
8606 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008607 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008608 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008609 hiddenapi::ShouldDenyAccessToMember(
8610 resolved,
8611 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8612 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008613 resolved = nullptr;
8614 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008615 return resolved;
8616}
8617
Vladimir Markof44d36c2017-03-14 14:18:46 +00008618ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8619 ObjPtr<mirror::DexCache> dex_cache,
8620 ObjPtr<mirror::ClassLoader> class_loader,
8621 bool is_static) {
8622 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008623 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008624 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8625 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008626 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008627 }
8628 if (klass == nullptr) {
8629 // The class has not been resolved yet, so the field is also unresolved.
8630 return nullptr;
8631 }
8632 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008633
David Brazdil1ab0fa82018-05-04 11:28:03 +01008634 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008635}
8636
Vladimir Markoe11dd502017-12-08 14:09:45 +00008637ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008638 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008639 Handle<mirror::ClassLoader> class_loader,
8640 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008641 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008642 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008643 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008644 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008645 return resolved;
8646 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008647 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008648 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008649 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008650 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008651 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008652 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008653 }
8654
David Brazdil1ab0fa82018-05-04 11:28:03 +01008655 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008656 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008657 const char* name = dex_file.GetFieldName(field_id);
8658 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008659 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008660 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008661 return resolved;
8662}
8663
Vladimir Markoe11dd502017-12-08 14:09:45 +00008664ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008665 Handle<mirror::DexCache> dex_cache,
8666 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008667 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008668 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008669 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008670 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008671 return resolved;
8672 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008673 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008674 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008675 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008676 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008677 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008678 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008679 }
8680
David Brazdil1ab0fa82018-05-04 11:28:03 +01008681 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8682 if (resolved == nullptr) {
8683 const char* name = dex_file.GetFieldName(field_id);
8684 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008685 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008686 }
8687 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008688}
8689
David Brazdil1ab0fa82018-05-04 11:28:03 +01008690ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8691 ObjPtr<mirror::DexCache> dex_cache,
8692 ObjPtr<mirror::ClassLoader> class_loader,
8693 uint32_t field_idx,
8694 bool is_static) {
8695 ArtField* resolved = nullptr;
8696 Thread* self = is_static ? Thread::Current() : nullptr;
8697 const DexFile& dex_file = *dex_cache->GetDexFile();
8698
8699 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8700 : klass->FindInstanceField(dex_cache, field_idx);
8701
8702 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008703 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008704 const char* name = dex_file.GetFieldName(field_id);
8705 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8706 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8707 : klass->FindInstanceField(name, type);
8708 }
8709
8710 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008711 hiddenapi::ShouldDenyAccessToMember(resolved,
8712 hiddenapi::AccessContext(class_loader, dex_cache),
8713 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008714 resolved = nullptr;
8715 }
8716
8717 if (resolved != nullptr) {
8718 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8719 }
8720
8721 return resolved;
8722}
8723
8724ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8725 ObjPtr<mirror::DexCache> dex_cache,
8726 ObjPtr<mirror::ClassLoader> class_loader,
8727 uint32_t field_idx) {
8728 ArtField* resolved = nullptr;
8729 Thread* self = Thread::Current();
8730 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008731 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008732
8733 const char* name = dex_file.GetFieldName(field_id);
8734 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8735 resolved = mirror::Class::FindField(self, klass, name, type);
8736
8737 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008738 hiddenapi::ShouldDenyAccessToMember(resolved,
8739 hiddenapi::AccessContext(class_loader, dex_cache),
8740 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008741 resolved = nullptr;
8742 }
8743
8744 if (resolved != nullptr) {
8745 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8746 }
8747
8748 return resolved;
8749}
8750
Vladimir Markoaf940202017-12-08 15:01:18 +00008751ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8752 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008753 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008754 Handle<mirror::DexCache> dex_cache,
8755 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008756 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008757 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008758
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008759 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008760 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008761 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008762 }
8763
Narayan Kamath25352fc2016-08-03 12:46:58 +01008764 StackHandleScope<4> hs(self);
8765
8766 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008767 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008768 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008769 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008770 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008771 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008772 DCHECK(self->IsExceptionPending());
8773 return nullptr;
8774 }
8775
8776 // Then resolve the argument types.
8777 //
8778 // TODO: Is there a better way to figure out the number of method arguments
8779 // other than by looking at the shorty ?
8780 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8781
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008782 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008783 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8784 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008785 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008786 DCHECK(self->IsExceptionPending());
8787 return nullptr;
8788 }
8789
8790 DexFileParameterIterator it(dex_file, proto_id);
8791 int32_t i = 0;
8792 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8793 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008794 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008795 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008796 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008797 DCHECK(self->IsExceptionPending());
8798 return nullptr;
8799 }
8800
8801 method_params->Set(i++, param_class.Get());
8802 }
8803
8804 DCHECK(!it.HasNext());
8805
8806 Handle<mirror::MethodType> type = hs.NewHandle(
8807 mirror::MethodType::Create(self, return_type, method_params));
8808 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8809
8810 return type.Get();
8811}
8812
Vladimir Markoaf940202017-12-08 15:01:18 +00008813ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008814 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008815 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008816 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008817 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8818 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008819 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008820}
8821
Vladimir Marko5aead702019-03-27 11:00:36 +00008822ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008823 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008824 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008825 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008826 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008827 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8828 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008829 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008830 bool is_static;
8831 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008832 switch (handle_type) {
8833 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008834 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008835 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008836 is_static = true;
8837 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008838 break;
8839 }
8840 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008841 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008842 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008843 is_static = true;
8844 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008845 break;
8846 }
8847 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008848 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008849 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008850 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008851 num_params = 2;
8852 break;
8853 }
8854 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008855 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008856 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008857 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008858 num_params = 1;
8859 break;
8860 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008861 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008862 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008863 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008864 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008865 case DexFile::MethodHandleType::kInvokeInterface:
8866 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008867 }
8868
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008869 ArtField* target_field =
8870 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8871 if (LIKELY(target_field != nullptr)) {
8872 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8873 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8874 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8875 ThrowIllegalAccessErrorField(referring_class, target_field);
8876 return nullptr;
8877 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008878 if (UNLIKELY(is_put && target_field->IsFinal())) {
8879 ThrowIllegalAccessErrorField(referring_class, target_field);
8880 return nullptr;
8881 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008882 } else {
8883 DCHECK(Thread::Current()->IsExceptionPending());
8884 return nullptr;
8885 }
8886
8887 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008888 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008889 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8890 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008891 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008892 DCHECK(self->IsExceptionPending());
8893 return nullptr;
8894 }
8895
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008896 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008897 Handle<mirror::Class> return_type;
8898 switch (handle_type) {
8899 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008900 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008901 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008902 break;
8903 }
8904 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008905 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008906 break;
8907 }
8908 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008909 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008910 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008911 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008912 break;
8913 }
8914 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008915 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008916 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008917 break;
8918 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008919 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008920 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008921 case DexFile::MethodHandleType::kInvokeConstructor:
8922 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008923 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008924 UNREACHABLE();
8925 }
8926
8927 for (int32_t i = 0; i < num_params; ++i) {
8928 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8929 DCHECK(self->IsExceptionPending());
8930 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008931 }
8932 }
8933
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008934 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008935 DCHECK(self->IsExceptionPending());
8936 return nullptr;
8937 }
8938
8939 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008940 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8941 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008942 DCHECK(self->IsExceptionPending());
8943 return nullptr;
8944 }
Orion Hodson631827d2017-04-10 14:53:47 +01008945
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008946 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8947 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8948}
8949
Vladimir Marko5aead702019-03-27 11:00:36 +00008950ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008951 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008952 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008953 ArtMethod* referrer) {
8954 DexFile::MethodHandleType handle_type =
8955 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8956 mirror::MethodHandle::Kind kind;
8957 uint32_t receiver_count = 0;
8958 ArtMethod* target_method = nullptr;
8959 switch (handle_type) {
8960 case DexFile::MethodHandleType::kStaticPut:
8961 case DexFile::MethodHandleType::kStaticGet:
8962 case DexFile::MethodHandleType::kInstancePut:
8963 case DexFile::MethodHandleType::kInstanceGet:
8964 UNREACHABLE();
8965 case DexFile::MethodHandleType::kInvokeStatic: {
8966 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8967 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008968 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8969 method_handle.field_or_method_idx_,
8970 referrer,
8971 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008972 break;
8973 }
8974 case DexFile::MethodHandleType::kInvokeInstance: {
8975 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8976 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008977 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8978 method_handle.field_or_method_idx_,
8979 referrer,
8980 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008981 break;
8982 }
8983 case DexFile::MethodHandleType::kInvokeConstructor: {
8984 // Constructors are currently implemented as a transform. They
8985 // are special cased later in this method.
8986 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8987 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008988 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8989 method_handle.field_or_method_idx_,
8990 referrer,
8991 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008992 break;
8993 }
8994 case DexFile::MethodHandleType::kInvokeDirect: {
8995 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8996 receiver_count = 1;
8997 StackHandleScope<2> hs(self);
8998 // A constant method handle with type kInvokeDirect can refer to
8999 // a method that is private or to a method in a super class. To
9000 // disambiguate the two options, we resolve the method ignoring
9001 // the invocation type to determine if the method is private. We
9002 // then resolve again specifying the intended invocation type to
9003 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009004 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009005 hs.NewHandle(referrer->GetDexCache()),
9006 hs.NewHandle(referrer->GetClassLoader()));
9007 if (UNLIKELY(target_method == nullptr)) {
9008 break;
9009 }
9010
9011 if (target_method->IsPrivate()) {
9012 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009013 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9014 method_handle.field_or_method_idx_,
9015 referrer,
9016 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009017 } else {
9018 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009019 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9020 method_handle.field_or_method_idx_,
9021 referrer,
9022 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009023 if (UNLIKELY(target_method == nullptr)) {
9024 break;
9025 }
9026 // Find the method specified in the parent in referring class
9027 // so invoke-super invokes the method in the parent of the
9028 // referrer.
9029 target_method =
9030 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9031 kRuntimePointerSize);
9032 }
9033 break;
9034 }
9035 case DexFile::MethodHandleType::kInvokeInterface: {
9036 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9037 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009038 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9039 method_handle.field_or_method_idx_,
9040 referrer,
9041 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009042 break;
9043 }
Orion Hodson631827d2017-04-10 14:53:47 +01009044 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009045
9046 if (UNLIKELY(target_method == nullptr)) {
9047 DCHECK(Thread::Current()->IsExceptionPending());
9048 return nullptr;
9049 }
9050
9051 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9052 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9053 uint32_t access_flags = target_method->GetAccessFlags();
9054 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9055 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9056 return nullptr;
9057 }
9058
9059 // Calculate the number of parameters from the method shorty. We add the
9060 // receiver count (0 or 1) and deduct one for the return value.
9061 uint32_t shorty_length;
9062 target_method->GetShorty(&shorty_length);
9063 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9064
Orion Hodsonecd58562018-09-24 11:27:33 +01009065 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009066 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009067 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9068 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9069 if (method_params.Get() == nullptr) {
9070 DCHECK(self->IsExceptionPending());
9071 return nullptr;
9072 }
9073
Orion Hodsonecd58562018-09-24 11:27:33 +01009074 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009075 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009076 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009077 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009078 // Insert receiver. Use the class identified in the method handle rather than the declaring
9079 // class of the resolved method which may be super class or default interface method
9080 // (b/115964401).
9081 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9082 // receiver_class should have been resolved when resolving the target method.
9083 DCHECK(receiver_class != nullptr);
9084 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009085 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009086
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009087 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009088 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009089 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009090 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009091 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009092 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009093 if (nullptr == klass) {
9094 DCHECK(self->IsExceptionPending());
9095 return nullptr;
9096 }
9097 method_params->Set(index++, klass);
9098 it.Next();
9099 }
9100
Orion Hodsonecd58562018-09-24 11:27:33 +01009101 Handle<mirror::Class> return_type =
9102 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009103 if (UNLIKELY(return_type.IsNull())) {
9104 DCHECK(self->IsExceptionPending());
9105 return nullptr;
9106 }
9107
9108 Handle<mirror::MethodType>
9109 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9110 if (UNLIKELY(method_type.IsNull())) {
9111 DCHECK(self->IsExceptionPending());
9112 return nullptr;
9113 }
9114
9115 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9116 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9117 Handle<mirror::MethodHandlesLookup> lookup =
9118 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9119 return lookup->FindConstructor(self, constructor_class, method_type);
9120 }
9121
9122 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9123 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9124}
9125
Vladimir Markoaf940202017-12-08 15:01:18 +00009126ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9127 uint32_t method_handle_idx,
9128 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009129 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009130 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009131 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009132 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9133 case DexFile::MethodHandleType::kStaticPut:
9134 case DexFile::MethodHandleType::kStaticGet:
9135 case DexFile::MethodHandleType::kInstancePut:
9136 case DexFile::MethodHandleType::kInstanceGet:
9137 return ResolveMethodHandleForField(self, method_handle, referrer);
9138 case DexFile::MethodHandleType::kInvokeStatic:
9139 case DexFile::MethodHandleType::kInvokeInstance:
9140 case DexFile::MethodHandleType::kInvokeConstructor:
9141 case DexFile::MethodHandleType::kInvokeDirect:
9142 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009143 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009144 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009145}
9146
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009147bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9148 return (entry_point == GetQuickResolutionStub()) ||
9149 (quick_resolution_trampoline_ == entry_point);
9150}
9151
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009152bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9153 return (entry_point == GetQuickToInterpreterBridge()) ||
9154 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9155}
9156
9157bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9158 return (entry_point == GetQuickGenericJniStub()) ||
9159 (quick_generic_jni_trampoline_ == entry_point);
9160}
9161
David Sehra49e0532017-08-25 08:05:29 -07009162bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9163 return entry_point == GetJniDlsymLookupStub();
9164}
9165
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009166const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9167 return GetQuickGenericJniStub();
9168}
9169
Mathieu Chartiere401d142015-04-22 13:56:20 -07009170void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009171 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009172 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9173 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009174 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009175 }
9176}
9177
Alex Lightdb01a092017-04-03 15:39:55 -07009178void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9179 DCHECK(method->IsObsolete());
9180 // We cannot mess with the entrypoints of native methods because they are used to determine how
9181 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9182 if (!method->IsNative()) {
9183 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9184 }
9185}
9186
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009187void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009188 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009189 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009190 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9191 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009192 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9193 os << "Dumping registered class loaders\n";
9194 size_t class_loader_index = 0;
9195 for (const ClassLoaderData& class_loader : class_loaders_) {
9196 ObjPtr<mirror::ClassLoader> loader =
9197 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9198 if (loader != nullptr) {
9199 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9200 bool saw_one_dex_file = false;
9201 for (const DexCacheData& dex_cache : dex_caches_) {
9202 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9203 if (saw_one_dex_file) {
9204 os << ":";
9205 }
9206 saw_one_dex_file = true;
9207 os << dex_cache.dex_file->GetLocation();
9208 }
9209 }
9210 os << "]";
9211 bool found_parent = false;
9212 if (loader->GetParent() != nullptr) {
9213 size_t parent_index = 0;
9214 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9215 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9216 soa.Self()->DecodeJObject(class_loader2.weak_root));
9217 if (loader2 == loader->GetParent()) {
9218 os << ", parent #" << parent_index;
9219 found_parent = true;
9220 break;
9221 }
9222 parent_index++;
9223 }
9224 if (!found_parent) {
9225 os << ", unregistered parent of type "
9226 << loader->GetParent()->GetClass()->PrettyDescriptor();
9227 }
9228 } else {
9229 os << ", no parent";
9230 }
9231 os << "\n";
9232 }
9233 }
9234 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009235}
9236
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009237class CountClassesVisitor : public ClassLoaderVisitor {
9238 public:
9239 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9240
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009241 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009242 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009243 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009244 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009245 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9246 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009247 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009248 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009249
9250 size_t num_zygote_classes;
9251 size_t num_non_zygote_classes;
9252};
9253
9254size_t ClassLinker::NumZygoteClasses() const {
9255 CountClassesVisitor visitor;
9256 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009257 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009258}
9259
9260size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009261 CountClassesVisitor visitor;
9262 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009263 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009264}
9265
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009266size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009267 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009268 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009269 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009270}
9271
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009272pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009273 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009274}
9275
9276pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009277 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009278}
9279
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009280void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009281 DCHECK(!init_done_);
9282
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009283 DCHECK(klass != nullptr);
9284 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009285
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009286 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009287 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009288 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9289 int32_t index = static_cast<int32_t>(class_root);
9290 DCHECK(class_roots->Get(index) == nullptr);
9291 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009292}
9293
Roland Levillain0e840272018-08-23 19:55:30 +01009294void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9295 ObjPtr<mirror::Class> java_lang_Class,
9296 ClassRoot primitive_array_class_root,
9297 ClassRoot primitive_class_root,
9298 const char* descriptor) {
9299 StackHandleScope<1> hs(self);
9300 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9301 AllocPrimitiveArrayClass(self, java_lang_Class)));
9302 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9303 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9304 CheckSystemClass(self, primitive_array_class, descriptor);
9305}
9306
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009307ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9308 Thread* self,
9309 const std::vector<const DexFile*>& dex_files,
9310 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009311 Handle<mirror::ClassLoader> parent_loader,
9312 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009313
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009314 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009315
Mathieu Chartierc7853442015-03-27 14:35:38 -07009316 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009317 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009318
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009319 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009320 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009321 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009322 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009323 mirror::ObjectArray<mirror::Object>::Alloc(self,
9324 dex_elements_class.Get(),
9325 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009326 Handle<mirror::Class> h_dex_element_class =
9327 hs.NewHandle(dex_elements_class->GetComponentType());
9328
Mathieu Chartierc7853442015-03-27 14:35:38 -07009329 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009330 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009331 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009332
Andreas Gampe08883de2016-11-08 13:20:52 -08009333 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009334 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009335
Andreas Gampe08883de2016-11-08 13:20:52 -08009336 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009337 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009338
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009339 // Fill the elements array.
9340 int32_t index = 0;
9341 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009342 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009343
Calin Juravle7865ac72017-06-28 11:03:12 -07009344 // CreateWellKnownClassLoader is only used by gtests and compiler.
9345 // 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 -07009346 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9347 self,
9348 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009349 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009350 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009351
Mathieu Chartier3738e982017-05-12 16:07:28 -07009352 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9353 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009354 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009355 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009356 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009357 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009358
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009359 Handle<mirror::String> h_file_name = hs2.NewHandle(
9360 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009361 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009362 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9363
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009364 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009365 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009366 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009367
9368 h_dex_elements->Set(index, h_element.Get());
9369 index++;
9370 }
9371 DCHECK_EQ(index, h_dex_elements->GetLength());
9372
9373 // Create DexPathList.
9374 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009375 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009376 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009377 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009378 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009379 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9380 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9381 // elements.
9382 {
9383 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9384 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9385 DCHECK(native_lib_dirs != nullptr);
9386 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9387 DCHECK(list_class != nullptr);
9388 {
9389 StackHandleScope<1> h_list_scope(self);
9390 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9391 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9392 DCHECK(list_init);
9393 list_class = h_list_class.Get();
9394 }
9395 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9396 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9397 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9398 // normally never null), as long as one does not try to add elements, this will still
9399 // work.
9400 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9401 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009402
Calin Juravle7865ac72017-06-28 11:03:12 -07009403 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009404 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9405 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009406 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009407 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009408 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009409 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009410 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009411 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009412
9413 // Make a pretend boot-classpath.
9414 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009415 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009416 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009417 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009418 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009419 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009420 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009421 if (parent_loader.Get() == nullptr) {
9422 ScopedObjectAccessUnchecked soa(self);
9423 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9424 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9425 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9426 } else {
9427 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9428 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009429
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009430 ArtField* shared_libraries_field =
9431 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9432 DCHECK(shared_libraries_field != nullptr);
9433 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9434
9435 return h_class_loader.Get();
9436}
9437
9438jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9439 const std::vector<const DexFile*>& dex_files,
9440 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009441 jobject parent_loader,
9442 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009443 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9444 WellKnownClasses::dalvik_system_PathClassLoader) ||
9445 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009446 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9447 self->GetJniEnv()->IsSameObject(loader_class,
9448 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009449
9450 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9451 // We could move the jobject to the callers, but all call-sites do this...
9452 ScopedObjectAccessUnchecked soa(self);
9453
9454 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009455 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009456
9457 Handle<mirror::Class> h_loader_class =
9458 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009459 Handle<mirror::ClassLoader> h_parent =
9460 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9461 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9462 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009463
9464 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9465 self,
9466 dex_files,
9467 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009468 h_parent,
9469 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009470
9471 // Make it a global ref and return.
9472 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009473 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009474 return soa.Env()->NewGlobalRef(local_ref.get());
9475}
9476
Calin Juravle7865ac72017-06-28 11:03:12 -07009477jobject ClassLinker::CreatePathClassLoader(Thread* self,
9478 const std::vector<const DexFile*>& dex_files) {
9479 return CreateWellKnownClassLoader(self,
9480 dex_files,
9481 WellKnownClasses::dalvik_system_PathClassLoader,
9482 nullptr);
9483}
9484
Andreas Gampe8ac75952015-06-02 21:01:45 -07009485void ClassLinker::DropFindArrayClassCache() {
9486 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9487 find_array_class_cache_next_victim_ = 0;
9488}
9489
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009490void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009491 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009492 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009493 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009494 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9495 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009496 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009497 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009498 }
9499 }
9500}
9501
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009502void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9503 for (const ClassLoaderData& data : class_loaders_) {
9504 LinearAlloc* alloc = data.allocator;
9505 if (alloc != nullptr && !visitor->Visit(alloc)) {
9506 break;
9507 }
9508 }
9509}
9510
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009511void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9512 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009513 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009514 Thread* const self = Thread::Current();
9515 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009516 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009517 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009518 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009519 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9520 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009521 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009522 }
9523}
9524
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009525void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009526 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009527 std::vector<ClassLoaderData> to_delete;
9528 // Do the delete outside the lock to avoid lock violation in jit code cache.
9529 {
9530 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9531 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9532 const ClassLoaderData& data = *it;
9533 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009534 ObjPtr<mirror::ClassLoader> class_loader =
9535 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009536 if (class_loader != nullptr) {
9537 ++it;
9538 } else {
9539 VLOG(class_linker) << "Freeing class loader";
9540 to_delete.push_back(data);
9541 it = class_loaders_.erase(it);
9542 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009543 }
9544 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009545 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009546 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009547 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009548 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009549}
9550
Vladimir Marko21300532017-01-24 18:06:55 +00009551class GetResolvedClassesVisitor : public ClassVisitor {
9552 public:
9553 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9554 : result_(result),
9555 ignore_boot_classes_(ignore_boot_classes),
9556 last_resolved_classes_(result->end()),
9557 last_dex_file_(nullptr),
9558 vlog_is_on_(VLOG_IS_ON(class_linker)),
9559 extra_stats_(),
9560 last_extra_stats_(extra_stats_.end()) { }
9561
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009562 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009563 if (!klass->IsProxyClass() &&
9564 !klass->IsArrayClass() &&
9565 klass->IsResolved() &&
9566 !klass->IsErroneousResolved() &&
9567 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9568 const DexFile& dex_file = klass->GetDexFile();
9569 if (&dex_file != last_dex_file_) {
9570 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009571 DexCacheResolvedClasses resolved_classes(
9572 dex_file.GetLocation(),
9573 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9574 dex_file.GetLocationChecksum(),
9575 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009576 last_resolved_classes_ = result_->find(resolved_classes);
9577 if (last_resolved_classes_ == result_->end()) {
9578 last_resolved_classes_ = result_->insert(resolved_classes).first;
9579 }
9580 }
9581 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9582 if (UNLIKELY(vlog_is_on_) && added) {
9583 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9584 if (last_extra_stats_ == extra_stats_.end() ||
9585 last_extra_stats_->first != resolved_classes) {
9586 last_extra_stats_ = extra_stats_.find(resolved_classes);
9587 if (last_extra_stats_ == extra_stats_.end()) {
9588 last_extra_stats_ =
9589 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9590 }
9591 }
9592 }
9593 }
9594 return true;
9595 }
9596
9597 void PrintStatistics() const {
9598 if (vlog_is_on_) {
9599 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9600 auto it = extra_stats_.find(std::addressof(resolved_classes));
9601 DCHECK(it != extra_stats_.end());
9602 const ExtraStats& extra_stats = it->second;
9603 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9604 << " has " << resolved_classes.GetClasses().size() << " / "
9605 << extra_stats.number_of_class_defs_ << " resolved classes";
9606 }
9607 }
9608 }
9609
9610 private:
9611 struct ExtraStats {
9612 explicit ExtraStats(uint32_t number_of_class_defs)
9613 : number_of_class_defs_(number_of_class_defs) {}
9614 uint32_t number_of_class_defs_;
9615 };
9616
9617 std::set<DexCacheResolvedClasses>* result_;
9618 bool ignore_boot_classes_;
9619 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9620 const DexFile* last_dex_file_;
9621
9622 // Statistics.
9623 bool vlog_is_on_;
9624 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9625 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9626};
9627
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009628std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009629 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009630 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009631 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009632 std::set<DexCacheResolvedClasses> ret;
9633 VLOG(class_linker) << "Collecting resolved classes";
9634 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009635 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9636 VisitClasses(&visitor);
9637 if (VLOG_IS_ON(class_linker)) {
9638 visitor.PrintStatistics();
9639 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009640 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009641 return ret;
9642}
9643
Mathieu Chartier65975772016-08-05 10:46:36 -07009644class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9645 public:
9646 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9647 : method_(method),
9648 pointer_size_(pointer_size) {}
9649
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009650 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009651 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9652 holder_ = klass;
9653 }
9654 // Return false to stop searching if holder_ is not null.
9655 return holder_ == nullptr;
9656 }
9657
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009658 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009659 const ArtMethod* const method_;
9660 const PointerSize pointer_size_;
9661};
9662
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009663ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009664 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9665 CHECK(method->IsCopied());
9666 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9667 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009668 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009669}
9670
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009671ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9672 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009673 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009674 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009675 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009676}
9677
Roland Levillain0e840272018-08-23 19:55:30 +01009678// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009679template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009680 uint32_t method_idx,
9681 Handle<mirror::DexCache> dex_cache,
9682 Handle<mirror::ClassLoader> class_loader,
9683 ArtMethod* referrer,
9684 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009685template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009686 uint32_t method_idx,
9687 Handle<mirror::DexCache> dex_cache,
9688 Handle<mirror::ClassLoader> class_loader,
9689 ArtMethod* referrer,
9690 InvokeType type);
9691
Roland Levillain0e840272018-08-23 19:55:30 +01009692// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009693template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009694 Thread* self,
9695 ObjPtr<mirror::Class> java_lang_Class,
9696 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009697template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009698 Thread* self,
9699 ObjPtr<mirror::Class> java_lang_Class,
9700 uint32_t class_size);
9701
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009702} // namespace art