blob: a27b28e435ef4f2c4cf9fa3d5cf9d36ecddcf102 [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"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080047#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010048#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080049#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080050#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070051#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070052#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070054#include "class_loader_utils.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010055#include "class_root.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070056#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000057#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010058#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080059#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070060#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080061#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080062#include "dex/dex_file-inl.h"
63#include "dex/dex_file_exception_helpers.h"
64#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080065#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000066#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070067#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070068#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070069#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070070#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080071#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000072#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070073#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070074#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070075#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070076#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000077#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070078#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070079#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070080#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080081#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070082#include "imt_conflict_table.h"
83#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070084#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070085#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000086#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080087#include "jit/jit.h"
88#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010089#include "jni/java_vm_ext.h"
90#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070091#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070092#include "mirror/array-alloc-inl.h"
93#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000094#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070095#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080096#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070097#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070098#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080099#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700100#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700101#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100102#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700103#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700105#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100106#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000107#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700108#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800109#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000110#include "mirror/object-refvisitor-inl.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700111#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700112#include "mirror/object_array-inl.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700113#include "mirror/object_reference.h"
114#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800115#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700116#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800117#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700118#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100119#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700120#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700121#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700122#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700123#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700124#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700125#include "oat_file_assistant.h"
126#include "oat_file_manager.h"
127#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700128#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700129#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800130#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700131#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700132#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700133#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700134#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100135#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700136#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700137#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700138
139namespace art {
140
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800141using android::base::StringPrintf;
142
Mathieu Chartierc7853442015-03-27 14:35:38 -0700143static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700144static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700145
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700146static void ThrowNoClassDefFoundError(const char* fmt, ...)
147 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700148 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700149static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700150 va_list args;
151 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800152 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000153 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800154 va_end(args);
155}
156
Andreas Gampe99babb62015-11-02 16:20:00 -0800157static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700158 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700159 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700160 StackHandleScope<1> hs(self);
161 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700162 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700163 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700164
165 if (exception_class == nullptr) {
166 // No exc class ~ no <init>-with-string.
167 CHECK(self->IsExceptionPending());
168 self->ClearException();
169 return false;
170 }
171
Vladimir Markoba118822017-06-12 15:41:56 +0100172 ArtMethod* exception_init_method = exception_class->FindConstructor(
173 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700174 return exception_init_method != nullptr;
175}
176
Alex Lightd6251582016-10-31 11:12:30 -0700177static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700178 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700179 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
180 if (ext == nullptr) {
181 return nullptr;
182 } else {
183 return ext->GetVerifyError();
184 }
185}
186
187// Helper for ThrowEarlierClassFailure. Throws the stored error.
188static void HandleEarlierVerifyError(Thread* self,
189 ClassLinker* class_linker,
190 ObjPtr<mirror::Class> c)
191 REQUIRES_SHARED(Locks::mutator_lock_) {
192 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800193 DCHECK(obj != nullptr);
194 self->AssertNoPendingException();
195 if (obj->IsClass()) {
196 // Previous error has been stored as class. Create a new exception of that type.
197
198 // It's possible the exception doesn't have a <init>(String).
199 std::string temp;
200 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
201
202 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700203 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800204 } else {
205 self->ThrowNewException(descriptor, nullptr);
206 }
207 } else {
208 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100209 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700210 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800211 CHECK(throwable_class->IsAssignableFrom(error_class));
212 self->SetException(obj->AsThrowable());
213 }
214 self->AssertPendingException();
215}
216
Andreas Gampe5b20b352018-10-11 19:03:20 -0700217// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
218// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
219// before.
220template <bool kNeedsVerified = false>
221static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
222 REQUIRES_SHARED(Locks::mutator_lock_) {
223 if (kNeedsVerified) {
224 // To not fail access-flags access checks, push a minimal state.
225 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
226 }
227 if (!klass->WasVerificationAttempted()) {
228 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
229 klass->SetVerificationAttempted();
230 }
231}
232
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800233void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
234 bool wrap_in_no_class_def,
235 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700236 // The class failed to initialize on a previous attempt, so we want to throw
237 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
238 // failed in verification, in which case v2 5.4.1 says we need to re-throw
239 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800240 Runtime* const runtime = Runtime::Current();
241 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700242 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700243 if (GetVerifyError(c) != nullptr) {
244 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800245 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700246 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800247 } else {
248 extra = verify_error->AsThrowable()->Dump();
249 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700250 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800251 if (log) {
252 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
253 << ": " << extra;
254 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700255 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700256
David Sehr709b0702016-10-13 09:12:37 -0700257 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800258 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800259 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700260 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700261 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000262 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700263 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700264 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800265 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800266 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800267 }
Alex Lightd6251582016-10-31 11:12:30 -0700268 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
269 // might have meant to go down the earlier if statement with the original error but it got
270 // swallowed by the OOM so we end up here.
271 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800272 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
273 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
274 // exception will be a cause.
275 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700276 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700277 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700278 }
279}
280
Brian Carlstromb23eab12014-10-08 17:55:21 -0700281static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700282 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700283 if (VLOG_IS_ON(class_linker)) {
284 std::string temp;
285 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000286 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700287 }
288}
289
290static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700291 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700292 Thread* self = Thread::Current();
293 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700294
295 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700296 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700297
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800298 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
299 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
300 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800301 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800302 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
303 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
304 // could have caused the error.
305 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
306 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
307 << " failed initialization: "
308 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800309 }
310
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700311 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700312 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
313 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700314
Elliott Hughesa4f94742012-05-29 16:28:38 -0700315 // We only wrap non-Error exceptions; an Error can just be used as-is.
316 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000317 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700318 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700319 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700320}
321
Fred Shih381e4ca2014-08-25 17:24:27 -0700322// Gap between two fields in object layout.
323struct FieldGap {
324 uint32_t start_offset; // The offset from the start of the object.
325 uint32_t size; // The gap size of 1, 2, or 4 bytes.
326};
327struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800328 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700329 }
330 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
331 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800332 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700333 // Note that the priority queue returns the largest element, so operator()
334 // should return true if lhs is less than rhs.
335 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700336 }
337};
Andreas Gampec55bb392018-09-21 00:02:02 +0000338using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700339
340// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800341static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700342 DCHECK(gaps != nullptr);
343
344 uint32_t current_offset = gap_start;
345 while (current_offset != gap_end) {
346 size_t remaining = gap_end - current_offset;
347 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
348 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
349 current_offset += sizeof(uint32_t);
350 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
351 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
352 current_offset += sizeof(uint16_t);
353 } else {
354 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
355 current_offset += sizeof(uint8_t);
356 }
357 DCHECK_LE(current_offset, gap_end) << "Overran gap";
358 }
359}
360// Shuffle fields forward, making use of gaps whenever possible.
361template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000362static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700363 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700364 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700365 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700366 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700367 DCHECK(current_field_idx != nullptr);
368 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700369 DCHECK(gaps != nullptr);
370 DCHECK(field_offset != nullptr);
371
372 DCHECK(IsPowerOfTwo(n));
373 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700374 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700375 Primitive::Type type = field->GetTypeAsPrimitiveType();
376 if (Primitive::ComponentSize(type) < n) {
377 break;
378 }
379 if (!IsAligned<n>(field_offset->Uint32Value())) {
380 MemberOffset old_offset = *field_offset;
381 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
382 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
383 }
David Sehr709b0702016-10-13 09:12:37 -0700384 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700385 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700386 if (!gaps->empty() && gaps->top().size >= n) {
387 FieldGap gap = gaps->top();
388 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100389 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700390 field->SetOffset(MemberOffset(gap.start_offset));
391 if (gap.size > n) {
392 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
393 }
394 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100395 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700396 field->SetOffset(*field_offset);
397 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
398 }
399 ++(*current_field_idx);
400 }
401}
402
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800403ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700404 : boot_class_table_(new ClassTable()),
405 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800406 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800407 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700408 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000409 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700410 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800411 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800412 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100413 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800414 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700415 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700416 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
417 // For CHA disabled during Aot, see b/34193647.
418
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700419 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700420 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
421 "Array cache size wrong.");
422 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700423}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800425void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700426 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800427 if (c2 == nullptr) {
428 LOG(FATAL) << "Could not find class " << descriptor;
429 UNREACHABLE();
430 }
431 if (c1.Get() != c2) {
432 std::ostringstream os1, os2;
433 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
434 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
435 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
436 << ". This is most likely the result of a broken build. Make sure that "
437 << "libcore and art projects match.\n\n"
438 << os1.str() << "\n\n" << os2.str();
439 UNREACHABLE();
440 }
441}
442
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800443bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
444 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800445 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700446
Mathieu Chartiere401d142015-04-22 13:56:20 -0700447 Thread* const self = Thread::Current();
448 Runtime* const runtime = Runtime::Current();
449 gc::Heap* const heap = runtime->GetHeap();
450
Jeff Haodcdc85b2015-12-04 14:06:18 -0800451 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700452 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700453
Mathieu Chartiere401d142015-04-22 13:56:20 -0700454 // Use the pointer size from the runtime since we are probably creating the image.
455 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
456
Elliott Hughes30646832011-10-13 16:59:46 -0700457 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700458 // 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 -0800459 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700460 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700461 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700462 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
463 // the incorrect result when comparing to-space vs from-space.
Vladimir Markobcf17522018-06-01 13:14:32 +0100464 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(MakeObjPtr(
465 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800466 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100467 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700468 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700469 if (kUseBakerReadBarrier) {
470 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800471 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700472 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700473 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800474 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700475 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700476
Elliott Hughes418d20f2011-09-22 14:00:39 -0700477 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700479 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers23435d02012-09-24 11:23:12 -0700483 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700484 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700485 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800486 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700487 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700488 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000489 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700490
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700491 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800492 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
493 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
494 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
495 java_lang_Object.Get(),
496 java_lang_Object->GetObjectSize(),
497 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700498
Igor Murashkin86083f72017-10-27 10:59:04 -0700499 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000500 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700501 // It might seem the lock here is unnecessary, however all the SubtypeCheck
502 // functions are annotated to require locks all the way down.
503 //
504 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
505 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000506 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
507 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700508 }
509
Ian Rogers23435d02012-09-24 11:23:12 -0700510 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700511 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700512 AllocClass(self, java_lang_Class.Get(),
513 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700515
Roland Levillain0e840272018-08-23 19:55:30 +0100516 // Setup java.lang.String.
517 //
518 // We make this class non-movable for the unlikely case where it were to be
519 // moved by a sticky-bit (minor) collection when using the Generational
520 // Concurrent Copying (CC) collector, potentially creating a stale reference
521 // in the `klass_` field of one of its instances allocated in the Large-Object
522 // Space (LOS) -- see the comment about the dirty card scanning logic in
523 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700524 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700525 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100526 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700527 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000528 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400529
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700530 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700531 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700532 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700533 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000534 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700535
Ian Rogers23435d02012-09-24 11:23:12 -0700536 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700537 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100538 mirror::ObjectArray<mirror::Class>::Alloc(self,
539 object_array_class.Get(),
540 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700541 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100542 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
543 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
544 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
545 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100546 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
547 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700548
Mathieu Chartier6beced42016-11-15 15:51:31 -0800549 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
550 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
551
Vladimir Marko02610552018-06-04 14:38:00 +0100552 // Create array interface entries to populate once we can load system classes.
553 object_array_class->SetIfTable(AllocIfTable(self, 2));
554 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
555
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100557 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
558 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100559 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100560 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
561 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
562 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
563 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
564 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
565 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566
Vladimir Markoacb906d2018-05-30 10:23:49 +0100567 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700568 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100569 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100570 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100571 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572
Vladimir Markoacb906d2018-05-30 10:23:49 +0100573 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700574 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100575 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100576 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100577 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700578
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700579 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700580
Ian Rogers52813c92012-10-11 11:50:38 -0700581 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700582 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700583 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100584 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100585 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700586 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000587 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700588
Alex Lightd6251582016-10-31 11:12:30 -0700589
590 // Setup dalvik.system.ClassExt
591 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
592 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100593 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000594 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700595
Mathieu Chartier66f19252012-09-18 08:57:04 -0700596 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700597 Handle<mirror::Class> object_array_string(hs.NewHandle(
598 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700599 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700600 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100601 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700602
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000603 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700604 // Create runtime resolution and imt conflict methods.
605 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000606 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
607 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700608
Ian Rogers23435d02012-09-24 11:23:12 -0700609 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
610 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
611 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800612 if (boot_class_path.empty()) {
613 *error_msg = "Boot classpath is empty.";
614 return false;
615 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800616 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800617 if (dex_file.get() == nullptr) {
618 *error_msg = "Null dex file.";
619 return false;
620 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700621 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800622 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700623 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700624
625 // now we can use FindSystemClass
626
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700627 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
628 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700629 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800630 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700631 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700632 quick_resolution_trampoline_ = GetQuickResolutionStub();
633 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
634 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700635 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700636
Alex Lightd6251582016-10-31 11:12:30 -0700637 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000638 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800639 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700640 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000641 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800642 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000643 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800644 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700645 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000646 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700647 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
648 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Ian Rogers23435d02012-09-24 11:23:12 -0700650 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100651 AllocAndSetPrimitiveArrayClassRoot(self,
652 java_lang_Class.Get(),
653 ClassRoot::kBooleanArrayClass,
654 ClassRoot::kPrimitiveBoolean,
655 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656
Roland Levillain0e840272018-08-23 19:55:30 +0100657 AllocAndSetPrimitiveArrayClassRoot(
658 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659
Roland Levillain0e840272018-08-23 19:55:30 +0100660 AllocAndSetPrimitiveArrayClassRoot(
661 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700662
Roland Levillain0e840272018-08-23 19:55:30 +0100663 AllocAndSetPrimitiveArrayClassRoot(
664 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800666 CheckSystemClass(self, int_array_class, "[I");
667 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700668
Roland Levillain0e840272018-08-23 19:55:30 +0100669 AllocAndSetPrimitiveArrayClassRoot(
670 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671
Roland Levillain0e840272018-08-23 19:55:30 +0100672 AllocAndSetPrimitiveArrayClassRoot(
673 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800675 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
676 // in class_table_.
677 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700678
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800679 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
680 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700681
Ian Rogers23435d02012-09-24 11:23:12 -0700682 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700683 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800684 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700685 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800686 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700687 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
688 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100689 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
690 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700691
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700692 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
693 // suspension.
694 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000695 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700696 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000697 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700698 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000699 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700700 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000701 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700702
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700703 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100704 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700705
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800706 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700707
Ian Rogers23435d02012-09-24 11:23:12 -0700708 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100709 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
710 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700711
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700712 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100713 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700714 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100715 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700716
717 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700718 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
719 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100720 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700721
722 // Create java.lang.reflect.Constructor.class root and array root.
723 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
724 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100725 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700726 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
727 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100728 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700729
730 // Create java.lang.reflect.Method.class root and array root.
731 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
732 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100733 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700734 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
735 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100736 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700737
Orion Hodson005ac512017-10-24 15:43:43 +0100738 // Create java.lang.invoke.CallSite.class root
739 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
740 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100741 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100742
Narayan Kamathafa48272016-08-03 12:46:58 +0100743 // Create java.lang.invoke.MethodType.class root
744 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
745 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100746 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100747
748 // Create java.lang.invoke.MethodHandleImpl.class root
749 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
750 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100751 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100752 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100753
Orion Hodsonc069a302017-01-18 09:23:12 +0000754 // Create java.lang.invoke.MethodHandles.Lookup.class root
755 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
756 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100757 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000758
Orion Hodson005ac512017-10-24 15:43:43 +0100759 // Create java.lang.invoke.VarHandle.class root
760 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000761 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100762 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100763
764 // Create java.lang.invoke.FieldVarHandle.class root
765 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
766 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100767 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100768
769 // Create java.lang.invoke.ArrayElementVarHandle.class root
770 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
771 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100772 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100773
774 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
775 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
776 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100777 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100778
779 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
780 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
781 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100782 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000783
Narayan Kamath000e1882016-10-24 17:14:25 +0100784 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
785 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100786 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100787
Brian Carlstrom1f870082011-08-23 16:02:11 -0700788 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700789 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000790 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800791 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700792 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700793 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
794 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700795 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700796 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700797 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700798 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700799 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700800 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700801 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700802 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700803 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700804 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700805 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700806 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700807
Ian Rogers23435d02012-09-24 11:23:12 -0700808 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700809 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700810 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700811 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100812 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700813
jeffhao8cd6dda2012-02-22 10:15:34 -0800814 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700815 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100816 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100817 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700818 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
820 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
821 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700822 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000823 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
824 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700825
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700826 // Create conflict tables that depend on the class linker.
827 runtime->FixupConflictTables();
828
Ian Rogers98379392014-02-24 16:53:16 -0800829 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700830
Brian Carlstroma004aa92012-02-08 18:05:09 -0800831 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800832
833 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700834}
835
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700836static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
837 REQUIRES_SHARED(Locks::mutator_lock_) {
838 // Find String.<init> -> StringFactory bindings.
839 ObjPtr<mirror::Class> string_factory_class =
840 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
841 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100842 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700843 WellKnownClasses::InitStringInit(string_class, string_factory_class);
844 // Update the primordial thread.
845 self->InitStringEntryPoints();
846}
847
Ian Rogers98379392014-02-24 16:53:16 -0800848void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800849 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700850
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700851 CreateStringInitBindings(self, this);
852
Brian Carlstrom16192862011-09-12 17:50:06 -0700853 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700854 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700855 // as the types of the field can't be resolved prior to the runtime being
856 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700857 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100858 Handle<mirror::Class> java_lang_ref_Reference =
859 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700860 Handle<mirror::Class> java_lang_ref_FinalizerReference =
861 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800862
Mathieu Chartierc7853442015-03-27 14:35:38 -0700863 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700864 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
865 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700866
Mathieu Chartierc7853442015-03-27 14:35:38 -0700867 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700868 CHECK_STREQ(queue->GetName(), "queue");
869 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700870
Mathieu Chartierc7853442015-03-27 14:35:38 -0700871 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700872 CHECK_STREQ(queueNext->GetName(), "queueNext");
873 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700874
Mathieu Chartierc7853442015-03-27 14:35:38 -0700875 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700876 CHECK_STREQ(referent->GetName(), "referent");
877 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700878
Mathieu Chartierc7853442015-03-27 14:35:38 -0700879 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700880 CHECK_STREQ(zombie->GetName(), "zombie");
881 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700882
Brian Carlstroma663ea52011-08-19 23:33:41 -0700883 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100884 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700885 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700886 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700887 CHECK(klass != nullptr);
888 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889 // note SetClassRoot does additional validation.
890 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700891 }
892
Vladimir Marko02610552018-06-04 14:38:00 +0100893 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700894
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700895 // disable the slow paths in FindClass and CreatePrimitiveClass now
896 // that Object, Class, and Object[] are setup
897 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700898
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700899 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
900 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
901 // ensure that the class will be initialized.
902 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700903 verifier::ClassVerifier::Init(); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700904
905 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
906 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
907 // Strange, but don't crash.
908 LOG(WARNING) << "Could not prepare StackOverflowError.";
909 self->ClearException();
910 }
911 }
912
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800913 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700914}
915
Vladimir Markodcfcce42018-06-27 10:00:28 +0000916void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100917 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
918 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700919 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700920 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100921 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700922 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000924 } else {
925 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700926 }
927 }
928}
929
Jeff Haodcdc85b2015-12-04 14:06:18 -0800930struct TrampolineCheckData {
931 const void* quick_resolution_trampoline;
932 const void* quick_imt_conflict_trampoline;
933 const void* quick_generic_jni_trampoline;
934 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700935 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800936 ArtMethod* m;
937 bool error;
938};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800939
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800940bool ClassLinker::InitFromBootImage(std::string* error_msg) {
941 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700942 CHECK(!init_done_);
943
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700944 Runtime* const runtime = Runtime::Current();
945 Thread* const self = Thread::Current();
946 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800947 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
948 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700949 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
950 if (!ValidPointerSize(pointer_size_unchecked)) {
951 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800952 return false;
953 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000954 const ImageHeader& image_header = spaces[0]->GetImageHeader();
955 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800956 if (!runtime->IsAotCompiler()) {
957 // Only the Aot compiler supports having an image with a different pointer size than the
958 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
959 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700960 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800961 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700962 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800963 sizeof(void*));
964 return false;
965 }
966 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000967 DCHECK(!runtime->HasResolutionMethod());
968 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
969 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
970 runtime->SetImtUnimplementedMethod(
971 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
972 runtime->SetCalleeSaveMethod(
973 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
974 CalleeSaveType::kSaveAllCalleeSaves);
975 runtime->SetCalleeSaveMethod(
976 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
977 CalleeSaveType::kSaveRefsOnly);
978 runtime->SetCalleeSaveMethod(
979 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
980 CalleeSaveType::kSaveRefsAndArgs);
981 runtime->SetCalleeSaveMethod(
982 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
983 CalleeSaveType::kSaveEverything);
984 runtime->SetCalleeSaveMethod(
985 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
986 CalleeSaveType::kSaveEverythingForClinit);
987 runtime->SetCalleeSaveMethod(
988 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
989 CalleeSaveType::kSaveEverythingForSuspendCheck);
990
Jeff Haodcdc85b2015-12-04 14:06:18 -0800991 std::vector<const OatFile*> oat_files =
992 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
993 DCHECK(!oat_files.empty());
994 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800995 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
996 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
997 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
998 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
999 if (kIsDebugBuild) {
1000 // Check that the other images use the same trampoline.
1001 for (size_t i = 1; i < oat_files.size(); ++i) {
1002 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1003 const void* ith_quick_resolution_trampoline =
1004 ith_oat_header.GetQuickResolutionTrampoline();
1005 const void* ith_quick_imt_conflict_trampoline =
1006 ith_oat_header.GetQuickImtConflictTrampoline();
1007 const void* ith_quick_generic_jni_trampoline =
1008 ith_oat_header.GetQuickGenericJniTrampoline();
1009 const void* ith_quick_to_interpreter_bridge_trampoline =
1010 ith_oat_header.GetQuickToInterpreterBridge();
1011 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1012 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1013 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1014 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1015 // Make sure that all methods in this image do not contain those trampolines as
1016 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1017 TrampolineCheckData data;
1018 data.error = false;
1019 data.pointer_size = GetImagePointerSize();
1020 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1021 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1022 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1023 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1024 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001025 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1026 if (obj->IsClass()) {
1027 ObjPtr<mirror::Class> klass = obj->AsClass();
1028 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1029 const void* entrypoint =
1030 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1031 if (entrypoint == data.quick_resolution_trampoline ||
1032 entrypoint == data.quick_imt_conflict_trampoline ||
1033 entrypoint == data.quick_generic_jni_trampoline ||
1034 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1035 data.m = &m;
1036 data.error = true;
1037 return;
1038 }
1039 }
1040 }
1041 };
1042 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001043 if (data.error) {
1044 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001045 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001046 *error_msg = "Found an ArtMethod with a bad entrypoint";
1047 return false;
1048 }
1049 }
1050 }
1051 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001052
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001053 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001054 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1055 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001056 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001057
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001058 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001059 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001060 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1061 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001062 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1063 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001064
Vladimir Marko4433c432018-12-04 14:57:47 +00001065 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1066 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001067 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001068 // Boot class loader, use a null handle.
1069 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001070 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001071 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001072 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001073 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001074 /*out*/&dex_files,
1075 error_msg)) {
1076 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001077 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001078 // Append opened dex files at the end.
1079 boot_dex_files_.insert(boot_dex_files_.end(),
1080 std::make_move_iterator(dex_files.begin()),
1081 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001082 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001083 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1084 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1085 }
Ian Rogers98379392014-02-24 16:53:16 -08001086 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001087
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001088 VLOG(startup) << __FUNCTION__ << " exiting";
1089 return true;
1090}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001091
Vladimir Marko4433c432018-12-04 14:57:47 +00001092void ClassLinker::AddExtraBootDexFiles(
1093 Thread* self,
1094 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1095 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1096 AppendToBootClassPath(self, *dex_file);
1097 boot_dex_files_.push_back(std::move(dex_file));
1098 }
1099}
1100
Jeff Hao5872d7c2016-04-27 11:07:41 -07001101bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001102 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001103 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001104 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1105 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001106}
1107
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001108static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1109 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001110 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001111 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001112 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001113 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001114 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001115 DCHECK(dex_file_field != nullptr);
1116 DCHECK(dex_file_name_field != nullptr);
1117 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001118 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001119 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001121 // Null dex file means it was probably a jar with no dex files, return a null string.
1122 *out_name = nullptr;
1123 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001124 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001125 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001127 *out_name = name_object->AsString();
1128 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001129 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001130 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001131}
1132
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001133static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1134 ObjPtr<mirror::ClassLoader> class_loader,
1135 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1136 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001137 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001138 StackHandleScope<1> hs(soa.Self());
1139 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001140 // Get element names. Sets error to true on failure.
1141 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1142 REQUIRES_SHARED(Locks::mutator_lock_) {
1143 if (element == nullptr) {
1144 *error_msg = "Null dex element";
1145 *error = true; // Null element is a critical error.
1146 return false; // Had an error, stop the visit.
1147 }
1148 ObjPtr<mirror::String> name;
1149 if (!GetDexPathListElementName(element, &name)) {
1150 *error_msg = "Invalid dex path list element";
1151 *error = true; // Invalid element, make it a critical error.
1152 return false; // Stop the visit.
1153 }
1154 if (name != nullptr) {
1155 dex_files->push_front(name);
1156 }
1157 return true; // Continue with the next Element.
1158 };
1159 bool error = VisitClassLoaderDexElements(soa,
1160 handle,
1161 add_element_names,
1162 /*defaultReturn=*/ false);
1163 return !error;
1164}
1165
1166static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1167 ObjPtr<mirror::ClassLoader> image_class_loader,
1168 ObjPtr<mirror::ClassLoader> class_loader,
1169 std::string* error_msg)
1170 REQUIRES_SHARED(Locks::mutator_lock_) {
1171 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1172 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1173 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001174 return false;
1175 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001176 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1177 *error_msg = "Hierarchies don't match";
1178 return false;
1179 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1180 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1181 image_class_loader->PrettyTypeOf().c_str(),
1182 class_loader->PrettyTypeOf().c_str());
1183 return false;
1184 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1185 class_loader->GetClass()) {
1186 *error_msg = StringPrintf("Unknown class loader type %s",
1187 class_loader->PrettyTypeOf().c_str());
1188 // Unsupported class loader.
1189 return false;
1190 }
1191 return true;
1192}
1193
1194static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1195 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1196 std::string* error_msg)
1197 REQUIRES_SHARED(Locks::mutator_lock_) {
1198 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1199 std::equal(image_dex_files.begin(),
1200 image_dex_files.end(),
1201 loader_dex_files.begin(),
1202 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1203 REQUIRES_SHARED(Locks::mutator_lock_) {
1204 return lhs->Equals(rhs);
1205 });
1206 if (!equal) {
1207 VLOG(image) << "Image dex files " << image_dex_files.size();
1208 for (ObjPtr<mirror::String> name : image_dex_files) {
1209 VLOG(image) << name->ToModifiedUtf8();
1210 }
1211 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1212 for (ObjPtr<mirror::String> name : loader_dex_files) {
1213 VLOG(image) << name->ToModifiedUtf8();
1214 }
1215 *error_msg = "Mismatch in dex files";
1216 }
1217 return equal;
1218}
1219
1220static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1221 ObjPtr<mirror::ClassLoader> image_class_loader,
1222 ObjPtr<mirror::ClassLoader> class_loader,
1223 bool check_dex_file_names,
1224 std::string* error_msg)
1225 REQUIRES_SHARED(Locks::mutator_lock_) {
1226 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1227 return false;
1228 }
1229
1230 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1231 // No need to check further.
1232 return true;
1233 }
1234
1235 if (check_dex_file_names) {
1236 std::list<ObjPtr<mirror::String>> image_dex_files;
1237 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001238 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001239 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001240
1241 std::list<ObjPtr<mirror::String>> loader_dex_files;
1242 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1243 return false;
1244 }
1245
1246 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1247 return false;
1248 }
1249 }
1250
1251 ArtField* field =
1252 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1253 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1254 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1255 if (shared_libraries_image_loader == nullptr) {
1256 if (shared_libraries_loader != nullptr) {
1257 *error_msg = "Mismatch in shared libraries";
1258 return false;
1259 }
1260 } else if (shared_libraries_loader == nullptr) {
1261 *error_msg = "Mismatch in shared libraries";
1262 return false;
1263 } else {
1264 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1265 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1266 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1267 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1268 if (array1->GetLength() != array2->GetLength()) {
1269 *error_msg = "Mismatch in number of shared libraries";
1270 return false;
1271 }
1272
1273 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1274 // Do a full comparison of the class loaders, including comparing their dex files.
1275 if (!CompareClassLoaders(soa,
1276 array1->Get(i),
1277 array2->Get(i),
1278 /*check_dex_file_names=*/ true,
1279 error_msg)) {
1280 return false;
1281 }
1282 }
1283 }
1284
1285 // Do a full comparison of the class loaders, including comparing their dex files.
1286 if (!CompareClassLoaders(soa,
1287 image_class_loader->GetParent(),
1288 class_loader->GetParent(),
1289 /*check_dex_file_names=*/ true,
1290 error_msg)) {
1291 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001292 }
1293 return true;
1294}
1295
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001296class CHAOnDeleteUpdateClassVisitor {
1297 public:
1298 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1299 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1300 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1301 self_(Thread::Current()) {}
1302
1303 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1304 // This class is going to be unloaded. Tell CHA about it.
1305 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1306 return true;
1307 }
1308 private:
1309 const LinearAlloc* allocator_;
1310 const ClassHierarchyAnalysis* cha_;
1311 const PointerSize pointer_size_;
1312 const Thread* self_;
1313};
1314
Chris Wailes0c61be42018-09-26 17:27:34 -07001315/*
1316 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001317 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001318 */
1319class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001320 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001321 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001322 space_(space),
1323 intern_table_(*Runtime::Current()->GetInternTable()) {}
1324
Chris Wailes0c61be42018-09-26 17:27:34 -07001325 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001326 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001327 if (referred_obj != nullptr &&
1328 space_.HasAddress(referred_obj.Ptr()) &&
1329 referred_obj->IsString()) {
1330 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001331
1332 if (kIsDebugBuild) {
1333 // Saved to temporary variables to aid in debugging.
1334 ObjPtr<mirror::String> strong_lookup_result =
1335 intern_table_.LookupStrong(Thread::Current(), referred_str);
1336 ObjPtr<mirror::String> weak_lookup_result =
1337 intern_table_.LookupWeak(Thread::Current(), referred_str);
1338
1339 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1340 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001341 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001342 }
1343
Chris Wailes0c61be42018-09-26 17:27:34 -07001344 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001345 mirror::CompressedReference<mirror::Object>* root) const
1346 REQUIRES_SHARED(Locks::mutator_lock_) {
1347 if (!root->IsNull()) {
1348 VisitRoot(root);
1349 }
1350 }
1351
Chris Wailes0c61be42018-09-26 17:27:34 -07001352 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001353 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001354 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001355 }
1356
1357 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001358 void operator()(ObjPtr<mirror::Object> obj,
1359 MemberOffset offset,
1360 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001361 REQUIRES_SHARED(Locks::mutator_lock_) {
1362 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1363 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1364 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1365 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001366 ObjPtr<mirror::Object> referred_obj =
1367 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1368
1369 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001370 }
1371 }
1372
1373 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1374 ObjPtr<mirror::Reference> ref) const
1375 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001376 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001377 }
1378
Chris Wailes0c61be42018-09-26 17:27:34 -07001379 const gc::space::ImageSpace& space_;
1380 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001381};
1382
Chris Wailes0c61be42018-09-26 17:27:34 -07001383/*
1384 * This function verifies that string references in the AppImage have been
1385 * properly interned. To be considered properly interned a reference must
1386 * point to the same version of the string that the intern table does.
1387 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001388void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001389 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1390 const ImageHeader& image_header = space.GetImageHeader();
1391 const uint8_t* target_base = space.GetMemMap()->Begin();
1392 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001393
1394 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1395 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001396
1397 VerifyStringInterningVisitor visitor(space);
1398 bitmap->VisitMarkedRange(objects_begin,
1399 objects_end,
1400 [&space, &visitor](mirror::Object* obj)
1401 REQUIRES_SHARED(Locks::mutator_lock_) {
1402 if (space.HasAddress(obj)) {
1403 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001404 obj->VisitReferences</* kVisitNativeRoots= */ true,
1405 kVerifyNone,
1406 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001407 } else {
1408 // Don't visit native roots for non-dex-cache as they can't contain
1409 // native references to strings. This is verified during compilation
1410 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001411 obj->VisitReferences</* kVisitNativeRoots= */ false,
1412 kVerifyNone,
1413 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001414 }
1415 }
1416 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001417}
1418
Andreas Gampe2af99022017-04-25 08:32:59 -07001419// new_class_set is the set of classes that were read from the class table section in the image.
1420// If there was no class table section, it is null.
1421// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001422class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001423 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001424 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001425 ClassLinker* class_linker,
1426 gc::space::ImageSpace* space,
1427 Handle<mirror::ClassLoader> class_loader,
1428 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001429 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001430 REQUIRES(!Locks::dex_lock_)
1431 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001432
Chris Wailesfbeef462018-10-19 14:16:35 -07001433 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001434 REQUIRES_SHARED(Locks::mutator_lock_);
1435
1436 static void UpdateInternStrings(
1437 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001438 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001439 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1440 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001441};
1442
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001443void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001444 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001445 gc::space::ImageSpace* space,
1446 Handle<mirror::ClassLoader> class_loader,
1447 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001448 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001449 REQUIRES(!Locks::dex_lock_)
1450 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001451 ScopedTrace app_image_timing("AppImage:Updating");
1452
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001453 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001454 Runtime* const runtime = Runtime::Current();
1455 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001456 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001457 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001458 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001459 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001460 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001461 const size_t num_dex_caches = dex_caches->GetLength();
1462 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001463 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001464 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001465 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001466 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001467 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1468 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001469 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001470
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001471 if (!load_app_image_startup_cache) {
1472 dex_cache->ClearPreResolvedStrings();
1473 }
1474
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001475 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001476 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001477 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001478 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001479 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001480 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001481 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001482
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001483 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001484 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001485 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001486 DCHECK(it != new_class_set->end());
1487 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001488 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001489
Vladimir Marko1a1de672016-10-13 12:53:15 +01001490 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001491 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001492 DCHECK(it2 != new_class_set->end());
1493 DCHECK_EQ(it2->Read(), super_class);
1494 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001495
Vladimir Marko1a1de672016-10-13 12:53:15 +01001496 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1497 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001498 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1499 if (!class_linker->IsQuickResolutionStub(code) &&
1500 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001501 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001502 !m.IsNative()) {
1503 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001504 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001505 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001506
Vladimir Marko1a1de672016-10-13 12:53:15 +01001507 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1508 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001509 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1510 if (!class_linker->IsQuickResolutionStub(code) &&
1511 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001512 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001513 !m.IsNative()) {
1514 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001515 }
1516 }
1517 }
1518 }
1519 }
1520 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001521 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001522
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001523 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001524 HandleAppImageStrings(space);
1525
1526 if (kIsDebugBuild) {
1527 VerifyStringInterning(*space);
1528 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001529 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001530
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001531 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001532 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001533 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001534 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1535 header.VisitPackedArtMethods([&](ArtMethod& method)
1536 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1537 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1538 if (klass != nullptr) {
1539 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1540 }
1541 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001542 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001543}
1544
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001545void AppImageLoadingHelper::UpdateInternStrings(
1546 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001547 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001548 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1549 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001550 const ImageSection& sro_section =
1551 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1552 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001553 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001554
1555 VLOG(image)
1556 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1557 << num_string_offsets;
1558
Chris Wailesfbeef462018-10-19 14:16:35 -07001559 const auto* sro_base =
1560 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001561
1562 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001563 uint32_t base_offset = sro_base[offset_index].first;
1564
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001565 if (HasDexCacheStringNativeRefTag(base_offset)) {
1566 base_offset = ClearDexCacheNativeRefTags(base_offset);
1567 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001568
1569 ObjPtr<mirror::DexCache> dex_cache =
1570 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1571 uint32_t string_index = sro_base[offset_index].second;
1572
1573 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1574 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001575 DCHECK(referred_string != nullptr);
1576
Chris Wailesfbeef462018-10-19 14:16:35 -07001577 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001578 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001579 // This doesn't use SetResolvedString to maintain consistency with how
1580 // we load the string. The index from the source string must be
1581 // re-used due to the circular nature of the cache. Because we are not
1582 // using a helper function we need to mark the GC card manually.
1583 WriteBarrier::ForEveryFieldWrite(dex_cache);
1584 dex_cache->GetStrings()[string_index].store(
1585 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001586 } else if (!use_preresolved_strings) {
1587 dex_cache->GetStrings()[string_index].store(
1588 mirror::StringDexCachePair(intern_table->InternStrong(referred_string), source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001589 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001590 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001591 if (use_preresolved_strings) {
1592 base_offset = ClearDexCacheNativeRefTags(base_offset);
1593 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001594
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001595 ObjPtr<mirror::DexCache> dex_cache =
1596 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1597 uint32_t string_index = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001598
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001599 ObjPtr<mirror::String> referred_string =
1600 dex_cache->GetPreResolvedStrings()[string_index].Read();
1601 DCHECK(referred_string != nullptr);
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001602
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001603 auto it = intern_remap.find(referred_string.Ptr());
1604 if (it != intern_remap.end()) {
1605 // Because we are not using a helper function we need to mark the GC card manually.
1606 WriteBarrier::ForEveryFieldWrite(dex_cache);
1607 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1608 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001609 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001610 } else {
1611 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001612 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001613 DCHECK_ALIGNED(raw_member_offset, 2);
1614
1615 ObjPtr<mirror::Object> obj_ptr =
1616 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1617 MemberOffset member_offset(raw_member_offset);
1618 ObjPtr<mirror::String> referred_string =
1619 obj_ptr->GetFieldObject<mirror::String,
1620 kVerifyNone,
1621 kWithoutReadBarrier,
1622 /* kIsVolatile= */ false>(member_offset);
1623 DCHECK(referred_string != nullptr);
1624
1625 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001626 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001627 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1628 /* kCheckTransaction= */ false,
1629 kVerifyNone,
1630 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001631 } else if (!use_preresolved_strings) {
1632 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1633 /* kCheckTransaction= */ false,
1634 kVerifyNone,
1635 /* kIsVolatile= */ false>(
1636 member_offset,
1637 intern_table->InternStrong(referred_string));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001638 }
1639 }
1640 }
1641}
1642
Chris Wailesfbeef462018-10-19 14:16:35 -07001643void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001644 // Iterate over the string reference offsets stored in the image and intern
1645 // the strings they point to.
1646 ScopedTrace timing("AppImage:InternString");
1647
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001648 Runtime* const runtime = Runtime::Current();
1649 InternTable* const intern_table = runtime->GetInternTable();
1650
1651 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001652
1653 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1654 // for faster lookup.
1655 // TODO: Optimize with a bitmap or bloom filter
1656 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001657 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001658 REQUIRES_SHARED(Locks::mutator_lock_)
1659 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001660 const size_t non_boot_image_strings = intern_table->CountInterns(
1661 /*visit_boot_images=*/false,
1662 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001663 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001664 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1665 // Visit the smaller of the two sets to compute the intersection.
1666 if (interns.size() < non_boot_image_strings) {
1667 for (auto it = interns.begin(); it != interns.end(); ) {
1668 ObjPtr<mirror::String> string = it->Read();
1669 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1670 if (existing == nullptr) {
1671 existing = intern_table->LookupStrongLocked(string);
1672 }
1673 if (existing != nullptr) {
1674 intern_remap.Put(string.Ptr(), existing.Ptr());
1675 it = interns.erase(it);
1676 } else {
1677 ++it;
1678 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001679 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001680 } else {
1681 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1682 REQUIRES_SHARED(Locks::mutator_lock_)
1683 REQUIRES(Locks::intern_table_lock_) {
1684 auto it = interns.find(root);
1685 if (it != interns.end()) {
1686 ObjPtr<mirror::String> existing = root.Read();
1687 intern_remap.Put(it->Read(), existing.Ptr());
1688 it = interns.erase(it);
1689 }
1690 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1691 }
1692 // Sanity check to ensure correctness.
1693 if (kIsDebugBuild) {
1694 for (GcRoot<mirror::String>& root : interns) {
1695 ObjPtr<mirror::String> string = root.Read();
1696 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1697 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001698 }
1699 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001700 };
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001701
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001702 bool update_intern_strings;
1703 if (load_startup_cache) {
Mathieu Chartiere23b3882019-02-14 07:35:43 -08001704 VLOG(image) << "AppImage:load_startup_cache";
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001705 // Only add the intern table if we are using the startup cache. Otherwise,
1706 // UpdateInternStrings adds the strings to the intern table.
1707 intern_table->AddImageStringsToTable(space, func);
1708 update_intern_strings = kIsDebugBuild || !intern_remap.empty();
1709 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
1710 } else {
1711 update_intern_strings = true;
1712 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001713
1714 // For debug builds, always run the code below to get coverage.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001715 if (update_intern_strings) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001716 // Slow path case is when there are conflicting intern strings to fix up.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001717 UpdateInternStrings(space, /*use_preresolved_strings=*/ load_startup_cache, intern_remap);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001718 }
1719}
1720
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001721static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1722 const char* location,
1723 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001724 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001725 DCHECK(error_msg != nullptr);
1726 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001727 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001728 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001729 return std::unique_ptr<const DexFile>();
1730 }
1731 std::string inner_error_msg;
1732 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1733 if (dex_file == nullptr) {
1734 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1735 location,
1736 oat_file->GetLocation().c_str(),
1737 inner_error_msg.c_str());
1738 return std::unique_ptr<const DexFile>();
1739 }
1740
1741 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1742 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1743 location,
1744 dex_file->GetLocationChecksum(),
1745 oat_dex_file->GetDexFileLocationChecksum());
1746 return std::unique_ptr<const DexFile>();
1747 }
1748 return dex_file;
1749}
1750
1751bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1752 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1753 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001754 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001755 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001756 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001757 DCHECK(dex_caches_object != nullptr);
1758 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1759 dex_caches_object->AsObjectArray<mirror::DexCache>();
1760 const OatFile* oat_file = space->GetOatFile();
1761 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001762 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001763 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1764 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1765 dex_file_location.c_str(),
1766 error_msg);
1767 if (dex_file == nullptr) {
1768 return false;
1769 }
1770 dex_cache->SetDexFile(dex_file.get());
1771 out_dex_files->push_back(std::move(dex_file));
1772 }
1773 return true;
1774}
1775
Andreas Gampe0793bec2016-12-01 11:37:33 -08001776// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1777// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001778class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001779 public:
1780 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1781 REQUIRES_SHARED(Locks::mutator_lock_) {
1782 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001783 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1784 DCHECK(obj != nullptr);
1785 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1786 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1787 if (obj->IsClass()) {
1788 auto klass = obj->AsClass();
1789 for (ArtField& field : klass->GetIFields()) {
1790 CHECK_EQ(field.GetDeclaringClass(), klass);
1791 }
1792 for (ArtField& field : klass->GetSFields()) {
1793 CHECK_EQ(field.GetDeclaringClass(), klass);
1794 }
1795 const auto pointer_size = isc.pointer_size_;
1796 for (auto& m : klass->GetMethods(pointer_size)) {
1797 isc.SanityCheckArtMethod(&m, klass);
1798 }
1799 auto* vtable = klass->GetVTable();
1800 if (vtable != nullptr) {
1801 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1802 }
1803 if (klass->ShouldHaveImt()) {
1804 ImTable* imt = klass->GetImt(pointer_size);
1805 for (size_t i = 0; i < ImTable::kSize; ++i) {
1806 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1807 }
1808 }
1809 if (klass->ShouldHaveEmbeddedVTable()) {
1810 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1811 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1812 }
1813 }
1814 mirror::IfTable* iftable = klass->GetIfTable();
1815 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1816 if (iftable->GetMethodArrayCount(i) > 0) {
1817 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1818 }
1819 }
1820 }
1821 };
1822 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001823 }
1824
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001825 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1826 ClassLinker* class_linker,
1827 mirror::MethodDexCacheType* arr,
1828 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001829 REQUIRES_SHARED(Locks::mutator_lock_) {
1830 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001831 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001832 }
1833
Andreas Gampe0793bec2016-12-01 11:37:33 -08001834 private:
1835 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1836 : spaces_(heap->GetBootImageSpaces()),
1837 pointer_size_(class_linker->GetImagePointerSize()) {
1838 space_begin_.reserve(spaces_.size());
1839 method_sections_.reserve(spaces_.size());
1840 runtime_method_sections_.reserve(spaces_.size());
1841 for (gc::space::ImageSpace* space : spaces_) {
1842 space_begin_.push_back(space->Begin());
1843 auto& header = space->GetImageHeader();
1844 method_sections_.push_back(&header.GetMethodsSection());
1845 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1846 }
1847 }
1848
1849 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1850 REQUIRES_SHARED(Locks::mutator_lock_) {
1851 if (m->IsRuntimeMethod()) {
1852 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1853 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1854 } else if (m->IsCopied()) {
1855 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1856 } else if (expected_class != nullptr) {
1857 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1858 }
1859 if (!spaces_.empty()) {
1860 bool contains = false;
1861 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1862 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1863 contains = method_sections_[i]->Contains(offset) ||
1864 runtime_method_sections_[i]->Contains(offset);
1865 }
1866 CHECK(contains) << m << " not found";
1867 }
1868 }
1869
1870 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1871 ObjPtr<mirror::Class> expected_class)
1872 REQUIRES_SHARED(Locks::mutator_lock_) {
1873 CHECK(arr != nullptr);
1874 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1875 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1876 // expected_class == null means we are a dex cache.
1877 if (expected_class != nullptr) {
1878 CHECK(method != nullptr);
1879 }
1880 if (method != nullptr) {
1881 SanityCheckArtMethod(method, expected_class);
1882 }
1883 }
1884 }
1885
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001886 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001887 REQUIRES_SHARED(Locks::mutator_lock_) {
1888 CHECK_EQ(arr != nullptr, size != 0u);
1889 if (arr != nullptr) {
1890 bool contains = false;
1891 for (auto space : spaces_) {
1892 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001893 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001894 contains = true;
1895 break;
1896 }
1897 }
1898 CHECK(contains);
1899 }
1900 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001901 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1902 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001903 // expected_class == null means we are a dex cache.
1904 if (method != nullptr) {
1905 SanityCheckArtMethod(method, nullptr);
1906 }
1907 }
1908 }
1909
1910 const std::vector<gc::space::ImageSpace*>& spaces_;
1911 const PointerSize pointer_size_;
1912
1913 // Cached sections from the spaces.
1914 std::vector<const uint8_t*> space_begin_;
1915 std::vector<const ImageSection*> method_sections_;
1916 std::vector<const ImageSection*> runtime_method_sections_;
1917};
1918
Andreas Gampebe7af222017-07-25 09:57:28 -07001919static void VerifyAppImage(const ImageHeader& header,
1920 const Handle<mirror::ClassLoader>& class_loader,
1921 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1922 ClassTable* class_table, gc::space::ImageSpace* space)
1923 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001924 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1925 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1926 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1927 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1928 << mirror::Class::PrettyClass(klass);
1929 }
1930 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001931 {
1932 // Verify that all direct interfaces of classes in the class table are also resolved.
1933 std::vector<ObjPtr<mirror::Class>> classes;
1934 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1935 REQUIRES_SHARED(Locks::mutator_lock_) {
1936 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1937 classes.push_back(klass);
1938 }
1939 return true;
1940 };
1941 class_table->Visit(verify_direct_interfaces_in_table);
1942 Thread* self = Thread::Current();
1943 for (ObjPtr<mirror::Class> klass : classes) {
1944 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1945 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1946 << klass->PrettyDescriptor() << " iface #" << i;
1947 }
1948 }
1949 }
1950 // Check that all non-primitive classes in dex caches are also in the class table.
1951 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1952 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1953 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1954 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1955 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1956 if (klass != nullptr && !klass->IsPrimitive()) {
1957 CHECK(class_table->Contains(klass))
1958 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1959 }
1960 }
1961 }
1962}
1963
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001964bool ClassLinker::AddImageSpace(
1965 gc::space::ImageSpace* space,
1966 Handle<mirror::ClassLoader> class_loader,
1967 jobjectArray dex_elements,
1968 const char* dex_location,
1969 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1970 std::string* error_msg) {
1971 DCHECK(out_dex_files != nullptr);
1972 DCHECK(error_msg != nullptr);
1973 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001974 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001975 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001976 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001977 DCHECK(dex_caches_object != nullptr);
1978 Runtime* const runtime = Runtime::Current();
1979 gc::Heap* const heap = runtime->GetHeap();
1980 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001981 // Check that the image is what we are expecting.
1982 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1983 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1984 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1985 image_pointer_size_);
1986 return false;
1987 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001988 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1989 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1990 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1991 expected_image_roots,
1992 header.GetImageRoots()->GetLength());
1993 return false;
1994 }
1995 StackHandleScope<3> hs(self);
1996 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1997 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1998 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1999 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002000 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002001 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2002 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002003 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002004 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002005 *error_msg = StringPrintf("Expected %d class roots but got %d",
2006 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002007 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002008 return false;
2009 }
2010 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002011 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2012 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2013 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002014 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2015 return false;
2016 }
2017 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002018 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002019 if (oat_file->GetOatHeader().GetDexFileCount() !=
2020 static_cast<uint32_t>(dex_caches->GetLength())) {
2021 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2022 "image";
2023 return false;
2024 }
2025
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002026 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002027 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2028 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002029 // TODO: Only store qualified paths.
2030 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002031 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002032 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2033 dex_file_location.c_str(),
2034 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002035 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002036 return false;
2037 }
2038
2039 if (app_image) {
2040 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2041 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002042 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002043 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002044 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002045 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002046 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002047 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002048 }
2049 }
2050 } else {
2051 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002052 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2053 this,
2054 dex_cache->GetResolvedMethods(),
2055 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002056 }
2057 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002058 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002059 }
2060 out_dex_files->push_back(std::move(dex_file));
2061 }
2062
2063 if (app_image) {
2064 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002065 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002066 // Check that the class loader resolves the same way as the ones in the image.
2067 // Image class loader [A][B][C][image dex files]
2068 // Class loader = [???][dex_elements][image dex files]
2069 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002070 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002071 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2072 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2073 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002074 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2075 *error_msg = "Unexpected BootClassLoader in app image";
2076 return false;
2077 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002078 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2079 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2080 // special case the comparison of dex files of the two class loaders, but then do full
2081 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002082 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002083 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002084 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2085 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2086 if (element != nullptr) {
2087 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002088 ObjPtr<mirror::String> name;
2089 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2090 loader_dex_file_names.push_back(name);
2091 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002092 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002093 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002094 std::string temp_error_msg;
2095 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2096 bool success = GetDexFileNames(
2097 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2098 if (success) {
2099 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2100 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2101 static_cast<size_t>(dex_caches->GetLength()));
2102 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2103 image_dex_file_names.resize(image_count);
2104 success = success && CompareDexFiles(image_dex_file_names,
2105 loader_dex_file_names,
2106 &temp_error_msg);
2107 success = success && CompareClassLoaders(soa,
2108 image_class_loader.Get(),
2109 class_loader.Get(),
2110 /*check_dex_file_names=*/ false,
2111 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002112 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002113 if (!success) {
2114 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2115 temp_error_msg.c_str());
2116 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002117 }
2118 }
2119
2120 if (kSanityCheckObjects) {
2121 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2122 auto* dex_cache = dex_caches->Get(i);
2123 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2124 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2125 if (field != nullptr) {
2126 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2127 }
2128 }
2129 }
2130 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002131 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002132 }
2133 }
2134
2135 // Set entry point to interpreter if in InterpretOnly mode.
2136 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002137 // Set image methods' entry point to interpreter.
2138 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2139 if (!method.IsRuntimeMethod()) {
2140 DCHECK(method.GetDeclaringClass() != nullptr);
2141 if (!method.IsNative() && !method.IsResolutionMethod()) {
2142 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2143 image_pointer_size_);
2144 }
2145 }
2146 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002147 }
2148
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002149 ClassTable* class_table = nullptr;
2150 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002151 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002152 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002153 }
2154 // If we have a class table section, read it and use it for verification in
2155 // UpdateAppImageClassLoadersAndDexCaches.
2156 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002157 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002158 const bool added_class_table = class_table_section.Size() > 0u;
2159 if (added_class_table) {
2160 const uint64_t start_time2 = NanoTime();
2161 size_t read_count = 0;
2162 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2163 /*make copy*/false,
2164 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002165 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002166 }
2167 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002168 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002169
2170 {
2171 ScopedTrace trace("AppImage:UpdateClassLoaders");
2172 // Update class loader and resolved strings. If added_class_table is false, the resolved
2173 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002174 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002175 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002176 // Note: We probably don't need the read barrier unless we copy the app image objects into
2177 // the region space.
2178 ObjPtr<mirror::Class> klass(root.Read());
2179 // Do not update class loader for boot image classes where the app image
2180 // class loader is only the initiating loader but not the defining loader.
2181 // Avoid read barrier since we are comparing against null.
2182 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2183 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2184 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002185 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002186 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002187
Vladimir Marko305c38b2018-02-14 11:50:07 +00002188 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002189 // Every class in the app image has initially SubtypeCheckInfo in the
2190 // Uninitialized state.
2191 //
2192 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2193 // after class initialization is complete. The app image ClassStatus as-is
2194 // are almost all ClassStatus::Initialized, and being in the
2195 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2196 //
2197 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2198 //
2199 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002200 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002201 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2202 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002203 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002204 }
2205 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002206 }
2207 if (!oat_file->GetBssGcRoots().empty()) {
2208 // Insert oat file to class table for visiting .bss GC roots.
2209 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002210 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002211
Mathieu Chartier69731002016-03-02 16:08:31 -08002212 if (added_class_table) {
2213 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2214 class_table->AddClassSet(std::move(temp_set));
2215 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002216
Mathieu Chartier69731002016-03-02 16:08:31 -08002217 if (kIsDebugBuild && app_image) {
2218 // This verification needs to happen after the classes have been added to the class loader.
2219 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002220 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002221 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002222 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002223
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002224 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002225 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002226}
2227
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002228bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002229 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2230 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002231}
2232
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002233void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002234 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2235 // enabling tracing requires the mutator lock, there are no race conditions here.
2236 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002237 Thread* const self = Thread::Current();
2238 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002239 if (kUseReadBarrier) {
2240 // We do not track new roots for CC.
2241 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2242 kVisitRootFlagClearRootLog |
2243 kVisitRootFlagStartLoggingNewRoots |
2244 kVisitRootFlagStopLoggingNewRoots));
2245 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002246 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002247 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2248 // There is 3 GC cases to handle:
2249 // Non moving concurrent:
2250 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002251 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002252 //
2253 // Moving non-concurrent:
2254 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2255 // To prevent missing roots, this case needs to ensure that there is no
2256 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2257 // class which is in the class table.
2258 //
2259 // Moving concurrent:
2260 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2261 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002262 //
2263 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2264 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2265 // these objects.
2266 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002267 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002268 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002269 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002270 for (const ClassLoaderData& data : class_loaders_) {
2271 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2272 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2273 }
2274 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002275 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002276 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002277 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002278 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002279 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002280 // Concurrent moving GC marked new roots through the to-space invariant.
2281 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002282 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002283 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2284 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2285 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2286 if (old_ref != nullptr) {
2287 DCHECK(old_ref->IsClass());
2288 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2289 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2290 // Concurrent moving GC marked new roots through the to-space invariant.
2291 CHECK_EQ(new_ref, old_ref);
2292 }
2293 }
2294 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002295 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002296 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002297 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002298 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002299 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002300 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002301 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002302 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002303 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002304 }
2305 // We deliberately ignore the class roots in the image since we
2306 // handle image roots by using the MS/CMS rescanning of dirty cards.
2307}
2308
Brian Carlstroma663ea52011-08-19 23:33:41 -07002309// Keep in sync with InitCallback. Anything we visit, we need to
2310// reinit references to when reinitializing a ClassLinker from a
2311// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002312void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002313 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002314 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002315 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2316 // unloading if we are marking roots.
2317 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002318}
2319
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002320class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2321 public:
2322 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2323 : visitor_(visitor),
2324 done_(false) {}
2325
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002326 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002327 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002328 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002329 if (!done_ && class_table != nullptr) {
2330 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2331 if (!class_table->Visit(visitor)) {
2332 // If the visitor ClassTable returns false it means that we don't need to continue.
2333 done_ = true;
2334 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002335 }
2336 }
2337
2338 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002339 // Class visitor that limits the class visits from a ClassTable to the classes with
2340 // the provided defining class loader. This filter is used to avoid multiple visits
2341 // of the same class which can be recorded for multiple initiating class loaders.
2342 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2343 public:
2344 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2345 ClassVisitor* visitor)
2346 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2347
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002348 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002349 if (klass->GetClassLoader() != defining_class_loader_) {
2350 return true;
2351 }
2352 return (*visitor_)(klass);
2353 }
2354
2355 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2356 ClassVisitor* const visitor_;
2357 };
2358
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002359 ClassVisitor* const visitor_;
2360 // If done is true then we don't need to do any more visiting.
2361 bool done_;
2362};
2363
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002364void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002365 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002366 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2367 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002368 }
2369}
2370
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002371void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002372 Thread* const self = Thread::Current();
2373 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2374 // Not safe to have thread suspension when we are holding a lock.
2375 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002376 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002377 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002378 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002379 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002380 }
2381}
2382
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002383class GetClassesInToVector : public ClassVisitor {
2384 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002385 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002386 classes_.push_back(klass);
2387 return true;
2388 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002389 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002390};
2391
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002392class GetClassInToObjectArray : public ClassVisitor {
2393 public:
2394 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2395 : arr_(arr), index_(0) {}
2396
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002397 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002398 ++index_;
2399 if (index_ <= arr_->GetLength()) {
2400 arr_->Set(index_ - 1, klass);
2401 return true;
2402 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002403 return false;
2404 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002405
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002406 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002407 return index_ <= arr_->GetLength();
2408 }
2409
2410 private:
2411 mirror::ObjectArray<mirror::Class>* const arr_;
2412 int32_t index_;
2413};
2414
2415void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002416 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2417 // is avoiding duplicates.
2418 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002419 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002420 GetClassesInToVector accumulator;
2421 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002422 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002423 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002424 return;
2425 }
2426 }
2427 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002428 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002429 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002430 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002431 // We size the array assuming classes won't be added to the class table during the visit.
2432 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002433 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002434 size_t class_table_size;
2435 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002436 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002437 // Add 100 in case new classes get loaded when we are filling in the object array.
2438 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002439 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002440 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002441 classes.Assign(
2442 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002443 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002444 GetClassInToObjectArray accumulator(classes.Get());
2445 VisitClasses(&accumulator);
2446 if (accumulator.Succeeded()) {
2447 break;
2448 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002449 }
2450 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2451 // If the class table shrank during creation of the clases array we expect null elements. If
2452 // the class table grew then the loop repeats. If classes are created after the loop has
2453 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002454 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002455 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002456 return;
2457 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002458 }
2459 }
2460}
2461
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002462ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002463 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002464 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002465 // CHA unloading analysis is not needed. No negative consequences are expected because
2466 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002467 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002468 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002469 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002470}
2471
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002472void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002473 Runtime* const runtime = Runtime::Current();
2474 JavaVMExt* const vm = runtime->GetJavaVM();
2475 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002476 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002477 if (runtime->GetJit() != nullptr) {
2478 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2479 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002480 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002481 code_cache->RemoveMethodsIn(self, *data.allocator);
2482 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002483 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002484 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002485 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002486 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002487 // Cleanup references to single implementation ArtMethods that will be deleted.
2488 if (cleanup_cha) {
2489 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2490 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2491 }
2492
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002493 delete data.allocator;
2494 delete data.class_table;
2495}
2496
Vladimir Markobcf17522018-06-01 13:14:32 +01002497ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2498 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002499 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002500 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2501 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002502}
2503
Vladimir Markobcf17522018-06-01 13:14:32 +01002504ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2505 Thread* self,
2506 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002507 StackHandleScope<1> hs(self);
2508 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002509 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002510 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002511 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002512 self->AssertPendingOOMException();
2513 return nullptr;
2514 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002515 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002516 if (location == nullptr) {
2517 self->AssertPendingOOMException();
2518 return nullptr;
2519 }
2520 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002521 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002522}
2523
Vladimir Markobcf17522018-06-01 13:14:32 +01002524ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2525 const DexFile& dex_file,
2526 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002527 ObjPtr<mirror::String> location = nullptr;
2528 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002529 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002530 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002531 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002532 mirror::DexCache::InitializeDexCache(self,
2533 dex_cache,
2534 location,
2535 &dex_file,
2536 linear_alloc,
2537 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002538 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002539 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002540}
2541
Roland Levillain0e840272018-08-23 19:55:30 +01002542template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002543ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2544 ObjPtr<mirror::Class> java_lang_Class,
2545 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002546 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002547 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002548 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002549 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002550 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2551 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002552 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002553 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002554 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002555 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002556 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002557}
2558
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002559ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002560 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002561}
2562
Roland Levillain0e840272018-08-23 19:55:30 +01002563ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2564 ObjPtr<mirror::Class> java_lang_Class) {
2565 // We make this class non-movable for the unlikely case where it were to be
2566 // moved by a sticky-bit (minor) collection when using the Generational
2567 // Concurrent Copying (CC) collector, potentially creating a stale reference
2568 // in the `klass_` field of one of its instances allocated in the Large-Object
2569 // Space (LOS) -- see the comment about the dirty card scanning logic in
2570 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002571 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002572 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2573}
2574
Vladimir Markobcf17522018-06-01 13:14:32 +01002575ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002576 Thread* self,
2577 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002578 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002579 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002580}
2581
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002582ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2583 const char* descriptor,
2584 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002585 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002586 if (kIsDebugBuild) {
2587 StackHandleScope<1> hs(self);
2588 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2589 Thread::PoisonObjectPointersIfDebug();
2590 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002591
2592 // For temporary classes we must wait for them to be retired.
2593 if (init_done_ && klass->IsTemp()) {
2594 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002595 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002596 ThrowEarlierClassFailure(klass);
2597 return nullptr;
2598 }
2599 StackHandleScope<1> hs(self);
2600 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2601 ObjectLock<mirror::Class> lock(self, h_class);
2602 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002603 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002604 lock.WaitIgnoringInterrupts();
2605 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002606 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002607 ThrowEarlierClassFailure(h_class.Get());
2608 return nullptr;
2609 }
2610 CHECK(h_class->IsRetired());
2611 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002612 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002613 }
2614
Brian Carlstromaded5f72011-10-07 17:15:04 -07002615 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002616 size_t index = 0;
2617 // Maximum number of yield iterations until we start sleeping.
2618 static const size_t kNumYieldIterations = 1000;
2619 // How long each sleep is in us.
2620 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002621 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002622 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002623 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002624 {
2625 ObjectTryLock<mirror::Class> lock(self, h_class);
2626 // Can not use a monitor wait here since it may block when returning and deadlock if another
2627 // thread has locked klass.
2628 if (lock.Acquired()) {
2629 // Check for circular dependencies between classes, the lock is required for SetStatus.
2630 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2631 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002632 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002633 return nullptr;
2634 }
2635 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002636 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002637 {
2638 // Handle wrapper deals with klass moving.
2639 ScopedThreadSuspension sts(self, kSuspended);
2640 if (index < kNumYieldIterations) {
2641 sched_yield();
2642 } else {
2643 usleep(kSleepDurationUS);
2644 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002646 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002647 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002648
Vladimir Marko72ab6842017-01-20 19:32:50 +00002649 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002650 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002651 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 }
2653 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002654 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002655 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002656 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002657}
2658
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002659using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002660
2661// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002662ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002663 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002664 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002665 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002666 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002667 return ClassPathEntry(dex_file, dex_class_def);
2668 }
2669 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002670 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002671}
2672
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002673bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2674 Thread* self,
2675 const char* descriptor,
2676 size_t hash,
2677 Handle<mirror::ClassLoader> class_loader,
2678 /*out*/ ObjPtr<mirror::Class>* result) {
2679 ArtField* field =
2680 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2681 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2682 if (raw_shared_libraries == nullptr) {
2683 return true;
2684 }
2685
2686 StackHandleScope<2> hs(self);
2687 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2688 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2689 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2690 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2691 temp_loader.Assign(shared_libraries->Get(i));
2692 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2693 return false; // One of the shared libraries is not supported.
2694 }
2695 if (*result != nullptr) {
2696 return true; // Found the class up the chain.
2697 }
2698 }
2699 return true;
2700}
2701
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002702bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2703 Thread* self,
2704 const char* descriptor,
2705 size_t hash,
2706 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002707 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002708 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002709 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002710 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002711 return true;
2712 }
2713
David Brazdil05909d82018-12-06 16:25:16 +00002714 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002715 // For regular path or dex class loader the search order is:
2716 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002717 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002718 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002719
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2721 StackHandleScope<1> hs(self);
2722 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2723 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2724 return false; // One of the parents is not supported.
2725 }
2726 if (*result != nullptr) {
2727 return true; // Found the class up the chain.
2728 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002729
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002730 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2731 return false; // One of the shared library loader is not supported.
2732 }
2733 if (*result != nullptr) {
2734 return true; // Found the class in a shared library.
2735 }
2736
Calin Juravlecdd49122017-07-05 20:09:53 -07002737 // Search the current class loader classpath.
2738 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002739 return true;
2740 }
2741
Calin Juravlecdd49122017-07-05 20:09:53 -07002742 if (IsDelegateLastClassLoader(soa, class_loader)) {
2743 // For delegate last, the search order is:
2744 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002745 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002746 // - class loader dex files
2747 // - parent
2748 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2749 if (*result != nullptr) {
2750 return true; // The class is part of the boot class path.
2751 }
2752
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002753 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2754 return false; // One of the shared library loader is not supported.
2755 }
2756 if (*result != nullptr) {
2757 return true; // Found the class in a shared library.
2758 }
2759
Calin Juravlecdd49122017-07-05 20:09:53 -07002760 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2761 if (*result != nullptr) {
2762 return true; // Found the class in the current class loader
2763 }
2764
2765 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2766 StackHandleScope<1> hs(self);
2767 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2768 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2769 }
2770
2771 // Unsupported class loader.
2772 *result = nullptr;
2773 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002774}
2775
2776// Finds the class in the boot class loader.
2777// If the class is found the method returns the resolved class. Otherwise it returns null.
2778ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2779 const char* descriptor,
2780 size_t hash) {
2781 ObjPtr<mirror::Class> result = nullptr;
2782 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2783 if (pair.second != nullptr) {
2784 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2785 if (klass != nullptr) {
2786 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002787 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002788 result = DefineClass(self,
2789 descriptor,
2790 hash,
2791 ScopedNullHandle<mirror::ClassLoader>(),
2792 *pair.first,
2793 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002794 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002795 if (result == nullptr) {
2796 CHECK(self->IsExceptionPending()) << descriptor;
2797 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002798 }
2799 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002800 return result;
2801}
Andreas Gampef865ea92015-04-13 22:14:19 -07002802
Calin Juravle415dc3d2017-06-28 11:03:12 -07002803ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2804 ScopedObjectAccessAlreadyRunnable& soa,
2805 const char* descriptor,
2806 size_t hash,
2807 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002808 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2809 IsInMemoryDexClassLoader(soa, class_loader) ||
2810 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002811 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002812
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002813 ObjPtr<mirror::Class> ret;
2814 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002815 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002816 if (dex_class_def != nullptr) {
2817 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2818 descriptor,
2819 hash,
2820 class_loader,
2821 *cp_dex_file,
2822 *dex_class_def);
2823 if (klass == nullptr) {
2824 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2825 soa.Self()->ClearException();
2826 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002827 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002828 ret = klass;
2829 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002830 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002831 return true; // Continue with the next DexFile.
2832 };
2833
2834 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2835 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002836}
2837
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002838ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2839 const char* descriptor,
2840 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002841 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002842 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002843 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002844 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002845 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002846 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2847 // for primitive classes that aren't backed by dex files.
2848 return FindPrimitiveClass(descriptor[0]);
2849 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002850 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002851 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002852 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002853 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002854 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002855 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002856 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002857 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002858 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002859 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002860 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002861 return DefineClass(self,
2862 descriptor,
2863 hash,
2864 ScopedNullHandle<mirror::ClassLoader>(),
2865 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002866 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002867 } else {
2868 // The boot class loader is searched ahead of the application class loader, failures are
2869 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2870 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002871 ObjPtr<mirror::Throwable> pre_allocated =
2872 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002873 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002874 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002875 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002876 }
2877 ObjPtr<mirror::Class> result_ptr;
2878 bool descriptor_equals;
2879 if (descriptor[0] == '[') {
2880 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2881 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2882 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2883 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002884 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002885 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002886 bool known_hierarchy =
2887 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2888 if (result_ptr != nullptr) {
2889 // The chain was understood and we found the class. We still need to add the class to
2890 // the class table to protect from racy programs that can try and redefine the path list
2891 // which would change the Class<?> returned for subsequent evaluation of const-class.
2892 DCHECK(known_hierarchy);
2893 DCHECK(result_ptr->DescriptorEquals(descriptor));
2894 descriptor_equals = true;
2895 } else {
2896 // Either the chain wasn't understood or the class wasn't found.
2897 //
2898 // If the chain was understood but we did not find the class, let the Java-side
2899 // rediscover all this and throw the exception with the right stack trace. Note that
2900 // the Java-side could still succeed for racy programs if another thread is actively
2901 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002902
Alex Light185a4612018-10-04 15:54:25 -07002903 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002904 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002905 // Oops, we can't call into java so we can't run actual class-loader code.
2906 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002907 ObjPtr<mirror::Throwable> pre_allocated =
2908 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2909 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002910 return nullptr;
2911 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002912
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002913 // Inlined DescriptorToDot(descriptor) with extra validation.
2914 //
2915 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2916 // the DescriptorEquals() check below and give a confusing error message. For example,
2917 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2918 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2919 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2920 size_t descriptor_length = strlen(descriptor);
2921 if (UNLIKELY(descriptor[0] != 'L') ||
2922 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2923 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2924 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2925 return nullptr;
2926 }
2927 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2928 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2929
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002930 ScopedLocalRef<jobject> class_loader_object(
2931 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002932 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2933 {
2934 ScopedThreadStateChange tsc(self, kNative);
2935 ScopedLocalRef<jobject> class_name_object(
2936 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2937 if (class_name_object.get() == nullptr) {
2938 DCHECK(self->IsExceptionPending()); // OOME.
2939 return nullptr;
2940 }
2941 CHECK(class_loader_object.get() != nullptr);
2942 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2943 WellKnownClasses::java_lang_ClassLoader_loadClass,
2944 class_name_object.get()));
2945 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002946 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002947 // broken loader - throw NPE to be compatible with Dalvik
2948 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2949 class_name_string.c_str()).c_str());
2950 return nullptr;
2951 }
2952 result_ptr = soa.Decode<mirror::Class>(result.get());
2953 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002954 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002955 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002956 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002957
2958 if (self->IsExceptionPending()) {
2959 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2960 // However, to comply with the RI behavior, first check if another thread succeeded.
2961 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2962 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2963 self->ClearException();
2964 return EnsureResolved(self, descriptor, result_ptr);
2965 }
2966 return nullptr;
2967 }
2968
2969 // Try to insert the class to the class table, checking for mismatch.
2970 ObjPtr<mirror::Class> old;
2971 {
2972 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2973 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2974 old = class_table->Lookup(descriptor, hash);
2975 if (old == nullptr) {
2976 old = result_ptr; // For the comparison below, after releasing the lock.
2977 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002978 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002979 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002980 } // else throw below, after releasing the lock.
2981 }
2982 }
2983 if (UNLIKELY(old != result_ptr)) {
2984 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2985 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2986 mirror::Class* loader_class = class_loader->GetClass();
2987 const char* loader_class_name =
2988 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2989 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2990 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2991 << DescriptorToDot(descriptor) << "\").";
2992 return EnsureResolved(self, descriptor, old);
2993 }
2994 if (UNLIKELY(!descriptor_equals)) {
2995 std::string result_storage;
2996 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2997 std::string loader_storage;
2998 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2999 ThrowNoClassDefFoundError(
3000 "Initiating class loader of type %s returned class %s instead of %s.",
3001 DescriptorToDot(loader_class_name).c_str(),
3002 DescriptorToDot(result_name).c_str(),
3003 DescriptorToDot(descriptor).c_str());
3004 return nullptr;
3005 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003006 // Success.
3007 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003008}
3009
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003010ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3011 const char* descriptor,
3012 size_t hash,
3013 Handle<mirror::ClassLoader> class_loader,
3014 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003015 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003016 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003017 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003018
Brian Carlstromaded5f72011-10-07 17:15:04 -07003019 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003020 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003021 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003022 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003023 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003024 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003025 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003026 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003027 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003028 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003029 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003030 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003031 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003032 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003033 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003034 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003035 }
3036
Alex Lighte9f61032018-09-24 16:04:51 -07003037 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3038 // code to be executed. We put it up here so we can avoid all the allocations associated with
3039 // creating the class. This can happen with (eg) jit threads.
3040 if (!self->CanLoadClasses()) {
3041 // Make sure we don't try to load anything, potentially causing an infinite loop.
3042 ObjPtr<mirror::Throwable> pre_allocated =
3043 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3044 self->SetException(pre_allocated);
3045 return nullptr;
3046 }
3047
Andreas Gampefa4333d2017-02-14 11:10:34 -08003048 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003049 // Allocate a class with the status of not ready.
3050 // Interface object should get the right size here. Regular class will
3051 // figure out the right size later and be replaced with one of the right
3052 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003053 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003054 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003055 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003056 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003057 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003058 }
Alex Lightb0f11922017-01-23 14:25:17 -08003059 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3060 // nothing.
3061 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003062 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003063 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3064 // will only be called once.
3065 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3066 klass,
3067 class_loader,
3068 dex_file,
3069 dex_class_def,
3070 &new_dex_file,
3071 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003072 // Check to see if an exception happened during runtime callbacks. Return if so.
3073 if (self->IsExceptionPending()) {
3074 return nullptr;
3075 }
Alex Lightb0f11922017-01-23 14:25:17 -08003076 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003077 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003078 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003079 return nullptr;
3080 }
3081 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003082 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003083
Jeff Hao848f70a2014-01-15 13:49:50 -08003084 // Mark the string class by setting its access flag.
3085 if (UNLIKELY(!init_done_)) {
3086 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3087 klass->SetStringClass();
3088 }
3089 }
3090
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003091 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003092 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003093 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003094 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003095
Mathieu Chartier590fee92013-09-13 13:46:47 -07003096 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003097 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003098 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003099 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3100 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003101 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003102 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003103
Mathieu Chartierc7853442015-03-27 14:35:38 -07003104 // Load the fields and other things after we are inserted in the table. This is so that we don't
3105 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3106 // other reason is that the field roots are only visited from the class table. So we need to be
3107 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003108 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003109 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003110 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003111 // An exception occured during load, set status to erroneous while holding klass' lock in case
3112 // notification is necessary.
3113 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003114 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003115 }
3116 return nullptr;
3117 }
3118
Brian Carlstromaded5f72011-10-07 17:15:04 -07003119 // Finish loading (if necessary) by finding parents
3120 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003121 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003122 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003123 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003124 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003125 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003126 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003127 }
3128 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003129
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003130 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003131 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003132 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003133
Brian Carlstromaded5f72011-10-07 17:15:04 -07003134 // Link the class (if necessary)
3135 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003136 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003137 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003138
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003139 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003140 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003141 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003142 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003143 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003144 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003145 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003146 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003147 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003148 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003149 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003150
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003151 // Instrumentation may have updated entrypoints for all methods of all
3152 // classes. However it could not update methods of this class while we
3153 // were loading it. Now the class is resolved, we can update entrypoints
3154 // as required by instrumentation.
3155 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3156 // We must be in the kRunnable state to prevent instrumentation from
3157 // suspending all threads to update entrypoints while we are doing it
3158 // for this class.
3159 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003160 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003161 }
3162
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003163 /*
3164 * We send CLASS_PREPARE events to the debugger from here. The
3165 * definition of "preparation" is creating the static fields for a
3166 * class and initializing them to the standard default values, but not
3167 * executing any code (that comes later, during "initialization").
3168 *
3169 * We did the static preparation in LinkClass.
3170 *
3171 * The class has been prepared and resolved but possibly not yet verified
3172 * at this point.
3173 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003174 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003175
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003176 // Notify native debugger of the new class and its layout.
3177 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3178
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003179 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003180}
3181
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003182uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003183 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003184 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003185 size_t num_8 = 0;
3186 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003187 size_t num_32 = 0;
3188 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003189 ClassAccessor accessor(dex_file, dex_class_def);
3190 // We allow duplicate definitions of the same field in a class_data_item
3191 // but ignore the repeated indexes here, b/21868015.
3192 uint32_t last_field_idx = dex::kDexNoIndex;
3193 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3194 uint32_t field_idx = field.GetIndex();
3195 // Ordering enforced by DexFileVerifier.
3196 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3197 if (UNLIKELY(field_idx == last_field_idx)) {
3198 continue;
3199 }
3200 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003201 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003202 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3203 char c = descriptor[0];
3204 switch (c) {
3205 case 'L':
3206 case '[':
3207 num_ref++;
3208 break;
3209 case 'J':
3210 case 'D':
3211 num_64++;
3212 break;
3213 case 'I':
3214 case 'F':
3215 num_32++;
3216 break;
3217 case 'S':
3218 case 'C':
3219 num_16++;
3220 break;
3221 case 'B':
3222 case 'Z':
3223 num_8++;
3224 break;
3225 default:
3226 LOG(FATAL) << "Unknown descriptor: " << c;
3227 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003228 }
3229 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003230 return mirror::Class::ComputeClassSize(false,
3231 0,
3232 num_8,
3233 num_16,
3234 num_32,
3235 num_64,
3236 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003237 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003238}
3239
Alex Lightfc49fec2018-01-16 22:28:36 +00003240// Special case to get oat code without overwriting a trampoline.
3241const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003242 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003243 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003244 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003245 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003246 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3247 if (code != nullptr) {
3248 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003249 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003250 if (method->IsNative()) {
3251 // No code and native? Use generic trampoline.
3252 return GetQuickGenericJniStub();
3253 }
3254 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003255}
3256
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003257bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003258 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003259 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3260 return false;
3261 }
3262
Elliott Hughes956af0f2014-12-11 14:34:28 -08003263 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003264 return true;
3265 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003266
3267 Runtime* runtime = Runtime::Current();
3268 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3269 if (instr->InterpretOnly()) {
3270 return true;
3271 }
3272
3273 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3274 // Doing this check avoids doing compiled/interpreter transitions.
3275 return true;
3276 }
3277
Alex Light3dacdd62019-03-12 15:45:47 +00003278 if (Thread::Current()->IsForceInterpreter() ||
3279 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003280 // Force the use of interpreter when it is required by the debugger.
3281 return true;
3282 }
3283
Alex Light8f34aba2017-10-09 13:46:32 -07003284 if (Thread::Current()->IsAsyncExceptionPending()) {
3285 // Force use of interpreter to handle async-exceptions
3286 return true;
3287 }
3288
Alex Light2d441b12018-06-08 15:33:21 -07003289 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3290 const void* instr_target = instr->GetCodeForInvoke(method);
3291 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3292 return ShouldUseInterpreterEntrypoint(method, instr_target);
3293 }
3294
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003295 if (runtime->IsJavaDebuggable()) {
3296 // For simplicity, we ignore precompiled code and go to the interpreter
3297 // assuming we don't already have jitted code.
3298 // We could look at the oat file where `quick_code` is being defined,
3299 // and check whether it's been compiled debuggable, but we decided to
3300 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003301 jit::Jit* jit = Runtime::Current()->GetJit();
3302 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3303 }
3304
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003305 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003306 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003307 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003308 // since we want to JIT it (at first use) with extra stackmaps for native
3309 // debugging. We keep however all AOT code from the boot image,
3310 // since the JIT-at-first-use is blocking and would result in non-negligible
3311 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003312 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003313 }
3314
3315 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003316}
3317
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003318void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003319 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003320 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003321 if (klass->NumDirectMethods() == 0) {
3322 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003323 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003324 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003325 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003326 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003327 return; // OAT file unavailable.
3328 }
Ian Rogers19846512012-02-24 11:42:47 -08003329 }
Alex Light64ad14d2014-08-19 14:23:13 -07003330
Mathieu Chartierf8322842014-05-16 10:59:25 -07003331 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003332 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3333 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3334 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003335 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003336 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003337 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003338 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3339 klass->GetDexClassDefIndex(),
3340 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003341 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003342 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003343 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003344 if (!method->IsStatic()) {
3345 // Only update static methods.
3346 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003347 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003348 const void* quick_code = nullptr;
3349 if (has_oat_class) {
3350 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003351 quick_code = oat_method.GetQuickCode();
3352 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003353 // Check whether the method is native, in which case it's generic JNI.
3354 if (quick_code == nullptr && method->IsNative()) {
3355 quick_code = GetQuickGenericJniStub();
3356 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003357 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003358 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003359 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003360 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003361 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003362 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003363}
3364
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003365// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3366// method. Should only be called on non-invokable methods.
3367inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003368 DCHECK(method != nullptr);
3369 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003370 method->SetEntryPointFromQuickCompiledCodePtrSize(
3371 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3372 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003373}
3374
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003375static void LinkCode(ClassLinker* class_linker,
3376 ArtMethod* method,
3377 const OatFile::OatClass* oat_class,
3378 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003379 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003380 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003381 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003382 // The following code only applies to a non-compiler runtime.
3383 return;
3384 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003385 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003386 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003387 if (oat_class != nullptr) {
3388 // Every kind of method should at least get an invoke stub from the oat_method.
3389 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003390 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003391 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003392 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003393
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003394 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003395 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003396 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003397
Alex Light9139e002015-10-09 15:59:48 -07003398 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003399 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003400 return;
3401 }
Ian Rogers19846512012-02-24 11:42:47 -08003402
3403 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003404 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003405 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3406 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003407 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003408 } else if (quick_code == nullptr && method->IsNative()) {
3409 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003410 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003411 // Set entry point from compiled code if there's no code or in interpreter only mode.
3412 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003413 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003414
Ian Rogers62d6c772013-02-27 08:32:07 -08003415 if (method->IsNative()) {
3416 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003417 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003418
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003419 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003420 // We have a native method here without code. Then it should have either the generic JNI
3421 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3422 // TODO: this doesn't handle all the cases where trampolines may be installed.
3423 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003424 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3425 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003426 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003427 }
3428}
3429
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003430void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003431 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003432 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003433 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003434 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003435 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003436 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003437 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003438 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003439
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003440 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003441 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003442 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003443 klass->SetAccessFlags(access_flags);
3444 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003445 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003446 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003447
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003448 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003449 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003450}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003451
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003452LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3453 LinearAlloc* allocator,
3454 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003455 if (length == 0) {
3456 return nullptr;
3457 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003458 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3459 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3460 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003461 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003462 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003463 CHECK(ret != nullptr);
3464 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3465 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003466}
3467
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003468LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3469 LinearAlloc* allocator,
3470 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003471 if (length == 0) {
3472 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003473 }
Vladimir Marko14632852015-08-17 12:07:23 +01003474 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3475 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003476 const size_t storage_size =
3477 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003478 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003479 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003480 CHECK(ret != nullptr);
3481 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003482 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003483 }
3484 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003485}
3486
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003487LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003488 if (class_loader == nullptr) {
3489 return Runtime::Current()->GetLinearAlloc();
3490 }
3491 LinearAlloc* allocator = class_loader->GetAllocator();
3492 DCHECK(allocator != nullptr);
3493 return allocator;
3494}
3495
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003496LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003497 if (class_loader == nullptr) {
3498 return Runtime::Current()->GetLinearAlloc();
3499 }
3500 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3501 LinearAlloc* allocator = class_loader->GetAllocator();
3502 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003503 RegisterClassLoader(class_loader);
3504 allocator = class_loader->GetAllocator();
3505 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003506 }
3507 return allocator;
3508}
3509
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003510void ClassLinker::LoadClass(Thread* self,
3511 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003512 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003513 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003514 ClassAccessor accessor(dex_file,
3515 dex_class_def,
3516 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003517 if (!accessor.HasClassData()) {
3518 return;
3519 }
3520 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003521 {
3522 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3523 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003524 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003525 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003526 // We allow duplicate definitions of the same field in a class_data_item
3527 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003528 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003529 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3530 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003531 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003532 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3533 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003534 accessor.NumInstanceFields());
3535 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003536 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003537 uint32_t last_static_field_idx = 0u;
3538 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003539
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003540 // Methods
3541 bool has_oat_class = false;
3542 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3543 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3544 : OatFile::OatClass::Invalid();
3545 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3546 klass->SetMethodsPtr(
3547 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3548 accessor.NumDirectMethods(),
3549 accessor.NumVirtualMethods());
3550 size_t class_def_method_index = 0;
3551 uint32_t last_dex_method_index = dex::kDexNoIndex;
3552 size_t last_class_def_method_index = 0;
3553
3554 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3555 // methods needs to decode all of the fields.
3556 accessor.VisitFieldsAndMethods([&](
3557 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3558 uint32_t field_idx = field.GetIndex();
3559 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3560 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3561 LoadField(field, klass, &sfields->At(num_sfields));
3562 ++num_sfields;
3563 last_static_field_idx = field_idx;
3564 }
3565 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3566 uint32_t field_idx = field.GetIndex();
3567 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3568 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3569 LoadField(field, klass, &ifields->At(num_ifields));
3570 ++num_ifields;
3571 last_instance_field_idx = field_idx;
3572 }
3573 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3574 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3575 image_pointer_size_);
3576 LoadMethod(dex_file, method, klass, art_method);
3577 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3578 uint32_t it_method_index = method.GetIndex();
3579 if (last_dex_method_index == it_method_index) {
3580 // duplicate case
3581 art_method->SetMethodIndex(last_class_def_method_index);
3582 } else {
3583 art_method->SetMethodIndex(class_def_method_index);
3584 last_dex_method_index = it_method_index;
3585 last_class_def_method_index = class_def_method_index;
3586 }
3587 ++class_def_method_index;
3588 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3589 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3590 class_def_method_index - accessor.NumDirectMethods(),
3591 image_pointer_size_);
3592 LoadMethod(dex_file, method, klass, art_method);
3593 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3594 ++class_def_method_index;
3595 });
3596
3597 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003598 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003599 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3600 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3601 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003602 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3603 if (sfields != nullptr) {
3604 sfields->SetSize(num_sfields);
3605 }
3606 if (ifields != nullptr) {
3607 ifields->SetSize(num_ifields);
3608 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003609 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003610 // Set the field arrays.
3611 klass->SetSFieldsPtr(sfields);
3612 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003613 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003614 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003615 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003616 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003617 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003618 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003619}
3620
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003621void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003622 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003623 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003624 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003625 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003626 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003627
David Brazdil85865692018-10-30 17:26:20 +00003628 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3629 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003630}
3631
Mathieu Chartier268764d2016-09-13 12:09:38 -07003632void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003633 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003634 Handle<mirror::Class> klass,
3635 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003636 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003637 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003638 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003639
Mathieu Chartier268764d2016-09-13 12:09:38 -07003640 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003641 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003642 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003643 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003644
David Brazdil85865692018-10-30 17:26:20 +00003645 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3646 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003647
Ian Rogersdfb325e2013-10-30 01:00:44 -07003648 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003649 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003650 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3651 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003652 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003653 klass->SetFinalizable();
3654 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003655 std::string temp;
3656 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003657 // The Enum class declares a "final" finalize() method to prevent subclasses from
3658 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3659 // subclasses, so we exclude it here.
3660 // We also want to avoid setting the flag on Object, where we know that finalize() is
3661 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003662 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3663 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003664 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003665 }
3666 }
3667 }
3668 } else if (method_name[0] == '<') {
3669 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003670 bool is_init = (strcmp("<init>", method_name) == 0);
3671 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003672 if (UNLIKELY(!is_init && !is_clinit)) {
3673 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3674 } else {
3675 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3676 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003677 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003678 access_flags |= kAccConstructor;
3679 }
3680 }
3681 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003682 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3683 // Check if the native method is annotated with @FastNative or @CriticalNative.
3684 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3685 dex_file, dst->GetClassDef(), dex_method_idx);
3686 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003687 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003688 // Must be done after SetAccessFlags since IsAbstract depends on it.
3689 if (klass->IsInterface() && dst->IsAbstract()) {
3690 dst->CalculateAndSetImtIndex();
3691 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003692}
3693
Ian Rogers7b078e82014-09-10 14:44:24 -07003694void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003695 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003696 self,
3697 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003698 Runtime::Current()->GetLinearAlloc());
3699 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003700 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003701}
3702
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003703void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003704 ObjPtr<mirror::DexCache> dex_cache) {
3705 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003706 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003707 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003708 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003709}
3710
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003711void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003712 ObjPtr<mirror::DexCache> dex_cache,
3713 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003714 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003715 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003716 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003717 // For app images, the dex cache location may be a suffix of the dex file location since the
3718 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003719 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3720 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003721 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3722 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003723 // The following paths checks don't work on preopt when using boot dex files, where the dex
3724 // cache location is the one on device, and the dex_file's location is the one on host.
3725 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3726 CHECK_GE(dex_file_location.length(), dex_cache_length)
3727 << dex_cache_location << " " << dex_file.GetLocation();
3728 const std::string dex_file_suffix = dex_file_location.substr(
3729 dex_file_location.length() - dex_cache_length,
3730 dex_cache_length);
3731 // Example dex_cache location is SettingsProvider.apk and
3732 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3733 CHECK_EQ(dex_cache_location, dex_file_suffix);
3734 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003735 const OatFile* oat_file =
3736 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003737 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3738 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3739 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3740 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003741 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003742 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3743 DexCacheData data = *it;
3744 if (self->IsJWeakCleared(data.weak_root)) {
3745 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003746 it = dex_caches_.erase(it);
3747 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003748 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003749 it->dex_file->GetOatDexFile() != nullptr &&
3750 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003751 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003752 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003753 ++it;
3754 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003755 }
Vladimir Markob066d432018-01-03 13:14:37 +00003756 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003757 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003758 }
David Brazdila5c3a802019-03-08 14:59:41 +00003759 // Let hiddenapi assign a domain to the newly registered dex file.
3760 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3761
Vladimir Markocd556b02017-02-03 11:47:34 +00003762 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003763 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003764 DexCacheData data;
3765 data.weak_root = dex_cache_jweak;
3766 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003767 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003768 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003769 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003770 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3771 // path dex caches without an image.
3772 data.class_table->InsertStrongRoot(dex_cache);
3773 if (class_loader != nullptr) {
3774 // Since we added a strong root to the class table, do the write barrier as required for
3775 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003776 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003777 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003778 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003779}
3780
Vladimir Markocd556b02017-02-03 11:47:34 +00003781ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3782 return data.IsValid()
3783 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3784 : nullptr;
3785}
3786
3787ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3788 Thread* self,
3789 ObjPtr<mirror::DexCache> dex_cache,
3790 const DexCacheData& data,
3791 ObjPtr<mirror::ClassLoader> class_loader) {
3792 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3793 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3794 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3795 "Attempt to register dex file %s with multiple class loaders",
3796 data.dex_file->GetLocation().c_str());
3797 return nullptr;
3798 }
3799 return dex_cache;
3800}
3801
Alex Light07f06212017-06-01 14:01:43 -07003802void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3803 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003804 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003805 Thread* self = Thread::Current();
3806 StackHandleScope<2> hs(self);
3807 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3808 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3809 const DexFile* dex_file = dex_cache->GetDexFile();
3810 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3811 if (kIsDebugBuild) {
3812 DexCacheData old_data;
3813 {
3814 ReaderMutexLock mu(self, *Locks::dex_lock_);
3815 old_data = FindDexCacheDataLocked(*dex_file);
3816 }
3817 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3818 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3819 << "been registered on dex file " << dex_file->GetLocation();
3820 }
3821 ClassTable* table;
3822 {
3823 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3824 table = InsertClassTableForClassLoader(h_class_loader.Get());
3825 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003826 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3827 // a thread holding the dex lock and blocking on a condition variable regarding
3828 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003829 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003830 WriterMutexLock mu(self, *Locks::dex_lock_);
3831 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3832 table->InsertStrongRoot(h_dex_cache.Get());
3833 if (h_class_loader.Get() != nullptr) {
3834 // Since we added a strong root to the class table, do the write barrier as required for
3835 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003836 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003837 }
3838}
3839
Vladimir Markocd556b02017-02-03 11:47:34 +00003840ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3841 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003842 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003843 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003844 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003845 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003846 old_data = FindDexCacheDataLocked(dex_file);
3847 }
3848 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3849 if (old_dex_cache != nullptr) {
3850 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003851 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003852 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003853 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3854 DCHECK(linear_alloc != nullptr);
3855 ClassTable* table;
3856 {
3857 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3858 table = InsertClassTableForClassLoader(class_loader);
3859 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003860 // Don't alloc while holding the lock, since allocation may need to
3861 // suspend all threads and another thread may need the dex_lock_ to
3862 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003863 StackHandleScope<3> hs(self);
3864 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003865 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003866 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3867 self,
3868 dex_file)));
3869 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003870 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003871 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3872 // a thread holding the dex lock and blocking on a condition variable regarding
3873 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003874 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003875 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003876 old_data = FindDexCacheDataLocked(dex_file);
3877 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003878 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003879 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3880 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3881 // that the arrays are null.
3882 mirror::DexCache::InitializeDexCache(self,
3883 h_dex_cache.Get(),
3884 h_location.Get(),
3885 &dex_file,
3886 linear_alloc,
3887 image_pointer_size_);
3888 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003889 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003890 }
3891 if (old_dex_cache != nullptr) {
3892 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3893 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003894 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003895 self->ClearException();
3896 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3897 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3898 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003899 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003900 self->AssertPendingOOMException();
3901 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003902 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003903 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003904 if (h_class_loader.Get() != nullptr) {
3905 // Since we added a strong root to the class table, do the write barrier as required for
3906 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003907 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003908 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003909 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003910}
3911
Vladimir Markocd556b02017-02-03 11:47:34 +00003912bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003913 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003914 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003915}
3916
Vladimir Markocd556b02017-02-03 11:47:34 +00003917ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3918 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003919 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3920 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003921 if (dex_cache != nullptr) {
3922 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003923 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003924 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003925 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003926 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003927 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003928 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003929 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003930 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3931 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003932 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003933}
3934
Vladimir Markocd556b02017-02-03 11:47:34 +00003935ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3936 const DexFile* dex_file = dex_cache->GetDexFile();
3937 DCHECK(dex_file != nullptr);
3938 ReaderMutexLock mu(self, *Locks::dex_lock_);
3939 // Search assuming unique-ness of dex file.
3940 for (const DexCacheData& data : dex_caches_) {
3941 // Avoid decoding (and read barriers) other unrelated dex caches.
3942 if (data.dex_file == dex_file) {
3943 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3944 if (registered_dex_cache != nullptr) {
3945 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3946 return data.class_table;
3947 }
3948 }
3949 }
3950 return nullptr;
3951}
3952
3953ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3954 // Search assuming unique-ness of dex file.
3955 for (const DexCacheData& data : dex_caches_) {
3956 // Avoid decoding (and read barriers) other unrelated dex caches.
3957 if (data.dex_file == &dex_file) {
3958 return data;
3959 }
3960 }
3961 return DexCacheData();
3962}
3963
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003964ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003965 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003966 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003967 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003968 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003969 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003970 }
Ian Rogers1f539342012-10-03 21:09:42 -07003971 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003972 StackHandleScope<1> hs(self);
3973 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003974 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003975 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3976 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003977 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003978 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003979 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003980 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003981 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3982 h_class.Get(),
3983 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003984 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003985 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003986}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003987
Vladimir Marko02610552018-06-04 14:38:00 +01003988inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
3989 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
3990}
3991
Brian Carlstrombe977852011-07-19 14:54:54 -07003992// Create an array class (i.e. the class object for the array, not the
3993// array itself). "descriptor" looks like "[C" or "[[[[B" or
3994// "[Ljava/lang/String;".
3995//
3996// If "descriptor" refers to an array of primitives, look up the
3997// primitive type's internally-generated class object.
3998//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003999// "class_loader" is the class loader of the class that's referring to
4000// us. It's used to ensure that we're looking for the element type in
4001// the right context. It does NOT become the class loader for the
4002// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004003//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004004// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004005ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4006 const char* descriptor,
4007 size_t hash,
4008 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004009 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004010 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004011 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004012
4013 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4014 // code to be executed. We put it up here so we can avoid all the allocations associated with
4015 // creating the class. This can happen with (eg) jit threads.
4016 if (!self->CanLoadClasses()) {
4017 // Make sure we don't try to load anything, potentially causing an infinite loop.
4018 ObjPtr<mirror::Throwable> pre_allocated =
4019 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4020 self->SetException(pre_allocated);
4021 return nullptr;
4022 }
4023
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004024 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4025 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004026 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004027 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004028 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004029 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4030 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004031 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004032 DCHECK(self->IsExceptionPending());
4033 return nullptr;
4034 } else {
4035 self->ClearException();
4036 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004037 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004038 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4039 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4040 return nullptr;
4041 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004042 // See if the component type is already loaded. Array classes are
4043 // always associated with the class loader of their underlying
4044 // element type -- an array of Strings goes with the loader for
4045 // java/lang/String -- so we need to look for it there. (The
4046 // caller should have checked for the existence of the class
4047 // before calling here, but they did so with *their* class loader,
4048 // not the component type's loader.)
4049 //
4050 // If we find it, the caller adds "loader" to the class' initiating
4051 // loader list, which should prevent us from going through this again.
4052 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004053 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004054 // are the same, because our caller (FindClass) just did the
4055 // lookup. (Even if we get this wrong we still have correct behavior,
4056 // because we effectively do this lookup again when we add the new
4057 // class to the hash table --- necessary because of possible races with
4058 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004059 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004060 ObjPtr<mirror::Class> new_class =
4061 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004062 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004063 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004064 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004065 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004066
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004067 // Fill out the fields in the Class.
4068 //
4069 // It is possible to execute some methods against arrays, because
4070 // all arrays are subclasses of java_lang_Object_, so we need to set
4071 // up a vtable. We can just point at the one in java_lang_Object_.
4072 //
4073 // Array classes are simple enough that we don't need to do a full
4074 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004075 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004076 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004077 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004078 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004079 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004080 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004081 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4082 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4083 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004084 } else if (strcmp(descriptor, "[Z") == 0) {
4085 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4086 } else if (strcmp(descriptor, "[B") == 0) {
4087 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4088 } else if (strcmp(descriptor, "[C") == 0) {
4089 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4090 } else if (strcmp(descriptor, "[S") == 0) {
4091 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004092 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004093 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004094 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004095 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004096 } else if (strcmp(descriptor, "[F") == 0) {
4097 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4098 } else if (strcmp(descriptor, "[D") == 0) {
4099 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004100 }
4101 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004102 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004103 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004104 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004105 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004106 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004107 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004108 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004109 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004110 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004111 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004112 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004113 new_class->SetSuperClass(java_lang_Object);
4114 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004115 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004116 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004117 if (component_type->IsPrimitive()) {
4118 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4119 } else {
4120 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4121 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004122 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004123 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4124 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4125 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004126 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004127 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004128 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004129 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004130
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004131 // All arrays have java/lang/Cloneable and java/io/Serializable as
4132 // interfaces. We need to set that up here, so that stuff like
4133 // "instanceof" works right.
4134 //
4135 // Note: The GC could run during the call to FindSystemClass,
4136 // so we need to make sure the class object is GC-valid while we're in
4137 // there. Do this by clearing the interface list so the GC will just
4138 // think that the entries are null.
4139
4140
4141 // Use the single, global copies of "interfaces" and "iftable"
4142 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004143 {
Vladimir Marko02610552018-06-04 14:38:00 +01004144 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004145 CHECK(array_iftable != nullptr);
4146 new_class->SetIfTable(array_iftable);
4147 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004148
Elliott Hughes00626c22013-06-14 15:04:14 -07004149 // Inherit access flags from the component type.
4150 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4151 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4152 access_flags &= kAccJavaFlagsMask;
4153 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004154 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004155 access_flags |= kAccAbstract | kAccFinal;
4156 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004157 // Arrays are access-checks-clean and preverified.
4158 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004159
4160 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004161
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004162 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004163 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004164 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4165 // duplicate events in case of races. Array classes don't really follow dedicated
4166 // load and prepare, anyways.
4167 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4168 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4169
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004170 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004171 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004172 }
4173 // Another thread must have loaded the class after we
4174 // started but before we finished. Abandon what we've
4175 // done.
4176 //
4177 // (Yes, this happens.)
4178
Vladimir Markobcf17522018-06-01 13:14:32 +01004179 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004180}
4181
Vladimir Marko9186b182018-11-06 14:55:54 +00004182ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4183 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004184 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004185 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4186 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4187 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4188 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4189 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4190 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4191 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4192 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4193 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004194 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004195 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004196 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004197 return GetClassRoot(class_root, this);
4198}
4199
4200ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4201 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4202 if (UNLIKELY(result == nullptr)) {
4203 std::string printable_type(PrintableChar(type));
4204 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4205 }
4206 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004207}
4208
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004209ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4210 ObjPtr<mirror::Class> klass,
4211 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004212 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004213 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004214 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004215 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004216 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004217 source += " from ";
4218 source += dex_cache->GetLocation()->ToModifiedUtf8();
4219 }
4220 LOG(INFO) << "Loaded class " << descriptor << source;
4221 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004222 {
4223 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004224 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004225 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004226 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004227 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004228 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004229 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004230 VerifyObject(klass);
4231 class_table->InsertWithHash(klass, hash);
4232 if (class_loader != nullptr) {
4233 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004234 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004235 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004236 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004237 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004238 }
4239 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004240 if (kIsDebugBuild) {
4241 // Test that copied methods correctly can find their holder.
4242 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4243 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4244 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004245 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004246 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004247}
4248
Vladimir Marko1998cd02017-01-13 13:02:58 +00004249void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004250 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4251 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4252 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4253 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004254 }
4255}
4256
Alex Lighte64300b2015-12-15 15:02:47 -08004257// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004258void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004259 LengthPrefixedArray<ArtMethod>* new_methods) {
4260 klass->SetMethodsPtrUnchecked(new_methods,
4261 klass->NumDirectMethods(),
4262 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004263 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004264 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004265}
4266
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004267ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4268 const char* descriptor,
4269 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004270 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4271}
4272
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004273ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4274 const char* descriptor,
4275 size_t hash,
4276 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004277 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4278 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4279 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004280 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004281 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004282 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004283 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004284 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004285 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004286}
4287
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004288class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4289 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004290 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004291
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004292 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004293 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004294 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004295 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004296 if (class_table != nullptr) {
4297 class_table->FreezeSnapshot();
4298 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004299 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004300};
4301
4302void ClassLinker::MoveClassTableToPreZygote() {
4303 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004304 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004305 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004306 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004307}
4308
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004309// Look up classes by hash and descriptor and put all matching ones in the result array.
4310class LookupClassesVisitor : public ClassLoaderVisitor {
4311 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004312 LookupClassesVisitor(const char* descriptor,
4313 size_t hash,
4314 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004315 : descriptor_(descriptor),
4316 hash_(hash),
4317 result_(result) {}
4318
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004319 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004320 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004321 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004322 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004323 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4324 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004325 result_->push_back(klass);
4326 }
4327 }
4328
4329 private:
4330 const char* const descriptor_;
4331 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004332 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004333};
4334
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004335void ClassLinker::LookupClasses(const char* descriptor,
4336 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004337 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004338 Thread* const self = Thread::Current();
4339 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004340 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004341 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004342 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004343 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004344 result.push_back(klass);
4345 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004346 LookupClassesVisitor visitor(descriptor, hash, &result);
4347 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004348}
4349
Alex Lightf1f10492015-10-07 16:08:36 -07004350bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4351 Handle<mirror::Class> klass,
4352 Handle<mirror::Class> supertype) {
4353 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004354 DCHECK(klass != nullptr);
4355 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004356
Alex Lightf1f10492015-10-07 16:08:36 -07004357 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4358 VerifyClass(self, supertype);
4359 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004360
4361 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4362 // The supertype is either verified, or we soft failed at AOT time.
4363 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004364 return true;
4365 }
4366 // If we got this far then we have a hard failure.
4367 std::string error_msg =
4368 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004369 klass->PrettyDescriptor().c_str(),
4370 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004371 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004372 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004373 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004374 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004375 // Set during VerifyClass call (if at all).
4376 self->ClearException();
4377 }
4378 // Change into a verify error.
4379 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004380 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004381 self->GetException()->SetCause(cause.Get());
4382 }
4383 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4384 if (Runtime::Current()->IsAotCompiler()) {
4385 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4386 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004387 // Need to grab the lock to change status.
4388 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004389 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004390 return false;
4391}
4392
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004393verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004394 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004395 {
4396 // TODO: assert that the monitor on the Class is held
4397 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004398
Andreas Gampe884f3b82016-03-30 19:52:58 -07004399 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004400 ClassStatus old_status = klass->GetStatus();
4401 while (old_status == ClassStatus::kVerifying ||
4402 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004403 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004404 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4405 // case we may see the same status again. b/62912904. This is why the check is
4406 // greater or equal.
4407 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004408 << "Class '" << klass->PrettyClass()
4409 << "' performed an illegal verification state transition from " << old_status
4410 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004411 old_status = klass->GetStatus();
4412 }
jeffhao98eacac2011-09-14 16:11:53 -07004413
Andreas Gampe884f3b82016-03-30 19:52:58 -07004414 // The class might already be erroneous, for example at compile time if we attempted to verify
4415 // this class as a parent to another.
4416 if (klass->IsErroneous()) {
4417 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004418 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004419 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004420
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004421 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004422 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004423 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004424 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004425 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004426
4427 // For AOT, don't attempt to re-verify if we have already found we should
4428 // verify at runtime.
4429 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004430 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004431 }
jeffhao98eacac2011-09-14 16:11:53 -07004432
Vladimir Marko2c64a832018-01-04 11:31:56 +00004433 if (klass->GetStatus() == ClassStatus::kResolved) {
4434 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004435 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004436 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004437 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004438 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004439 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004440 }
4441
4442 // Skip verification if disabled.
4443 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004444 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004445 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004446 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004447 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004448 }
4449
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004450 VLOG(class_linker) << "Beginning verification for class: "
4451 << klass->PrettyDescriptor()
4452 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4453
Ian Rogers9ffb0392012-09-10 11:56:50 -07004454 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004455 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004456 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4457 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004458 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004459 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004460 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004461 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004462
Alex Lightf1f10492015-10-07 16:08:36 -07004463 // Verify all default super-interfaces.
4464 //
4465 // (1) Don't bother if the superclass has already had a soft verification failure.
4466 //
4467 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4468 // recursive initialization by themselves. This is because when an interface is initialized
4469 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4470 // but choose not to for an optimization. If the interfaces is being verified due to a class
4471 // initialization (which would need all the default interfaces to be verified) the class code
4472 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004473 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004474 && !klass->IsInterface()) { // See (2)
4475 int32_t iftable_count = klass->GetIfTableCount();
4476 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4477 // Loop through all interfaces this class has defined. It doesn't matter the order.
4478 for (int32_t i = 0; i < iftable_count; i++) {
4479 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004480 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004481 // We only care if we have default interfaces and can skip if we are already verified...
4482 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4483 continue;
4484 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4485 // We had a hard failure while verifying this interface. Just return immediately.
4486 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004487 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004488 } else if (UNLIKELY(!iface->IsVerified())) {
4489 // We softly failed to verify the iface. Stop checking and clean up.
4490 // Put the iface into the supertype handle so we know what caused us to fail.
4491 supertype.Assign(iface.Get());
4492 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004493 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004494 }
4495 }
4496
Alex Lightf1f10492015-10-07 16:08:36 -07004497 // At this point if verification failed, then supertype is the "first" supertype that failed
4498 // verification (without a specific order). If verification succeeded, then supertype is either
4499 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004500 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004501 supertype.Get() == klass->GetSuperClass() ||
4502 !supertype->IsVerified());
4503
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004504 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004505 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004506 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004507 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004508
4509 VLOG(class_linker) << "Class preverified status for class "
4510 << klass->PrettyDescriptor()
4511 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4512 << ": "
4513 << preverified;
4514
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004515 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4516 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004517 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4518 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004519
Ian Rogers62d6c772013-02-27 08:32:07 -08004520 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004521 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004522 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004523 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004524 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004525
4526 // Verification is done, grab the lock again.
4527 ObjectLock<mirror::Class> lock(self, klass);
4528
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004529 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4530 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004531 VLOG(class_linker) << "Soft verification failure in class "
4532 << klass->PrettyDescriptor()
4533 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4534 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004535 }
Ian Rogers1f539342012-10-03 21:09:42 -07004536 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004537 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004538 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004539 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004540 // Even though there were no verifier failures we need to respect whether the super-class and
4541 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004542 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004543 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004544 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004545 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4546 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004547 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004548 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004549 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004550 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004551 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004552 // Soft failures at compile time should be retried at runtime. Soft
4553 // failures at runtime will be handled by slow paths in the generated
4554 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004555 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004556 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004557 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004558 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004559 // As this is a fake verified status, make sure the methods are _not_ marked
4560 // kAccSkipAccessChecks later.
4561 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004562 }
4563 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004564 } else {
David Sehr709b0702016-10-13 09:12:37 -07004565 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004566 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4567 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004568 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004569 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004570 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004571 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004572 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004573 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004574 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004575 // method.
4576 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004577 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004578 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004579
4580 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4581 // Never skip access checks if the verification soft fail is forced.
4582 // Mark the class as having a verification attempt to avoid re-running the verifier.
4583 klass->SetVerificationAttempted();
4584 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004585 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004586 }
Andreas Gampe48498592014-09-10 19:48:05 -07004587 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004588 // Done verifying. Notify the compiler about the verification status, in case the class
4589 // was verified implicitly (eg super class of a compiled class).
4590 if (Runtime::Current()->IsAotCompiler()) {
4591 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4592 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4593 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004594 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004595}
4596
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004597verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4598 Handle<mirror::Class> klass,
4599 verifier::HardFailLogMode log_level,
4600 std::string* error_msg) {
4601 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004602 return verifier::ClassVerifier::VerifyClass(self,
4603 klass.Get(),
4604 runtime->GetCompilerCallbacks(),
4605 runtime->IsAotCompiler(),
4606 log_level,
4607 Runtime::Current()->GetTargetSdkVersion(),
4608 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004609}
4610
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004611bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004612 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004613 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004614 // If we're compiling, we can only verify the class using the oat file if
4615 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004616 // the compilation unit (app - dependencies). We will let the compiler callback
4617 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004618 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004619 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004620 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004621 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004622 return false;
4623 }
4624 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004625 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004626 return false;
4627 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004628 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004629
Andreas Gampeb40d3612018-06-26 15:49:42 -07004630 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004631 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004632 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004633 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4634 // For boot classpath classes in the case we're not using a default boot image:
4635 // we don't have the infrastructure yet to query verification data on individual
4636 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4637 // verified. This should be taken into account when measuring boot time and app
4638 // startup compare to the (current) production system where both:
4639 // 1) updatable boot classpath classes, and
4640 // 2) classes in /system referencing updatable classes
4641 // will be verified at runtime.
4642 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4643 oat_file_class_status = ClassStatus::kVerified;
4644 return true;
4645 }
4646 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004647 return false;
4648 }
4649
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004650 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004651 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004652 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004653 return true;
4654 }
4655 // If we only verified a subset of the classes at compile time, we can end up with classes that
4656 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004657 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004658 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004659 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004660 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004661 // Compile time verification failed with a soft error. Compile time verification can fail
4662 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004663 // class ... {
4664 // Foo x;
4665 // .... () {
4666 // if (...) {
4667 // v1 gets assigned a type of resolved class Foo
4668 // } else {
4669 // v1 gets assigned a type of unresolved class Bar
4670 // }
4671 // iput x = v1
4672 // } }
4673 // when we merge v1 following the if-the-else it results in Conflict
4674 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4675 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4676 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4677 // at compile time).
4678 return false;
4679 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004680 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004681 // Compile time verification failed with a hard error. This is caused by invalid instructions
4682 // in the class. These errors are unrecoverable.
4683 return false;
4684 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004685 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004686 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4687 // not loading the class.
4688 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4689 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004690 return false;
4691 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004692 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004693 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004694 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004695 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004696 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004697}
4698
Alex Light5a559862016-01-29 12:24:48 -08004699void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004700 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004701 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004702 }
4703}
4704
Alex Light5a559862016-01-29 12:24:48 -08004705void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004706 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004707 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004708 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004709 return; // native or abstract method
4710 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004711 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004712 return; // nothing to process
4713 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004714 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004715 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004716 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4717 CatchHandlerIterator iterator(handlers_ptr);
4718 for (; iterator.HasNext(); iterator.Next()) {
4719 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4720 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004721 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004722 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004723 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004724 DCHECK(Thread::Current()->IsExceptionPending());
4725 Thread::Current()->ClearException();
4726 }
4727 }
4728 }
4729 handlers_ptr = iterator.EndDataPointer();
4730 }
4731}
4732
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004733ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4734 jstring name,
4735 jobjectArray interfaces,
4736 jobject loader,
4737 jobjectArray methods,
4738 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004739 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004740
4741 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4742 // code to be executed. We put it up here so we can avoid all the allocations associated with
4743 // creating the class. This can happen with (eg) jit-threads.
4744 if (!self->CanLoadClasses()) {
4745 // Make sure we don't try to load anything, potentially causing an infinite loop.
4746 ObjPtr<mirror::Throwable> pre_allocated =
4747 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4748 self->SetException(pre_allocated);
4749 return nullptr;
4750 }
4751
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004752 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004753 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004754 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004755 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004756 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004757 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004758 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004759 DCHECK(temp_klass->GetClass() != nullptr);
4760 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004761 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4762 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004763 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4764 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4765 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4766 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004767 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004768 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004769 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004770 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004771 std::string storage;
4772 const char* descriptor = temp_klass->GetDescriptor(&storage);
4773 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004774
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004775 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004776 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004777
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004778 // Insert the class before loading the fields as the field roots
4779 // (ArtField::declaring_class_) are only visited from the class
4780 // table. There can't be any suspend points between inserting the
4781 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004782 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004783 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004784
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004785 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004786 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004787 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004788 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004789
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004790 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4791 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004792 ArtField& interfaces_sfield = sfields->At(0);
4793 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004794 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004795 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004796
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004797 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004798 ArtField& throws_sfield = sfields->At(1);
4799 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004800 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004801 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004802
Ian Rogers466bb252011-10-14 03:29:56 -07004803 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004804 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004805
Alex Lighte64300b2015-12-15 15:02:47 -08004806 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004807 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004808 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004809 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004810 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004811
4812 // Create the methods array.
4813 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4814 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004815 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4816 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004817 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004818 self->AssertPendingOOMException();
4819 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004820 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004821 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004822
4823 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004824 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004825
4826 // Create virtual method using specified prototypes.
4827 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004828 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004829 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004830 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004831 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004832 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4833 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004834 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004835
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004836 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004837 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004838 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004839 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004840 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004841
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004842 // At this point the class is loaded. Publish a ClassLoad event.
4843 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4844 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4845
4846 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004847 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004848 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004849 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004850 // Link the fields and virtual methods, creating vtable and iftables.
4851 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004852 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004853 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004854 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004855 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004856 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004857 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004858 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004859 CHECK(temp_klass->IsRetired());
4860 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004861
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004862 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004863 interfaces_sfield.SetObject<false>(
4864 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004865 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004866 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4867 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004868 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004869 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004870
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004871 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4872
Vladimir Marko305c38b2018-02-14 11:50:07 +00004873 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4874 // See also ClassLinker::EnsureInitialized().
4875 if (kBitstringSubtypeCheckEnabled) {
4876 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4877 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4878 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4879 }
4880
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004881 {
4882 // Lock on klass is released. Lock new class object.
4883 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004884 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004885 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004886 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004887
4888 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004889 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004890 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004891 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4892
Ian Rogersc2b44472011-12-14 21:17:17 -08004893 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004894 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4895 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004896 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004897 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004898
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004899 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004900 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004901 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004902 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004903 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004904
4905 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004906 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004907 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004908
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004909 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004910 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004911 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004912 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004913 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004914 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004915}
4916
Mathieu Chartiere401d142015-04-22 13:56:20 -07004917void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4918 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004919 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4920 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004921
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004922 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4923 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004924 ArtMethod* proxy_constructor =
4925 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004926 DCHECK(proxy_constructor != nullptr)
4927 << "Could not find <init> method in java.lang.reflect.Proxy";
4928
Jeff Haodb8a6642014-08-14 17:18:52 -07004929 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4930 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004931 DCHECK(out != nullptr);
4932 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004933 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004934 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004935 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004936 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4937 kAccPublic |
4938 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004939 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004940
4941 // Set the original constructor method.
4942 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004943}
4944
Mathieu Chartiere401d142015-04-22 13:56:20 -07004945void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004946 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004947 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4948 CHECK_STREQ(np->GetName(), "<init>");
4949 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004950 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004951}
4952
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004953void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004954 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004955 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004956 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004957 DCHECK(out != nullptr);
4958 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004959
Alex Lighte9dd04f2016-03-16 16:09:45 -07004960 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004961 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004962 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4963 // preference to the invocation handler.
4964 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4965 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004966 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4967 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004968 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4969
4970 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4971 // method they copy might (if it's a default method).
4972 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004973
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004974 // Set the original interface method.
4975 out->SetDataPtrSize(prototype, image_pointer_size_);
4976
Ian Rogers466bb252011-10-14 03:29:56 -07004977 // At runtime the method looks like a reference and argument saving method, clone the code
4978 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004979 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004980}
Jesse Wilson95caa792011-10-12 18:14:17 -04004981
Mathieu Chartiere401d142015-04-22 13:56:20 -07004982void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004983 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004984 CHECK(!prototype->IsFinal());
4985 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004986 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004987
4988 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4989 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004990 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004991 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004992}
4993
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004994bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004995 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004996 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004997 return true;
4998 }
4999 if (!can_init_statics) {
5000 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005001 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005002 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005003 return false;
5004 }
5005 // Check if there are encoded static values needing initialization.
5006 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005007 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005008 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005009 if (dex_class_def->static_values_off_ != 0) {
5010 return false;
5011 }
5012 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005013 // If we are a class we need to initialize all interfaces with default methods when we are
5014 // initialized. Check all of them.
5015 if (!klass->IsInterface()) {
5016 size_t num_interfaces = klass->GetIfTableCount();
5017 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005018 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005019 if (iface->HasDefaultMethods() &&
5020 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5021 return false;
5022 }
5023 }
5024 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005025 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005026 if (klass->IsInterface() || !klass->HasSuperClass()) {
5027 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005028 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005029 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005030 if (!can_init_parents && !super_class->IsInitialized()) {
5031 return false;
5032 }
5033 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005034}
5035
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005036bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5037 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005038 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5039
5040 // Are we already initialized and therefore done?
5041 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5042 // an initialized class will never change its state.
5043 if (klass->IsInitialized()) {
5044 return true;
5045 }
5046
5047 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005048 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005049 return false;
5050 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005051
Ian Rogers7b078e82014-09-10 14:44:24 -07005052 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005053 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005054 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005055 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005056
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005057 // Re-check under the lock in case another thread initialized ahead of us.
5058 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005059 return true;
5060 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005061
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005062 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005063 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005064 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005065 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005066 return false;
5067 }
5068
Vladimir Marko72ab6842017-01-20 19:32:50 +00005069 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5070 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005071
5072 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005073 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005074 if (!klass->IsVerified()) {
5075 // We failed to verify, expect either the klass to be erroneous or verification failed at
5076 // compile time.
5077 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005078 // The class is erroneous. This may be a verifier error, or another thread attempted
5079 // verification and/or initialization and failed. We can distinguish those cases by
5080 // whether an exception is already pending.
5081 if (self->IsExceptionPending()) {
5082 // Check that it's a VerifyError.
5083 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005084 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005085 } else {
5086 // Check that another thread attempted initialization.
5087 DCHECK_NE(0, klass->GetClinitThreadId());
5088 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5089 // Need to rethrow the previous failure now.
5090 ThrowEarlierClassFailure(klass.Get(), true);
5091 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005092 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005093 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005094 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005095 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005096 self->AssertNoPendingException();
5097 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005098 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005099 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005100 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005101 } else {
5102 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005103 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005104
5105 // A separate thread could have moved us all the way to initialized. A "simple" example
5106 // involves a subclass of the current class being initialized at the same time (which
5107 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005108 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005109 if (klass->IsInitialized()) {
5110 return true;
5111 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005112 }
5113
Vladimir Marko2c64a832018-01-04 11:31:56 +00005114 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005115 // initializing higher up the stack or another thread has beat us
5116 // to initializing and we need to wait. Either way, this
5117 // invocation of InitializeClass will not be responsible for
5118 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005119 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005120 // Could have got an exception during verification.
5121 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005122 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005123 return false;
5124 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005125 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005126 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005127 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005128 return true;
5129 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005130 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005131 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005132 }
5133
Jeff Haoe2e40342017-07-19 10:45:18 -07005134 // Try to get the oat class's status for this class if the oat file is present. The compiler
5135 // tries to validate superclass descriptors, and writes the result into the oat file.
5136 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5137 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5138 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005139 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005140 const Runtime* runtime = Runtime::Current();
5141 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5142 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5143 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005144 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005145 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005146 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005147 return false;
5148 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005149 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005150
Vladimir Marko2c64a832018-01-04 11:31:56 +00005151 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005152 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005153
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005154 // From here out other threads may observe that we're initializing and so changes of state
5155 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005156 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005157 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005158
5159 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005160 }
5161
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005162 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005163 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005164 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005165 if (!super_class->IsInitialized()) {
5166 CHECK(!super_class->IsInterface());
5167 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005168 StackHandleScope<1> hs(self);
5169 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005170 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005171 if (!super_initialized) {
5172 // The super class was verified ahead of entering initializing, we should only be here if
5173 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005174 // For the case of aot compiler, the super class might also be initializing but we don't
5175 // want to process circular dependencies in pre-compile.
5176 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005177 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005178 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005179 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005180 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005181 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005182 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005183 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005184 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005185 return false;
5186 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005187 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005188 }
5189
Alex Lighteb7c1442015-08-31 13:17:42 -07005190 if (!klass->IsInterface()) {
5191 // Initialize interfaces with default methods for the JLS.
5192 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005193 // Only setup the (expensive) handle scope if we actually need to.
5194 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005195 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005196 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5197 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005198 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005199 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005200 CHECK(handle_scope_iface->IsInterface());
5201 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5202 // We have already done this for this interface. Skip it.
5203 continue;
5204 }
5205 // We cannot just call initialize class directly because we need to ensure that ALL
5206 // interfaces with default methods are initialized. Non-default interface initialization
5207 // will not affect other non-default super-interfaces.
5208 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5209 handle_scope_iface,
5210 can_init_statics,
5211 can_init_parents);
5212 if (!iface_initialized) {
5213 ObjectLock<mirror::Class> lock(self, klass);
5214 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005215 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005216 return false;
5217 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005218 }
5219 }
5220 }
5221
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005222 const size_t num_static_fields = klass->NumStaticFields();
5223 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005224 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005225 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005226 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005227 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005228 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005229
5230 // Eagerly fill in static fields so that the we don't have to do as many expensive
5231 // Class::FindStaticField in ResolveField.
5232 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005233 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005234 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005235 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005236 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005237 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005238 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5239 field,
5240 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5241 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005242 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005243 } else {
5244 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005245 }
5246 }
5247
Vladimir Markoe11dd502017-12-08 14:09:45 +00005248 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5249 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005250 this,
5251 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005252 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005253
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005254 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005255 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005256 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005257 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5258 if (!value_it.HasNext()) {
5259 break;
5260 }
5261 ArtField* art_field = ResolveField(field.GetIndex(),
5262 dex_cache,
5263 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005264 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005265 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005266 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005267 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005268 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005269 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005270 if (self->IsExceptionPending()) {
5271 break;
5272 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005273 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005274 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005275 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005276 }
5277 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005278
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005279
Mathieu Chartierda595be2016-08-10 13:57:39 -07005280 if (!self->IsExceptionPending()) {
5281 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5282 if (clinit != nullptr) {
5283 CHECK(can_init_statics);
5284 JValue result;
5285 clinit->Invoke(self, nullptr, 0, &result, "V");
5286 }
5287 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005288 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005289 uint64_t t1 = NanoTime();
5290
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005291 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005292 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005293 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005294
5295 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005296 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005297 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005298 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005299 } else if (Runtime::Current()->IsTransactionAborted()) {
5300 // The exception thrown when the transaction aborted has been caught and cleared
5301 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005302 VLOG(compiler) << "Return from class initializer of "
5303 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005304 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005305 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005306 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005307 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005308 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005309 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5310 RuntimeStats* thread_stats = self->GetStats();
5311 ++global_stats->class_init_count;
5312 ++thread_stats->class_init_count;
5313 global_stats->class_init_time_ns += (t1 - t0);
5314 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005315 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005316 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005317 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005318 std::string temp;
5319 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005320 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005321 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005322 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005323 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005324 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005325 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005326 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005327}
5328
Alex Lighteb7c1442015-08-31 13:17:42 -07005329// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5330// and perform the initialization only on those interfaces that contain default methods.
5331bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5332 Handle<mirror::Class> iface,
5333 bool can_init_statics,
5334 bool can_init_parents) {
5335 CHECK(iface->IsInterface());
5336 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005337 // Only create the (expensive) handle scope if we need it.
5338 if (UNLIKELY(num_direct_ifaces > 0)) {
5339 StackHandleScope<1> hs(self);
5340 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5341 // First we initialize all of iface's super-interfaces recursively.
5342 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005343 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005344 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005345 if (!super_iface->HasBeenRecursivelyInitialized()) {
5346 // Recursive step
5347 handle_super_iface.Assign(super_iface);
5348 if (!InitializeDefaultInterfaceRecursive(self,
5349 handle_super_iface,
5350 can_init_statics,
5351 can_init_parents)) {
5352 return false;
5353 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005354 }
5355 }
5356 }
5357
5358 bool result = true;
5359 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5360 // initialize if we don't have default methods.
5361 if (iface->HasDefaultMethods()) {
5362 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5363 }
5364
5365 // Mark that this interface has undergone recursive default interface initialization so we know we
5366 // can skip it on any later class initializations. We do this even if we are not a default
5367 // interface since we can still avoid the traversal. This is purely a performance optimization.
5368 if (result) {
5369 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005370 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5371 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5372 // initialization is a performance optimization (to avoid another idempotent visit
5373 // for other implementing classes/interfaces), and can be revisited later.
5374 ObjectTryLock<mirror::Class> lock(self, iface);
5375 if (lock.Acquired()) {
5376 iface->SetRecursivelyInitialized();
5377 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005378 }
5379 return result;
5380}
5381
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005382bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5383 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005384 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005385 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005386 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005387 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005388 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005389 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005390
5391 // When we wake up, repeat the test for init-in-progress. If
5392 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005393 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005394 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005395 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005396 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005397 return false;
5398 }
5399 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005400 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005401 continue;
5402 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005403 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005404 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005405 // Compile time initialization failed.
5406 return false;
5407 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005408 if (klass->IsErroneous()) {
5409 // The caller wants an exception, but it was thrown in a
5410 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005411 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005412 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005413 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005414 return false;
5415 }
5416 if (klass->IsInitialized()) {
5417 return true;
5418 }
David Sehr709b0702016-10-13 09:12:37 -07005419 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005420 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005421 }
Ian Rogers07140832014-09-30 15:43:59 -07005422 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005423}
5424
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005425static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5426 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005427 ArtMethod* method,
5428 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005429 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005430 DCHECK(Thread::Current()->IsExceptionPending());
5431 DCHECK(!m->IsProxyMethod());
5432 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005433 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5434 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005435 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005436 std::string return_type = dex_file->PrettyType(return_type_idx);
5437 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005438 ThrowWrappedLinkageError(klass.Get(),
5439 "While checking class %s method %s signature against %s %s: "
5440 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005441 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5442 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005443 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005444 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005445 return_type.c_str(), class_loader.c_str());
5446}
5447
5448static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5449 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005450 ArtMethod* method,
5451 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005452 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005453 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005454 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005455 DCHECK(Thread::Current()->IsExceptionPending());
5456 DCHECK(!m->IsProxyMethod());
5457 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005458 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5459 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005460 ThrowWrappedLinkageError(klass.Get(),
5461 "While checking class %s method %s signature against %s %s: "
5462 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005463 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5464 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005465 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005466 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005467 index, arg_type.c_str(), class_loader.c_str());
5468}
5469
5470static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5471 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005472 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005473 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005474 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005475 ThrowLinkageError(klass.Get(),
5476 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005477 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5478 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005479 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005480 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005481 error_msg.c_str());
5482}
5483
Ian Rogersb5fb2072014-12-02 17:22:02 -08005484static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005485 Handle<mirror::Class> klass,
5486 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005487 ArtMethod* method1,
5488 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005489 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005490 {
5491 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005492 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005493 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005494 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005495 return false;
5496 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005497 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005498 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005499 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005500 return false;
5501 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005502 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005503 ThrowSignatureMismatch(klass, super_klass, method1,
5504 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005505 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005506 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005507 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005508 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005509 return false;
5510 }
5511 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005512 const dex::TypeList* types1 = method1->GetParameterTypeList();
5513 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005514 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005515 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005516 ThrowSignatureMismatch(klass, super_klass, method1,
5517 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005518 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005519 return false;
5520 }
5521 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005522 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005523 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005524 ThrowSignatureMismatch(klass, super_klass, method1,
5525 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005526 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005527 return false;
5528 }
5529 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005530 }
5531 uint32_t num_types = types1->Size();
5532 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005533 ThrowSignatureMismatch(klass, super_klass, method1,
5534 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005535 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005536 return false;
5537 }
5538 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005539 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005540 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005541 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005542 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005543 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005544 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005545 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005546 return false;
5547 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005548 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005549 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005550 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005551 if (UNLIKELY(other_param_type == nullptr)) {
5552 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005553 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005554 return false;
5555 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005556 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005557 ThrowSignatureMismatch(klass, super_klass, method1,
5558 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5559 i,
David Sehr709b0702016-10-13 09:12:37 -07005560 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005562 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005563 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005564 return false;
5565 }
5566 }
5567 return true;
5568}
5569
5570
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005571bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005572 if (klass->IsInterface()) {
5573 return true;
5574 }
Ian Rogers151f2212014-05-06 11:27:27 -07005575 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005576 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005577 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005578 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005579 if (klass->HasSuperClass() &&
5580 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005581 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005582 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005583 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5584 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5585 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005586 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5587 klass,
5588 super_klass,
5589 m,
5590 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005591 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005592 return false;
5593 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005594 }
5595 }
5596 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005597 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005598 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5599 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5600 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005601 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005602 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5603 j, image_pointer_size_);
5604 auto* super_m = super_klass->GetVirtualMethod(j, 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 }
5617 }
5618 return true;
5619}
5620
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005621bool ClassLinker::EnsureInitialized(Thread* self,
5622 Handle<mirror::Class> c,
5623 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005624 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005625 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005626
Mathieu Chartier524507a2014-08-27 15:28:28 -07005627 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005628 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005629 return true;
5630 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005631 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5632 //
5633 // Ensure the bitstring is initialized before any of the class initialization
5634 // logic occurs. Once a class initializer starts running, objects can
5635 // escape into the heap and use the subtype checking code.
5636 //
5637 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5638 // can be used as a source for the IsSubClass check, and that all ancestors
5639 // of the class are Assigned (can be used as a target for IsSubClass check)
5640 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005641 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005642 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005643 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005644 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5645 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005646 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005647 if (!success) {
5648 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005649 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005650 }
5651 } else {
5652 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005653 }
5654 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005655}
5656
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005657void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5658 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005659 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005660 for (ArtField& field : new_class->GetIFields()) {
5661 if (field.GetDeclaringClass() == temp_class) {
5662 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005663 }
5664 }
5665
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005666 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005667 for (ArtField& field : new_class->GetSFields()) {
5668 if (field.GetDeclaringClass() == temp_class) {
5669 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005670 }
5671 }
5672
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005673 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005674 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005675 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005676 if (method.GetDeclaringClass() == temp_class) {
5677 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005678 }
5679 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005680
5681 // Make sure the remembered set and mod-union tables know that we updated some of the native
5682 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005683 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005684}
5685
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005686void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005687 CHECK(class_loader->GetAllocator() == nullptr);
5688 CHECK(class_loader->GetClassTable() == nullptr);
5689 Thread* const self = Thread::Current();
5690 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005691 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005692 // Create and set the class table.
5693 data.class_table = new ClassTable;
5694 class_loader->SetClassTable(data.class_table);
5695 // Create and set the linear allocator.
5696 data.allocator = Runtime::Current()->CreateLinearAlloc();
5697 class_loader->SetAllocator(data.allocator);
5698 // Add to the list so that we know to free the data later.
5699 class_loaders_.push_back(data);
5700}
5701
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005702ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005703 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005704 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005705 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005706 ClassTable* class_table = class_loader->GetClassTable();
5707 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005708 RegisterClassLoader(class_loader);
5709 class_table = class_loader->GetClassTable();
5710 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005711 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005712 return class_table;
5713}
5714
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005715ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005716 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005717}
5718
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005719static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005720 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005721 while (klass->HasSuperClass()) {
5722 klass = klass->GetSuperClass();
5723 if (klass->ShouldHaveImt()) {
5724 return klass->GetImt(pointer_size);
5725 }
5726 }
5727 return nullptr;
5728}
5729
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005730bool ClassLinker::LinkClass(Thread* self,
5731 const char* descriptor,
5732 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005733 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005734 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005735 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005736
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005737 if (!LinkSuperClass(klass)) {
5738 return false;
5739 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005740 ArtMethod* imt_data[ImTable::kSize];
5741 // If there are any new conflicts compared to super class.
5742 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005743 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005744 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005745 return false;
5746 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005747 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005748 return false;
5749 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005750 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005751 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005752 return false;
5753 }
5754 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005755 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005756
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005757 ImTable* imt = nullptr;
5758 if (klass->ShouldHaveImt()) {
5759 // If there are any new conflicts compared to the super class we can not make a copy. There
5760 // can be cases where both will have a conflict method at the same slot without having the same
5761 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5762 // will possibly create a table that is incorrect for either of the classes.
5763 // Same IMT with new_conflict does not happen very often.
5764 if (!new_conflict) {
5765 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5766 if (super_imt != nullptr) {
5767 bool imt_equals = true;
5768 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5769 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5770 }
5771 if (imt_equals) {
5772 imt = super_imt;
5773 }
5774 }
5775 }
5776 if (imt == nullptr) {
5777 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5778 imt = reinterpret_cast<ImTable*>(
5779 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5780 if (imt == nullptr) {
5781 return false;
5782 }
5783 imt->Populate(imt_data, image_pointer_size_);
5784 }
5785 }
5786
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005787 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5788 // We don't need to retire this class as it has no embedded tables or it was created the
5789 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005790 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005791
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005792 if (klass->ShouldHaveEmbeddedVTable()) {
5793 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005794 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005795 if (klass->ShouldHaveImt()) {
5796 klass->SetImt(imt, image_pointer_size_);
5797 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005798
5799 // Update CHA info based on whether we override methods.
5800 // Have to do this before setting the class as resolved which allows
5801 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005802 if (cha_ != nullptr) {
5803 cha_->UpdateAfterLoadingOf(klass);
5804 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005805
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005806 // This will notify waiters on klass that saw the not yet resolved
5807 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005808 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005809 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005810 } else {
5811 CHECK(!klass->IsResolved());
5812 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005813 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005814 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005815 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5816 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5817 // may not see any references to the target space and clean the card for a class if another
5818 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005819 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005820 klass->SetSFieldsPtrUnchecked(nullptr);
5821 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005822 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005823 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005824 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005825 return false;
5826 }
5827
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005828 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5829 ObjectLock<mirror::Class> lock(self, h_new_class);
5830 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005831
5832 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005833 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005834 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005835 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005836 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005837 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005838 if (class_loader != nullptr) {
5839 // We updated the class in the class table, perform the write barrier so that the GC knows
5840 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005841 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005842 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005843 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005844 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005845 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5846 }
5847 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005848
Mingyao Yang063fc772016-08-02 11:02:54 -07005849 // Update CHA info based on whether we override methods.
5850 // Have to do this before setting the class as resolved which allows
5851 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005852 if (cha_ != nullptr) {
5853 cha_->UpdateAfterLoadingOf(h_new_class);
5854 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005855
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005856 // This will notify waiters on temp class that saw the not yet resolved class in the
5857 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005858 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005859
Vladimir Marko2c64a832018-01-04 11:31:56 +00005860 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005861 // This will notify waiters on new_class that saw the not yet resolved
5862 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005863 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005864 // Return the new class.
5865 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005866 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005867 return true;
5868}
5869
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005870bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005871 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005872 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005873 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5874 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005875 // Check that a class does not inherit from itself directly.
5876 //
5877 // TODO: This is a cheap check to detect the straightforward case
5878 // of a class extending itself (b/28685551), but we should do a
5879 // proper cycle detection on loaded classes, to detect all cases
5880 // of class circularity errors (b/28830038).
5881 if (super_class_idx == class_def.class_idx_) {
5882 ThrowClassCircularityError(klass.Get(),
5883 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005884 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005885 return false;
5886 }
5887
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005888 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005889 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005890 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005891 return false;
5892 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005893 // Verify
5894 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005895 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005896 super_class->PrettyDescriptor().c_str(),
5897 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005898 return false;
5899 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005900 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005901 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005902 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005903 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005904 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005905 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005906 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005907 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005908 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005909 DCHECK(Thread::Current()->IsExceptionPending());
5910 return false;
5911 }
5912 // Verify
5913 if (!klass->CanAccess(interface)) {
5914 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005915 ThrowIllegalAccessError(klass.Get(),
5916 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005917 interface->PrettyDescriptor().c_str(),
5918 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005919 return false;
5920 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005921 }
5922 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005923 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005924 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005925 return true;
5926}
5927
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005928bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005929 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005930 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005931 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5932 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005933 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005934 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005935 return false;
5936 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005937 return true;
5938 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005939 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005940 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005941 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005942 return false;
5943 }
5944 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005945 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005946 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5947 return false;
5948 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005949 if (super->IsFinal()) {
5950 ThrowVerifyError(klass.Get(),
5951 "Superclass %s of %s is declared final",
5952 super->PrettyDescriptor().c_str(),
5953 klass->PrettyDescriptor().c_str());
5954 return false;
5955 }
5956 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005957 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005958 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005959 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005960 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005961 return false;
5962 }
5963 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005964 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005965 super->PrettyDescriptor().c_str(),
5966 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005967 return false;
5968 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005969
Brian Carlstromf3632832014-05-20 15:36:53 -07005970 // Inherit kAccClassIsFinalizable from the superclass in case this
5971 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005972 if (super->IsFinalizable()) {
5973 klass->SetFinalizable();
5974 }
5975
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005976 // Inherit class loader flag form super class.
5977 if (super->IsClassLoaderClass()) {
5978 klass->SetClassLoaderClass();
5979 }
5980
Elliott Hughes2da50362011-10-10 16:57:08 -07005981 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005982 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005983 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005984 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005985 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005986 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005987 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005988 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005989 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005990 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005991 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005992 return false;
5993 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005994
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005995 if (kIsDebugBuild) {
5996 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005997 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005998 CHECK(super->IsResolved());
5999 super = super->GetSuperClass();
6000 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006001 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006002 return true;
6003}
6004
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006005// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006006bool ClassLinker::LinkMethods(Thread* self,
6007 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006008 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006009 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006010 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006011 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006012 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6013 // need to have default methods be in the virtuals array of each class but we don't set that up
6014 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006015 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006016 // Link virtual methods then interface methods.
6017 // We set up the interface lookup table first because we need it to determine if we need to update
6018 // any vtable entries with new default method implementations.
6019 return SetupInterfaceLookupTable(self, klass, interfaces)
6020 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006021 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006022}
6023
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006024// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6025// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6026// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006027class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006028 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006029 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006030 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006031 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6032 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006033 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006034 }
6035
6036 const char* GetName() {
6037 if (name_ == nullptr) {
6038 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6039 }
6040 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006041 }
6042
Mathieu Chartiere401d142015-04-22 13:56:20 -07006043 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006044 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006045 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006046 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006047 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006048 if (dex_file_ == other_dex_file) {
6049 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6050 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006051 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006052 uint32_t other_name_len;
6053 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6054 &other_name_len);
6055 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6056 return false;
6057 }
6058 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6059 }
6060
6061 private:
6062 // Dex file for the method to compare against.
6063 const DexFile* const dex_file_;
6064 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006065 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006066 // Lazily computed name from the dex file's strings.
6067 const char* name_;
6068 // Lazily computed name length.
6069 uint32_t name_len_;
6070};
6071
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006072class LinkVirtualHashTable {
6073 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006074 LinkVirtualHashTable(Handle<mirror::Class> klass,
6075 size_t hash_size,
6076 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006077 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006078 : klass_(klass),
6079 hash_size_(hash_size),
6080 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006081 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006082 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6083 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006084
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006085 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006086 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6087 virtual_method_index, image_pointer_size_);
6088 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006089 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006090 uint32_t index = hash % hash_size_;
6091 // Linear probe until we have an empty slot.
6092 while (hash_table_[index] != invalid_index_) {
6093 if (++index == hash_size_) {
6094 index = 0;
6095 }
6096 }
6097 hash_table_[index] = virtual_method_index;
6098 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006099
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006100 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006101 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006102 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006103 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006104 size_t index = hash % hash_size_;
6105 while (true) {
6106 const uint32_t value = hash_table_[index];
6107 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6108 // the block and can safely assume not found.
6109 if (value == invalid_index_) {
6110 break;
6111 }
6112 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006113 ArtMethod* virtual_method =
6114 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6115 if (comparator->HasSameNameAndSignature(
6116 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006117 hash_table_[index] = removed_index_;
6118 return value;
6119 }
6120 }
6121 if (++index == hash_size_) {
6122 index = 0;
6123 }
6124 }
6125 return GetNotFoundIndex();
6126 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006127
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006128 static uint32_t GetNotFoundIndex() {
6129 return invalid_index_;
6130 }
6131
6132 private:
6133 static const uint32_t invalid_index_;
6134 static const uint32_t removed_index_;
6135
6136 Handle<mirror::Class> klass_;
6137 const size_t hash_size_;
6138 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006139 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006140};
6141
6142const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6143const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6144
Stephen Hines1ddd9132017-02-08 01:51:18 -08006145bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006146 Thread* self,
6147 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006148 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006149 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006150 if (klass->IsInterface()) {
6151 // No vtable.
6152 if (!IsUint<16>(num_virtual_methods)) {
6153 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6154 return false;
6155 }
6156 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006157 // Assign each method an IMT index and set the default flag.
6158 for (size_t i = 0; i < num_virtual_methods; ++i) {
6159 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6160 m->SetMethodIndex(i);
6161 if (!m->IsAbstract()) {
6162 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6163 has_defaults = true;
6164 }
6165 }
6166 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6167 // during initialization. This is a performance optimization. We could simply traverse the
6168 // virtual_methods_ array again during initialization.
6169 if (has_defaults) {
6170 klass->SetHasDefaultMethods();
6171 }
6172 return true;
6173 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006174 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6175 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006176 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006177 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006178 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006179 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006180 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006181 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006182 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006183 return false;
6184 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006185 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006186 vtable->SetElementPtrSize(
6187 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006188 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006189 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6190 // might give us new default methods). If no new interfaces then we can skip the rest since
6191 // the class cannot override any of the super-class's methods. This is required for
6192 // correctness since without it we might not update overridden default method vtable entries
6193 // correctly.
6194 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006195 klass->SetVTable(vtable.Get());
6196 return true;
6197 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006198 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006199 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006200 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006201 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006202 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6203 // might give us new default methods). See comment above.
6204 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006205 klass->SetVTable(super_vtable);
6206 return true;
6207 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006208 vtable = hs.NewHandle(
6209 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006210 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006211 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006212 return false;
6213 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006214 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006215 // How the algorithm works:
6216 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6217 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6218 // method which has not been matched to a vtable method, and j if the virtual method at the
6219 // index overrode the super virtual method at index j.
6220 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6221 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6222 // the need for the initial vtable which we later shrink back down).
6223 // 3. Add non overridden methods to the end of the vtable.
6224 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006225 // + 1 so that even if we only have new default methods we will still be able to use this hash
6226 // table (i.e. it will never have 0 size).
6227 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006228 uint32_t* hash_table_ptr;
6229 std::unique_ptr<uint32_t[]> hash_heap_storage;
6230 if (hash_table_size <= kMaxStackHash) {
6231 hash_table_ptr = reinterpret_cast<uint32_t*>(
6232 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6233 } else {
6234 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6235 hash_table_ptr = hash_heap_storage.get();
6236 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006237 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006238 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006239 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006240 DCHECK(klass->GetVirtualMethodDuringLinking(
6241 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006242 hash_table.Add(i);
6243 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006244 // 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 -07006245 // the hash table.
6246 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006247 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006248 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006249 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6250 super_method->GetAccessFlags())) {
6251 // Continue on to the next method since this one is package private and canot be overridden.
6252 // Before Android 4.1, the package-private method super_method might have been incorrectly
6253 // overridden.
6254 continue;
6255 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006256 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006257 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006258 // We remove the method so that subsequent lookups will be faster by making the hash-map
6259 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006260 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6261 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006262 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6263 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006264 if (super_method->IsFinal()) {
6265 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6266 virtual_method->PrettyMethod().c_str(),
6267 super_method->GetDeclaringClassDescriptor());
6268 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006269 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006270 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6271 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006272 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006273 // We didn't directly override this method but we might through default methods...
6274 // Check for default method update.
6275 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006276 switch (FindDefaultMethodImplementation(self,
6277 super_method,
6278 klass,
6279 /*out*/&default_method)) {
6280 case DefaultMethodSearchResult::kDefaultConflict: {
6281 // A conflict was found looking for default methods. Note this (assuming it wasn't
6282 // pre-existing) in the translations map.
6283 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6284 // Don't generate another conflict method to reduce memory use as an optimization.
6285 default_translations->insert(
6286 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6287 }
6288 break;
6289 }
6290 case DefaultMethodSearchResult::kAbstractFound: {
6291 // No conflict but method is abstract.
6292 // We note that this vtable entry must be made abstract.
6293 if (UNLIKELY(!super_method->IsAbstract())) {
6294 default_translations->insert(
6295 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6296 }
6297 break;
6298 }
6299 case DefaultMethodSearchResult::kDefaultFound: {
6300 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6301 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6302 // Found a default method implementation that is new.
6303 // TODO Refactor this add default methods to virtuals here and not in
6304 // LinkInterfaceMethods maybe.
6305 // The problem is default methods might override previously present
6306 // default-method or miranda-method vtable entries from the superclass.
6307 // Unfortunately we need these to be entries in this class's virtuals. We do not
6308 // give these entries there until LinkInterfaceMethods so we pass this map around
6309 // to let it know which vtable entries need to be updated.
6310 // Make a note that vtable entry j must be updated, store what it needs to be updated
6311 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6312 // then.
6313 default_translations->insert(
6314 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006315 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6316 << " overridden by default "
6317 << default_method->PrettyMethod()
6318 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006319 }
6320 break;
6321 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006322 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006323 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006324 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006325 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006326 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006327 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006328 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006329 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6330 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006331 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006332 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006333 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006334 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006335 local_method->SetMethodIndex(actual_count);
6336 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006337 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006338 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006339 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006340 return false;
6341 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006342 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006343 CHECK_LE(actual_count, max_count);
6344 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006345 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006346 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006347 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006348 return false;
6349 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006350 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006351 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006352 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006353 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006354 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006355 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6356 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006357 return false;
6358 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006359 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006360 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006361 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006362 return false;
6363 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006364 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006365 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6366 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006367 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006368 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006369 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006370 }
6371 return true;
6372}
6373
Alex Light9139e002015-10-09 15:59:48 -07006374// Determine if the given iface has any subinterface in the given list that declares the method
6375// specified by 'target'.
6376//
6377// Arguments
6378// - self: The thread we are running on
6379// - target: A comparator that will match any method that overrides the method we are checking for
6380// - iftable: The iftable we are searching for an overriding method on.
6381// - ifstart: The index of the interface we are checking to see if anything overrides
6382// - iface: The interface we are checking to see if anything overrides.
6383// - image_pointer_size:
6384// The image pointer size.
6385//
6386// Returns
6387// - True: There is some method that matches the target comparator defined in an interface that
6388// is a subtype of iface.
6389// - False: There is no method that matches the target comparator in any interface that is a subtype
6390// of iface.
6391static bool ContainsOverridingMethodOf(Thread* self,
6392 MethodNameAndSignatureComparator& target,
6393 Handle<mirror::IfTable> iftable,
6394 size_t ifstart,
6395 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006396 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006397 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006398 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006399 DCHECK(iface != nullptr);
6400 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006401 DCHECK_GE(ifstart, 0u);
6402 DCHECK_LT(ifstart, iftable->Count());
6403 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6404 DCHECK(iface->IsInterface());
6405
6406 size_t iftable_count = iftable->Count();
6407 StackHandleScope<1> hs(self);
6408 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6409 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6410 // Skip ifstart since our current interface obviously cannot override itself.
6411 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006412 // Iterate through every method on this interface. The order does not matter.
6413 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006414 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006415 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006416 // Check if the i'th interface is a subtype of this one.
6417 if (iface->IsAssignableFrom(current_iface.Get())) {
6418 return true;
6419 }
6420 break;
6421 }
6422 }
6423 }
6424 return false;
6425}
6426
Alex Lighteb7c1442015-08-31 13:17:42 -07006427// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006428// out_default_method and returns kDefaultFound on success. If no default method was found return
6429// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6430// default_method conflict) it will return kDefaultConflict.
6431ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6432 Thread* self,
6433 ArtMethod* target_method,
6434 Handle<mirror::Class> klass,
6435 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006436 DCHECK(self != nullptr);
6437 DCHECK(target_method != nullptr);
6438 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006439
6440 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006441
6442 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6443 // table. This lets us walk the table backwards when searching for default methods. The first one
6444 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6445 // track of it and then continue checking all other interfaces, since we need to throw an error if
6446 // we encounter conflicting default method implementations (one is not a subtype of the other).
6447 //
6448 // The order of unrelated interfaces does not matter and is not defined.
6449 size_t iftable_count = klass->GetIfTableCount();
6450 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006451 // No interfaces. We have already reset out to null so just return kAbstractFound.
6452 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 }
6454
Alex Light9139e002015-10-09 15:59:48 -07006455 StackHandleScope<3> hs(self);
6456 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006457 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006458 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006459 MethodNameAndSignatureComparator target_name_comparator(
6460 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6461 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006462 for (size_t k = iftable_count; k != 0; ) {
6463 --k;
6464
Alex Lighteb7c1442015-08-31 13:17:42 -07006465 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006466
6467 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006468 // Iterate through every declared method on this interface. The order does not matter.
6469 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6470 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006471 // Skip abstract methods and methods with different names.
6472 if (current_method->IsAbstract() ||
6473 !target_name_comparator.HasSameNameAndSignature(
6474 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6475 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006476 } else if (!current_method->IsPublic()) {
6477 // The verifier should have caught the non-public method for dex version 37. Just warn and
6478 // skip it since this is from before default-methods so we don't really need to care that it
6479 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006480 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6481 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006482 << "This will be a fatal error in subsequent versions of android. "
6483 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006484 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006485 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006486 // We have multiple default impls of the same method. This is a potential default conflict.
6487 // We need to check if this possibly conflicting method is either a superclass of the chosen
6488 // default implementation or is overridden by a non-default interface method. In either case
6489 // there is no conflict.
6490 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6491 !ContainsOverridingMethodOf(self,
6492 target_name_comparator,
6493 iftable,
6494 k,
6495 iface,
6496 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006497 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006498 << current_method->PrettyMethod() << " and "
6499 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6500 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006501 *out_default_method = nullptr;
6502 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006503 } else {
6504 break; // Continue checking at the next interface.
6505 }
6506 } else {
Alex Light9139e002015-10-09 15:59:48 -07006507 // chosen_iface == null
6508 if (!ContainsOverridingMethodOf(self,
6509 target_name_comparator,
6510 iftable,
6511 k,
6512 iface,
6513 image_pointer_size_)) {
6514 // Don't set this as the chosen interface if something else is overriding it (because that
6515 // other interface would be potentially chosen instead if it was default). If the other
6516 // interface was abstract then we wouldn't select this interface as chosen anyway since
6517 // the abstract method masks it.
6518 *out_default_method = current_method;
6519 chosen_iface.Assign(iface.Get());
6520 // We should now finish traversing the graph to find if we have default methods that
6521 // conflict.
6522 } else {
David Sehr709b0702016-10-13 09:12:37 -07006523 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6524 << "' was "
6525 << "skipped because it was overridden by an abstract method in a "
6526 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006527 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006528 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006529 break;
6530 }
6531 }
Alex Light9139e002015-10-09 15:59:48 -07006532 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006533 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6534 << "' selected "
6535 << "as the implementation for '" << target_method->PrettyMethod()
6536 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006537 return DefaultMethodSearchResult::kDefaultFound;
6538 } else {
6539 return DefaultMethodSearchResult::kAbstractFound;
6540 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006541}
6542
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006543ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006544 ArtMethod* conflict_method,
6545 ArtMethod* interface_method,
6546 ArtMethod* method,
6547 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006548 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006549 Runtime* const runtime = Runtime::Current();
6550 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6551 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6552
6553 // Create a new entry if the existing one is the shared conflict method.
6554 ArtMethod* new_conflict_method = new_entry
6555 ? runtime->CreateImtConflictMethod(linear_alloc)
6556 : conflict_method;
6557
6558 // Allocate a new table. Note that we will leak this table at the next conflict,
6559 // but that's a tradeoff compared to making the table fixed size.
6560 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006561 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6562 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006563 if (data == nullptr) {
6564 LOG(ERROR) << "Failed to allocate conflict table";
6565 return conflict_method;
6566 }
6567 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6568 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006569 method,
6570 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006571
6572 // Do a fence to ensure threads see the data in the table before it is assigned
6573 // to the conflict method.
6574 // Note that there is a race in the presence of multiple threads and we may leak
6575 // memory from the LinearAlloc, but that's a tradeoff compared to using
6576 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006577 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006578 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006579 return new_conflict_method;
6580}
6581
Vladimir Marko921094a2017-01-12 18:37:06 +00006582bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6583 Handle<mirror::Class> klass,
6584 Handle<mirror::IfTable> iftable) {
6585 DCHECK(!klass->IsInterface());
6586 const bool has_superclass = klass->HasSuperClass();
6587 const bool extend_super_iftable = has_superclass;
6588 const size_t ifcount = klass->GetIfTableCount();
6589 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6590 for (size_t i = 0; i < ifcount; ++i) {
6591 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6592 if (num_methods > 0) {
6593 const bool is_super = i < super_ifcount;
6594 // This is an interface implemented by a super-class. Therefore we can just copy the method
6595 // array from the superclass.
6596 const bool super_interface = is_super && extend_super_iftable;
6597 ObjPtr<mirror::PointerArray> method_array;
6598 if (super_interface) {
6599 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6600 DCHECK(if_table != nullptr);
6601 DCHECK(if_table->GetMethodArray(i) != nullptr);
6602 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006603 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6604 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006605 } else {
6606 method_array = AllocPointerArray(self, num_methods);
6607 }
6608 if (UNLIKELY(method_array == nullptr)) {
6609 self->AssertPendingOOMException();
6610 return false;
6611 }
6612 iftable->SetMethodArray(i, method_array);
6613 }
6614 }
6615 return true;
6616}
6617
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006618void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6619 ArtMethod* imt_conflict_method,
6620 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006621 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006622 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006623 // Place method in imt if entry is empty, place conflict otherwise.
6624 if (*imt_ref == unimplemented_method) {
6625 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006626 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006627 // If we are not a conflict and we have the same signature and name as the imt
6628 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006629 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6630 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006631 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006632 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006633 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006634 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006635 *imt_ref = current_method;
6636 } else {
Alex Light9139e002015-10-09 15:59:48 -07006637 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006638 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006639 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006640 } else {
6641 // Place the default conflict method. Note that there may be an existing conflict
6642 // method in the IMT, but it could be one tailored to the super class, with a
6643 // specific ImtConflictTable.
6644 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006645 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006646 }
6647}
6648
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006649void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006650 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6651 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006652 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006653 Runtime* const runtime = Runtime::Current();
6654 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6655 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006656 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006657 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006658 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006659 FillIMTFromIfTable(klass->GetIfTable(),
6660 unimplemented_method,
6661 conflict_method,
6662 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006663 /*create_conflict_tables=*/true,
6664 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006665 &new_conflict,
6666 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006667 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006668 if (!klass->ShouldHaveImt()) {
6669 return;
6670 }
6671 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6672 // we can just use the same pointer.
6673 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006674 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006675 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6676 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6677 bool same = true;
6678 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6679 ArtMethod* method = imt_data[i];
6680 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6681 if (method != super_method) {
6682 bool is_conflict_table = method->IsRuntimeMethod() &&
6683 method != unimplemented_method &&
6684 method != conflict_method;
6685 // Verify conflict contents.
6686 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6687 super_method != unimplemented_method &&
6688 super_method != conflict_method;
6689 if (!is_conflict_table || !super_conflict_table) {
6690 same = false;
6691 } else {
6692 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6693 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6694 same = same && table1->Equals(table2, image_pointer_size_);
6695 }
6696 }
6697 }
6698 if (same) {
6699 imt = super_imt;
6700 }
6701 }
6702 if (imt == nullptr) {
6703 imt = klass->GetImt(image_pointer_size_);
6704 DCHECK(imt != nullptr);
6705 imt->Populate(imt_data, image_pointer_size_);
6706 } else {
6707 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006708 }
6709}
6710
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006711ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6712 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006713 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006714 void* data = linear_alloc->Alloc(Thread::Current(),
6715 ImtConflictTable::ComputeSize(count,
6716 image_pointer_size));
6717 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6718}
6719
6720ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6721 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6722}
6723
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006724void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006725 ArtMethod* unimplemented_method,
6726 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006727 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006728 bool create_conflict_tables,
6729 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006730 /*out*/bool* new_conflict,
6731 /*out*/ArtMethod** imt) {
6732 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006733 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006734 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006735 const size_t num_virtuals = interface->NumVirtualMethods();
6736 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6737 // Virtual methods can be larger than the if table methods if there are default methods.
6738 DCHECK_GE(num_virtuals, method_array_count);
6739 if (kIsDebugBuild) {
6740 if (klass->IsInterface()) {
6741 DCHECK_EQ(method_array_count, 0u);
6742 } else {
6743 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6744 }
6745 }
6746 if (method_array_count == 0) {
6747 continue;
6748 }
6749 auto* method_array = if_table->GetMethodArray(i);
6750 for (size_t j = 0; j < method_array_count; ++j) {
6751 ArtMethod* implementation_method =
6752 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6753 if (ignore_copied_methods && implementation_method->IsCopied()) {
6754 continue;
6755 }
6756 DCHECK(implementation_method != nullptr);
6757 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6758 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6759 // or interface methods in the IMT here they will not create extra conflicts since we compare
6760 // names and signatures in SetIMTRef.
6761 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006762 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006763
6764 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6765 // the same implementation method, keep track of this to avoid creating a conflict table in
6766 // this case.
6767
6768 // Conflict table size for each IMT slot.
6769 ++conflict_counts[imt_index];
6770
6771 SetIMTRef(unimplemented_method,
6772 imt_conflict_method,
6773 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006774 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006775 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006776 }
6777 }
6778
6779 if (create_conflict_tables) {
6780 // Create the conflict tables.
6781 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006782 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006783 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006784 if (imt[i] == imt_conflict_method) {
6785 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6786 if (new_table != nullptr) {
6787 ArtMethod* new_conflict_method =
6788 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6789 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6790 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006791 } else {
6792 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006793 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006794 }
6795 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006796 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006797 }
6798 }
6799
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006800 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006801 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006802 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6803 // Virtual methods can be larger than the if table methods if there are default methods.
6804 if (method_array_count == 0) {
6805 continue;
6806 }
6807 auto* method_array = if_table->GetMethodArray(i);
6808 for (size_t j = 0; j < method_array_count; ++j) {
6809 ArtMethod* implementation_method =
6810 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6811 if (ignore_copied_methods && implementation_method->IsCopied()) {
6812 continue;
6813 }
6814 DCHECK(implementation_method != nullptr);
6815 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006816 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006817 if (!imt[imt_index]->IsRuntimeMethod() ||
6818 imt[imt_index] == unimplemented_method ||
6819 imt[imt_index] == imt_conflict_method) {
6820 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006822 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6823 const size_t num_entries = table->NumEntries(image_pointer_size_);
6824 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6825 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006826 }
6827 }
6828 }
6829}
6830
Alex Lighteb7c1442015-08-31 13:17:42 -07006831// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6832// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006833static bool NotSubinterfaceOfAny(
6834 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6835 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006836 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006837 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006838 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006839 for (ObjPtr<mirror::Class> c : classes) {
6840 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006841 return false;
6842 }
6843 }
6844 return true;
6845}
6846
6847// Fills in and flattens the interface inheritance hierarchy.
6848//
6849// By the end of this function all interfaces in the transitive closure of to_process are added to
6850// the iftable and every interface precedes all of its sub-interfaces in this list.
6851//
6852// all I, J: Interface | I <: J implies J precedes I
6853//
6854// (note A <: B means that A is a subtype of B)
6855//
6856// This returns the total number of items in the iftable. The iftable might be resized down after
6857// this call.
6858//
6859// We order this backwards so that we do not need to reorder superclass interfaces when new
6860// interfaces are added in subclass's interface tables.
6861//
6862// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6863// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6864// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6865// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006866static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006867 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006868 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006869 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006870 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006871 // This is the set of all class's already in the iftable. Used to make checking if a class has
6872 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006873 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006874 // The first super_ifcount elements are from the superclass. We note that they are already added.
6875 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006876 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006877 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6878 classes_in_iftable.insert(iface);
6879 }
6880 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006881 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006882 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6883 // At this point in the loop current-iface-list has the invariant that:
6884 // for every pair of interfaces I,J within it:
6885 // if index_of(I) < index_of(J) then I is not a subtype of J
6886
6887 // If we have already seen this element then all of its super-interfaces must already be in the
6888 // current-iface-list so we can skip adding it.
6889 if (!ContainsElement(classes_in_iftable, interface)) {
6890 // We haven't seen this interface so add all of its super-interfaces onto the
6891 // current-iface-list, skipping those already on it.
6892 int32_t ifcount = interface->GetIfTableCount();
6893 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006894 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 if (!ContainsElement(classes_in_iftable, super_interface)) {
6896 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6897 classes_in_iftable.insert(super_interface);
6898 iftable->SetInterface(filled_ifcount, super_interface);
6899 filled_ifcount++;
6900 }
6901 }
6902 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6903 // Place this interface onto the current-iface-list after all of its super-interfaces.
6904 classes_in_iftable.insert(interface);
6905 iftable->SetInterface(filled_ifcount, interface);
6906 filled_ifcount++;
6907 } else if (kIsDebugBuild) {
6908 // Check all super-interfaces are already in the list.
6909 int32_t ifcount = interface->GetIfTableCount();
6910 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006911 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006912 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006913 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6914 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006915 }
6916 }
6917 }
6918 if (kIsDebugBuild) {
6919 // Check that the iftable is ordered correctly.
6920 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006921 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006922 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006923 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006924 // !(if_a <: if_b)
6925 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006926 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6927 << ") extends "
6928 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006929 << "interface list.";
6930 }
6931 }
6932 }
6933 return filled_ifcount;
6934}
6935
6936bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6937 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6938 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006939 const bool has_superclass = klass->HasSuperClass();
6940 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006941 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006942 const size_t num_interfaces =
6943 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006944 if (num_interfaces == 0) {
6945 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006946 if (LIKELY(has_superclass)) {
6947 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6948 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006949 // Class implements no interfaces.
6950 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006951 return true;
6952 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006953 // Class implements same interfaces as parent, are any of these not marker interfaces?
6954 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006955 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006956 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006957 if (super_iftable->GetMethodArrayCount(i) > 0) {
6958 has_non_marker_interface = true;
6959 break;
6960 }
6961 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006962 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006963 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006964 klass->SetIfTable(super_iftable);
6965 return true;
6966 }
6967 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006968 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006969 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006970 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006971 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006972 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006973 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006974 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006975 if (UNLIKELY(!interface->IsInterface())) {
6976 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006977 ThrowIncompatibleClassChangeError(klass.Get(),
6978 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006979 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006980 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6981 return false;
6982 }
6983 ifcount += interface->GetIfTableCount();
6984 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006985 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006986 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006987 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006988 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006989 return false;
6990 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006991 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006992 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006993 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006994 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006995 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006996 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006997 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006998 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006999
7000 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7001 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7002 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007003 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007004
7005 size_t new_ifcount;
7006 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007007 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007008 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007009 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007010 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007011 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007012 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007013 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007014
7015 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007016 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007017
Ian Rogers7b078e82014-09-10 14:44:24 -07007018 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007019
Ian Rogersb52b01a2012-01-12 17:01:38 -08007020 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007021 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007022 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007023 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007024 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007025 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007026 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007027 return false;
7028 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007029 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007030 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007031 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007032 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007033 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007034 return true;
7035}
7036
Alex Light1f3925d2016-09-07 12:04:20 -07007037// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7038// of methods must be unique.
7039static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7040 return nullptr;
7041}
7042
7043template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007044static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007045 const ScopedArenaVector<ArtMethod*>& list,
7046 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007047 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007048 for (ArtMethod* method : list) {
7049 if (cmp.HasSameNameAndSignature(method)) {
7050 return method;
7051 }
7052 }
Alex Light1f3925d2016-09-07 12:04:20 -07007053 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007054}
7055
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007056namespace {
7057
Alex Light1f3925d2016-09-07 12:04:20 -07007058// Check that all vtable entries are present in this class's virtuals or are the same as a
7059// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007060void CheckClassOwnsVTableEntries(Thread* self,
7061 Handle<mirror::Class> klass,
7062 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007063 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007064 StackHandleScope<2> hs(self);
7065 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007066 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007067 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007068 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007069 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7070 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7071 CHECK(m != nullptr);
7072
Alex Lighta41a30782017-03-29 11:33:19 -07007073 if (m->GetMethodIndexDuringLinking() != i) {
7074 LOG(WARNING) << m->PrettyMethod()
7075 << " has an unexpected method index for its spot in the vtable for class"
7076 << klass->PrettyClass();
7077 }
Alex Lighte64300b2015-12-15 15:02:47 -08007078 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7079 auto is_same_method = [m] (const ArtMethod& meth) {
7080 return &meth == m;
7081 };
Alex Light3f980532017-03-17 15:10:32 -07007082 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7083 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7084 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7085 << klass->PrettyClass() << " or any of its superclasses!";
7086 }
Alex Lighte64300b2015-12-15 15:02:47 -08007087 }
7088}
7089
Alex Light1f3925d2016-09-07 12:04:20 -07007090// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7091// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007092template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007093void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007094 REQUIRES_SHARED(Locks::mutator_lock_) {
7095 StackHandleScope<1> hs(self);
7096 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7097 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007098
7099 // Observations:
7100 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7101 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7102 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7103 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7104 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7105 // * The single-pass algorithm will trade memory for speed, but that is OK.
7106
7107 CHECK_GT(num_entries, 0);
7108
7109 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7110 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7111 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7112 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7113 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7114 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7115 << m2->PrettyMethod() << " (0x" << std::hex
7116 << reinterpret_cast<uintptr_t>(m2) << ")";
7117 };
7118 struct BaseHashType {
7119 static size_t HashCombine(size_t seed, size_t val) {
7120 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7121 }
7122 };
7123
7124 // Check assuming all entries come from the same dex file.
7125 {
7126 // Find the first interesting method and its dex file.
7127 int32_t start = 0;
7128 for (; start < num_entries; ++start) {
7129 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7130 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7131 // maybe).
7132 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7133 vtable_entry->GetAccessFlags())) {
7134 continue;
7135 }
7136 break;
7137 }
7138 if (start == num_entries) {
7139 return;
7140 }
7141 const DexFile* dex_file =
7142 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7143 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7144
7145 // Helper function to avoid logging if we have to run the cross-file checks.
7146 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7147 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7148 using PairType = std::pair<uint32_t, uint16_t>;
7149 struct PairHash : BaseHashType {
7150 size_t operator()(const PairType& key) const {
7151 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7152 }
7153 };
7154 std::unordered_map<PairType, int32_t, PairHash> seen;
7155 seen.reserve(2 * num_entries);
7156 bool need_slow_path = false;
7157 bool found_dup = false;
7158 for (int i = start; i < num_entries; ++i) {
7159 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7160 // wrt/ kPointerSize.
7161 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7162 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7163 vtable_entry->GetAccessFlags())) {
7164 continue;
7165 }
7166 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7167 if (dex_file != m->GetDexFile()) {
7168 need_slow_path = true;
7169 break;
7170 }
7171 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7172 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7173 auto it = seen.find(pair);
7174 if (it != seen.end()) {
7175 found_dup = true;
7176 if (log_warn) {
7177 log_fn(it->second, i);
7178 }
7179 } else {
7180 seen.emplace(pair, i);
7181 }
7182 }
7183 return std::make_pair(need_slow_path, found_dup);
7184 };
7185 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7186 if (!result.first) {
7187 if (result.second) {
7188 check_fn(/* log_warn= */ true);
7189 }
7190 return;
7191 }
7192 }
7193
7194 // Need to check across dex files.
7195 struct Entry {
7196 size_t cached_hash = 0;
7197 const char* name = nullptr;
7198 Signature signature = Signature::NoSignature();
7199 uint32_t name_len = 0;
7200
7201 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7202 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7203 signature(dex_file->GetMethodSignature(mid)) {
7204 }
7205
7206 bool operator==(const Entry& other) const {
7207 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7208 return false;
7209 }
7210 return signature == other.signature;
7211 }
7212 };
7213 struct EntryHash {
7214 size_t operator()(const Entry& key) const {
7215 return key.cached_hash;
7216 }
7217 };
7218 std::unordered_map<Entry, int32_t, EntryHash> map;
7219 for (int32_t i = 0; i < num_entries; ++i) {
7220 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7221 // wrt/ kPointerSize.
7222 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7223 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7224 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007225 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7226 vtable_entry->GetAccessFlags())) {
7227 continue;
7228 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007229 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7230 const DexFile* dex_file = m->GetDexFile();
7231 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7232
7233 Entry e(dex_file, mid);
7234
7235 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7236 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7237 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7238 sig_hash);
7239
7240 auto it = map.find(e);
7241 if (it != map.end()) {
7242 log_fn(it->second, i);
7243 } else {
7244 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007245 }
7246 }
7247}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007248
7249void CheckVTableHasNoDuplicates(Thread* self,
7250 Handle<mirror::Class> klass,
7251 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007252 REQUIRES_SHARED(Locks::mutator_lock_) {
7253 switch (pointer_size) {
7254 case PointerSize::k64:
7255 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7256 break;
7257 case PointerSize::k32:
7258 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7259 break;
7260 }
7261}
Alex Light1f3925d2016-09-07 12:04:20 -07007262
7263static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7264 REQUIRES_SHARED(Locks::mutator_lock_) {
7265 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7266 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7267}
7268
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007269} // namespace
7270
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007271void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7272 ArtMethod* unimplemented_method,
7273 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007274 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007275 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007276 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007277 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007278 if (super_class->ShouldHaveImt()) {
7279 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7280 for (size_t i = 0; i < ImTable::kSize; ++i) {
7281 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007282 }
7283 } else {
7284 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007285 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007286 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007287 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007288 FillIMTFromIfTable(if_table,
7289 unimplemented_method,
7290 imt_conflict_method,
7291 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007292 /*create_conflict_tables=*/false,
7293 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007294 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007295 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007296 }
7297 }
7298}
7299
Vladimir Marko921094a2017-01-12 18:37:06 +00007300class ClassLinker::LinkInterfaceMethodsHelper {
7301 public:
7302 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7303 Handle<mirror::Class> klass,
7304 Thread* self,
7305 Runtime* runtime)
7306 : class_linker_(class_linker),
7307 klass_(klass),
7308 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7309 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7310 self_(self),
7311 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7312 allocator_(&stack_),
7313 default_conflict_methods_(allocator_.Adapter()),
7314 overriding_default_conflict_methods_(allocator_.Adapter()),
7315 miranda_methods_(allocator_.Adapter()),
7316 default_methods_(allocator_.Adapter()),
7317 overriding_default_methods_(allocator_.Adapter()),
7318 move_table_(allocator_.Adapter()) {
7319 }
7320
7321 ArtMethod* FindMethod(ArtMethod* interface_method,
7322 MethodNameAndSignatureComparator& interface_name_comparator,
7323 ArtMethod* vtable_impl)
7324 REQUIRES_SHARED(Locks::mutator_lock_);
7325
7326 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7327 MethodNameAndSignatureComparator& interface_name_comparator)
7328 REQUIRES_SHARED(Locks::mutator_lock_);
7329
7330 bool HasNewVirtuals() const {
7331 return !(miranda_methods_.empty() &&
7332 default_methods_.empty() &&
7333 overriding_default_methods_.empty() &&
7334 overriding_default_conflict_methods_.empty() &&
7335 default_conflict_methods_.empty());
7336 }
7337
7338 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7339
7340 ObjPtr<mirror::PointerArray> UpdateVtable(
7341 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7342 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7343
7344 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7345
7346 void UpdateIMT(ArtMethod** out_imt);
7347
7348 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7349 if (kIsDebugBuild) {
7350 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7351 // Check that there are no stale methods are in the dex cache array.
7352 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7353 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007354 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7355 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007356 CHECK(move_table_.find(m) == move_table_.end() ||
7357 // The original versions of copied methods will still be present so allow those too.
7358 // Note that if the first check passes this might fail to GetDeclaringClass().
7359 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7360 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7361 [m] (ArtMethod& meth) {
7362 return &meth == m;
7363 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7364 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7365 }
7366 }
7367 }
7368
7369 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7370 LengthPrefixedArray<ArtMethod>* methods) {
7371 if (kIsDebugBuild) {
7372 CHECK(methods != nullptr);
7373 // Put some random garbage in old methods to help find stale pointers.
7374 if (methods != old_methods && old_methods != nullptr) {
7375 // Need to make sure the GC is not running since it could be scanning the methods we are
7376 // about to overwrite.
7377 ScopedThreadStateChange tsc(self_, kSuspended);
7378 gc::ScopedGCCriticalSection gcs(self_,
7379 gc::kGcCauseClassLinker,
7380 gc::kCollectorTypeClassLinker);
7381 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7382 method_size_,
7383 method_alignment_);
7384 memset(old_methods, 0xFEu, old_size);
7385 }
7386 }
7387 }
7388
7389 private:
7390 size_t NumberOfNewVirtuals() const {
7391 return miranda_methods_.size() +
7392 default_methods_.size() +
7393 overriding_default_conflict_methods_.size() +
7394 overriding_default_methods_.size() +
7395 default_conflict_methods_.size();
7396 }
7397
7398 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7399 return !klass_->IsInterface();
7400 }
7401
7402 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7403 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7404 << "Interfaces should only have default-conflict methods appended to them.";
7405 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7406 << miranda_methods_.size()
7407 << " default_methods=" << default_methods_.size()
7408 << " overriding_default_methods=" << overriding_default_methods_.size()
7409 << " default_conflict_methods=" << default_conflict_methods_.size()
7410 << " overriding_default_conflict_methods="
7411 << overriding_default_conflict_methods_.size();
7412 }
7413
7414 ClassLinker* class_linker_;
7415 Handle<mirror::Class> klass_;
7416 size_t method_alignment_;
7417 size_t method_size_;
7418 Thread* const self_;
7419
7420 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7421 // the virtual methods array.
7422 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7423 // during cross compilation.
7424 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7425 ArenaStack stack_;
7426 ScopedArenaAllocator allocator_;
7427
7428 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7429 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7430 ScopedArenaVector<ArtMethod*> miranda_methods_;
7431 ScopedArenaVector<ArtMethod*> default_methods_;
7432 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7433
7434 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7435};
7436
7437ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7438 ArtMethod* interface_method,
7439 MethodNameAndSignatureComparator& interface_name_comparator,
7440 ArtMethod* vtable_impl) {
7441 ArtMethod* current_method = nullptr;
7442 switch (class_linker_->FindDefaultMethodImplementation(self_,
7443 interface_method,
7444 klass_,
7445 /*out*/&current_method)) {
7446 case DefaultMethodSearchResult::kDefaultConflict: {
7447 // Default method conflict.
7448 DCHECK(current_method == nullptr);
7449 ArtMethod* default_conflict_method = nullptr;
7450 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7451 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7452 default_conflict_method = vtable_impl;
7453 } else {
7454 // See if we already have a conflict method for this method.
7455 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7456 interface_name_comparator,
7457 default_conflict_methods_,
7458 overriding_default_conflict_methods_);
7459 if (LIKELY(preexisting_conflict != nullptr)) {
7460 // We already have another conflict we can reuse.
7461 default_conflict_method = preexisting_conflict;
7462 } else {
7463 // Note that we do this even if we are an interface since we need to create this and
7464 // cannot reuse another classes.
7465 // Create a new conflict method for this to use.
7466 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7467 new(default_conflict_method) ArtMethod(interface_method,
7468 class_linker_->GetImagePointerSize());
7469 if (vtable_impl == nullptr) {
7470 // Save the conflict method. We need to add it to the vtable.
7471 default_conflict_methods_.push_back(default_conflict_method);
7472 } else {
7473 // Save the conflict method but it is already in the vtable.
7474 overriding_default_conflict_methods_.push_back(default_conflict_method);
7475 }
7476 }
7477 }
7478 current_method = default_conflict_method;
7479 break;
7480 } // case kDefaultConflict
7481 case DefaultMethodSearchResult::kDefaultFound: {
7482 DCHECK(current_method != nullptr);
7483 // Found a default method.
7484 if (vtable_impl != nullptr &&
7485 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7486 // We found a default method but it was the same one we already have from our
7487 // superclass. Don't bother adding it to our vtable again.
7488 current_method = vtable_impl;
7489 } else if (LIKELY(FillTables())) {
7490 // Interfaces don't need to copy default methods since they don't have vtables.
7491 // Only record this default method if it is new to save space.
7492 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7493 // would make lookup for interface super much faster. (We would only need to scan
7494 // the iftable to find if there is a NSME or AME.)
7495 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7496 default_methods_,
7497 overriding_default_methods_);
7498 if (old == nullptr) {
7499 // We found a default method implementation and there were no conflicts.
7500 if (vtable_impl == nullptr) {
7501 // Save the default method. We need to add it to the vtable.
7502 default_methods_.push_back(current_method);
7503 } else {
7504 // Save the default method but it is already in the vtable.
7505 overriding_default_methods_.push_back(current_method);
7506 }
7507 } else {
7508 CHECK(old == current_method) << "Multiple default implementations selected!";
7509 }
7510 }
7511 break;
7512 } // case kDefaultFound
7513 case DefaultMethodSearchResult::kAbstractFound: {
7514 DCHECK(current_method == nullptr);
7515 // Abstract method masks all defaults.
7516 if (vtable_impl != nullptr &&
7517 vtable_impl->IsAbstract() &&
7518 !vtable_impl->IsDefaultConflicting()) {
7519 // We need to make this an abstract method but the version in the vtable already is so
7520 // don't do anything.
7521 current_method = vtable_impl;
7522 }
7523 break;
7524 } // case kAbstractFound
7525 }
7526 return current_method;
7527}
7528
7529ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7530 ArtMethod* interface_method,
7531 MethodNameAndSignatureComparator& interface_name_comparator) {
7532 // Find out if there is already a miranda method we can use.
7533 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7534 miranda_methods_);
7535 if (miranda_method == nullptr) {
7536 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7537 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7538 CHECK(miranda_method != nullptr);
7539 // Point the interface table at a phantom slot.
7540 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7541 miranda_methods_.push_back(miranda_method);
7542 }
7543 return miranda_method;
7544}
7545
7546void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7547 LogNewVirtuals();
7548
7549 const size_t old_method_count = klass_->NumMethods();
7550 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7551 DCHECK_NE(old_method_count, new_method_count);
7552
7553 // Attempt to realloc to save RAM if possible.
7554 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7555 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7556 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7557 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7558 // CopyFrom has internal read barriers.
7559 //
7560 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7561 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7562 method_size_,
7563 method_alignment_);
7564 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7565 method_size_,
7566 method_alignment_);
7567 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7568 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007569 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007570 self_, old_methods, old_methods_ptr_size, new_size));
7571 CHECK(methods != nullptr); // Native allocation failure aborts.
7572
7573 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7574 if (methods != old_methods) {
7575 // Maps from heap allocated miranda method to linear alloc miranda method.
7576 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7577 // Copy over the old methods.
7578 for (auto& m : klass_->GetMethods(pointer_size)) {
7579 move_table_.emplace(&m, &*out);
7580 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7581 // barriers when it copies.
7582 out->CopyFrom(&m, pointer_size);
7583 ++out;
7584 }
7585 }
7586 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7587 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7588 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007589 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7590 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007591 ArtMethod& new_method = *out;
7592 new_method.CopyFrom(mir_method, pointer_size);
7593 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7594 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7595 << "Miranda method should be abstract!";
7596 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007597 // Update the entry in the method array, as the array will be used for future lookups,
7598 // where thread suspension is allowed.
7599 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7600 // would not see them.
7601 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007602 ++out;
7603 }
7604 // We need to copy the default methods into our own method table since the runtime requires that
7605 // every method on a class's vtable be in that respective class's virtual method table.
7606 // NOTE This means that two classes might have the same implementation of a method from the same
7607 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7608 // default method found on a class with one found on the declaring interface directly and must
7609 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007610 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7611 &overriding_default_methods_}) {
7612 for (size_t i = 0; i < methods_vec->size(); ++i) {
7613 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007614 ArtMethod& new_method = *out;
7615 new_method.CopyFrom(def_method, pointer_size);
7616 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7617 // verified yet it shouldn't have methods that are skipping access checks.
7618 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7619 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007620 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007621 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7622 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7623 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7624 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007625 // Update the entry in the method array, as the array will be used for future lookups,
7626 // where thread suspension is allowed.
7627 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7628 // would not see them.
7629 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007630 ++out;
7631 }
7632 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007633 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7634 &overriding_default_conflict_methods_}) {
7635 for (size_t i = 0; i < methods_vec->size(); ++i) {
7636 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007637 ArtMethod& new_method = *out;
7638 new_method.CopyFrom(conf_method, pointer_size);
7639 // This is a type of default method (there are default method impls, just a conflict) so
7640 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7641 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7642 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007643 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7644 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007645 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007646 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007647 constexpr uint32_t kMaskFlags =
7648 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007649 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7650 DCHECK(new_method.IsDefaultConflicting());
7651 // The actual method might or might not be marked abstract since we just copied it from a
7652 // (possibly default) interface method. We need to set it entry point to be the bridge so
7653 // that the compiler will not invoke the implementation of whatever method we copied from.
7654 EnsureThrowsInvocationError(class_linker_, &new_method);
7655 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007656 // Update the entry in the method array, as the array will be used for future lookups,
7657 // where thread suspension is allowed.
7658 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7659 // would not see them.
7660 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007661 ++out;
7662 }
7663 }
7664 methods->SetSize(new_method_count);
7665 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7666}
7667
7668ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7669 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7670 ObjPtr<mirror::PointerArray> old_vtable) {
7671 // Update the vtable to the new method structures. We can skip this for interfaces since they
7672 // do not have vtables.
7673 const size_t old_vtable_count = old_vtable->GetLength();
7674 const size_t new_vtable_count = old_vtable_count +
7675 miranda_methods_.size() +
7676 default_methods_.size() +
7677 default_conflict_methods_.size();
7678
7679 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007680 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007681 if (UNLIKELY(vtable == nullptr)) {
7682 self_->AssertPendingOOMException();
7683 return nullptr;
7684 }
7685
7686 size_t vtable_pos = old_vtable_count;
7687 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7688 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7689 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7690 default_conflict_methods_,
7691 miranda_methods_}) {
7692 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007693 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007694 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7695 // fields are references into the dex file the method was defined in. Since the ArtMethod
7696 // does not store that information it uses declaring_class_->dex_cache_.
7697 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7698 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7699 ++vtable_pos;
7700 }
7701 }
7702 DCHECK_EQ(vtable_pos, new_vtable_count);
7703
7704 // Update old vtable methods. We use the default_translations map to figure out what each
7705 // vtable entry should be updated to, if they need to be at all.
7706 for (size_t i = 0; i < old_vtable_count; ++i) {
7707 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7708 // Try and find what we need to change this method to.
7709 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007710 if (translation_it != default_translations.end()) {
7711 if (translation_it->second.IsInConflict()) {
7712 // Find which conflict method we are to use for this method.
7713 MethodNameAndSignatureComparator old_method_comparator(
7714 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7715 // We only need to look through overriding_default_conflict_methods since this is an
7716 // overridden method we are fixing up here.
7717 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7718 old_method_comparator, overriding_default_conflict_methods_);
7719 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7720 translated_method = new_conflict_method;
7721 } else if (translation_it->second.IsAbstract()) {
7722 // Find which miranda method we are to use for this method.
7723 MethodNameAndSignatureComparator old_method_comparator(
7724 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7725 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7726 miranda_methods_);
7727 DCHECK(miranda_method != nullptr);
7728 translated_method = miranda_method;
7729 } else {
7730 // Normal default method (changed from an older default or abstract interface method).
7731 DCHECK(translation_it->second.IsTranslation());
7732 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007733 auto it = move_table_.find(translated_method);
7734 DCHECK(it != move_table_.end());
7735 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007736 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007737 } else {
7738 auto it = move_table_.find(translated_method);
7739 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007740 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007741
7742 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007743 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007744 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007745 if (kIsDebugBuild) {
7746 auto* methods = klass_->GetMethodsPtr();
7747 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007748 reinterpret_cast<uintptr_t>(translated_method));
7749 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007750 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7751 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007752 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007753 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007754 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007755 }
7756 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007757 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007758 return vtable;
7759}
7760
7761void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7762 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7763 const size_t ifcount = klass_->GetIfTableCount();
7764 // Go fix up all the stale iftable pointers.
7765 for (size_t i = 0; i < ifcount; ++i) {
7766 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7767 auto* method_array = iftable->GetMethodArray(i);
7768 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7769 DCHECK(m != nullptr) << klass_->PrettyClass();
7770 auto it = move_table_.find(m);
7771 if (it != move_table_.end()) {
7772 auto* new_m = it->second;
7773 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7774 method_array->SetElementPtrSize(j, new_m, pointer_size);
7775 }
7776 }
7777 }
7778}
7779
7780void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7781 // Fix up IMT next.
7782 for (size_t i = 0; i < ImTable::kSize; ++i) {
7783 auto it = move_table_.find(out_imt[i]);
7784 if (it != move_table_.end()) {
7785 out_imt[i] = it->second;
7786 }
7787 }
7788}
7789
Alex Light705ad492015-09-21 11:36:30 -07007790// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007791bool ClassLinker::LinkInterfaceMethods(
7792 Thread* self,
7793 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007794 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007795 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007796 ArtMethod** out_imt) {
7797 StackHandleScope<3> hs(self);
7798 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007799
7800 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007801 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007802 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007803 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007804 const size_t ifcount = klass->GetIfTableCount();
7805
Vladimir Marko921094a2017-01-12 18:37:06 +00007806 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007807
7808 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7809 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007810 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007811 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007812 const bool extend_super_iftable = has_superclass;
7813 if (has_superclass && fill_tables) {
7814 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007815 unimplemented_method,
7816 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007817 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007818 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007819 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007820 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7821 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007822 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007823 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7824 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007825 }
7826 }
7827
Vladimir Marko921094a2017-01-12 18:37:06 +00007828 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7829
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007830 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007831 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007832 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7833 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7834 // they will already be null. This has the additional benefit that the declarer of a miranda
7835 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007836 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007837 --i;
Alex Light9139e002015-10-09 15:59:48 -07007838 DCHECK_LT(i, ifcount);
7839
Alex Light705ad492015-09-21 11:36:30 -07007840 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007841 if (num_methods > 0) {
7842 StackHandleScope<2> hs2(self);
7843 const bool is_super = i < super_ifcount;
7844 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007845 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7846 // conflict methods. Just set this as nullptr in those cases.
7847 Handle<mirror::PointerArray> method_array(fill_tables
7848 ? hs2.NewHandle(iftable->GetMethodArray(i))
7849 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007850
Alex Lighte64300b2015-12-15 15:02:47 -08007851 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007852 ScopedNullHandle<mirror::PointerArray> null_handle;
7853 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007854 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007855
Alex Light9139e002015-10-09 15:59:48 -07007856 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7857 // and confusing. Default methods should always look through all the superclasses
7858 // because they are the last choice of an implementation. We get around this by looking
7859 // at the super-classes iftable methods (copied into method_array previously) when we are
7860 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007861 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007862 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007863 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007864 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007865 using_virtuals = true;
7866 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7867 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007868 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007869 // For a new interface, however, we need the whole vtable in case a new
7870 // interface method is implemented in the whole superclass.
7871 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007872 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007873 input_vtable_array = vtable;
7874 input_array_length = input_vtable_array->GetLength();
7875 }
Alex Lighte64300b2015-12-15 15:02:47 -08007876
Alex Lighteb7c1442015-08-31 13:17:42 -07007877 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007878 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007879 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007880 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007881 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007882 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007883 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007884 // For each method listed in the interface's method list, find the
7885 // matching method in our class's method list. We want to favor the
7886 // subclass over the superclass, which just requires walking
7887 // back from the end of the vtable. (This only matters if the
7888 // superclass defines a private method and this class redefines
7889 // it -- otherwise it would use the same vtable slot. In .dex files
7890 // those don't end up in the virtual method table, so it shouldn't
7891 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007892 //
7893 // To find defaults we need to do the same but also go over interfaces.
7894 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007895 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007896 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007897 ArtMethod* vtable_method = using_virtuals ?
7898 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007899 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7900 ArtMethod* vtable_method_for_name_comparison =
7901 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007902 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007903 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007904 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007905 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7906 // allocations.
7907 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007908 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007909 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007910 vtable_method->PrettyMethod().c_str(),
7911 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007912 return false;
Alex Light9139e002015-10-09 15:59:48 -07007913 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007914 // We might have a newer, better, default method for this, so we just skip it. If we
7915 // are still using this we will select it again when scanning for default methods. To
7916 // obviate the need to copy the method again we will make a note that we already found
7917 // a default here.
7918 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007919 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007920 break;
7921 } else {
7922 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007923 if (LIKELY(fill_tables)) {
7924 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7925 // Place method in imt if entry is empty, place conflict otherwise.
7926 SetIMTRef(unimplemented_method,
7927 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007928 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007929 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007930 /*out*/imt_ptr);
7931 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007932 break;
7933 }
7934 }
Alex Light9139e002015-10-09 15:59:48 -07007935 }
7936 // Continue on to the next method if we are done.
7937 if (LIKELY(found_impl)) {
7938 continue;
7939 } else if (LIKELY(super_interface)) {
7940 // Don't look for a default implementation when the super-method is implemented directly
7941 // by the class.
7942 //
7943 // See if we can use the superclasses method and skip searching everything else.
7944 // Note: !found_impl && super_interface
7945 CHECK(extend_super_iftable);
7946 // If this is a super_interface method it is possible we shouldn't override it because a
7947 // superclass could have implemented it directly. We get the method the superclass used
7948 // to implement this to know if we can override it with a default method. Doing this is
7949 // safe since we know that the super_iftable is filled in so we can simply pull it from
7950 // there. We don't bother if this is not a super-classes interface since in that case we
7951 // have scanned the entire vtable anyway and would have found it.
7952 // TODO This is rather dirty but it is faster than searching through the entire vtable
7953 // every time.
7954 ArtMethod* supers_method =
7955 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7956 DCHECK(supers_method != nullptr);
7957 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007958 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007959 // The method is not overridable by a default method (i.e. it is directly implemented
7960 // in some class). Therefore move onto the next interface method.
7961 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007962 } else {
7963 // If the super-classes method is override-able by a default method we need to keep
7964 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7965 // 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 -07007966 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7967 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7968 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007969 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007970 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7971 << " and not 'nullptr' or "
7972 << supers_method->PrettyMethod()
7973 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007974 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007975 }
7976 }
7977 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007978 ArtMethod* current_method = helper.FindMethod(interface_method,
7979 interface_name_comparator,
7980 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007981 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007982 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007983 // We could not find an implementation for this method and since it is a brand new
7984 // interface we searched the entire vtable (and all default methods) for an
7985 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007986 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7987 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007988 }
7989
7990 if (current_method != nullptr) {
7991 // We found a default method implementation. Record it in the iftable and IMT.
7992 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7993 SetIMTRef(unimplemented_method,
7994 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007995 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007996 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007997 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007998 }
7999 }
Alex Light705ad492015-09-21 11:36:30 -07008000 } // For each method in interface end.
8001 } // if (num_methods > 0)
8002 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008003 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008004 if (helper.HasNewVirtuals()) {
8005 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8006 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8007 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8008
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008009 // 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 -07008010 // suspension assert.
8011 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008012
Alex Light705ad492015-09-21 11:36:30 -07008013 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008014 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008015 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008016 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008017 return false;
8018 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008019 helper.UpdateIfTable(iftable);
8020 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008021 }
Alex Light705ad492015-09-21 11:36:30 -07008022
Vladimir Marko921094a2017-01-12 18:37:06 +00008023 helper.CheckNoStaleMethodsInDexCache();
8024 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008025 } else {
8026 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008027 }
Alex Light705ad492015-09-21 11:36:30 -07008028 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008029 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008030 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008031 return true;
8032}
8033
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008034bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008035 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008036 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008037}
8038
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008039bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008040 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008041 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008042}
8043
Brian Carlstromdbc05252011-09-09 01:59:59 -07008044struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008045 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008046 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008047 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008048 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008049 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008050 // 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 -07008051 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8052 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008053 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008054 if (type1 == Primitive::kPrimNot) {
8055 // Reference always goes first.
8056 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008057 }
Vladimir Markod5777482014-11-12 17:02:02 +00008058 if (type2 == Primitive::kPrimNot) {
8059 // Reference always goes first.
8060 return false;
8061 }
8062 size_t size1 = Primitive::ComponentSize(type1);
8063 size_t size2 = Primitive::ComponentSize(type2);
8064 if (size1 != size2) {
8065 // Larger primitive types go first.
8066 return size1 > size2;
8067 }
8068 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8069 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008070 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008071 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8072 // by name and for equal names by type id index.
8073 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8074 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008075 }
8076};
8077
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008078bool ClassLinker::LinkFields(Thread* self,
8079 Handle<mirror::Class> klass,
8080 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008081 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008082 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008083 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008084 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8085 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008086
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008087 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008088 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008089 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008090 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008091 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008092 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008093 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008094 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008095 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008096 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008097 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008098 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008099
David Sehr709b0702016-10-13 09:12:37 -07008100 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008101
Brian Carlstromdbc05252011-09-09 01:59:59 -07008102 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008103 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008104 //
8105 // The overall sort order order is:
8106 // 1) All object reference fields, sorted alphabetically.
8107 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8108 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8109 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8110 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8111 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8112 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8113 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8114 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8115 //
8116 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8117 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008118 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008119 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008120 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008121 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008122 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008123 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008124 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8125 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008126
Fred Shih381e4ca2014-08-25 17:24:27 -07008127 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008128 size_t current_field = 0;
8129 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008130 FieldGaps gaps;
8131
Brian Carlstromdbc05252011-09-09 01:59:59 -07008132 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008133 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008134 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008135 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008136 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008137 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008138 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008139 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8140 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008141 MemberOffset old_offset = field_offset;
8142 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8143 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8144 }
Roland Levillain14d90572015-07-16 10:52:26 +01008145 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008146 grouped_and_sorted_fields.pop_front();
8147 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008148 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008149 field_offset = MemberOffset(field_offset.Uint32Value() +
8150 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008151 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008152 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8153 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008154 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8155 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8156 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8157 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008158 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8159 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008160 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008161
Elliott Hughesadb460d2011-10-05 17:02:34 -07008162 // 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 -07008163 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008164 // We know there are no non-reference fields in the Reference classes, and we know
8165 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008166 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008167 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008168 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008169 --num_reference_fields;
8170 }
8171
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008172 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008173 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008174 if (is_static) {
8175 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008176 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008177 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008178 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008179 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008180 if (num_reference_fields == 0 || super_class == nullptr) {
8181 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008182 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008183 if (super_class == nullptr ||
8184 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8185 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008186 }
8187 }
8188 if (kIsDebugBuild) {
8189 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8190 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008191 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008192 while (cur_super != nullptr) {
8193 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8194 cur_super = cur_super->GetSuperClass();
8195 }
8196 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008197 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008198 } else {
8199 // Check that there is at least num_reference_fields other than Object.class.
8200 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008201 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008202 }
8203 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008204 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008205 std::string temp;
8206 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8207 size_t previous_size = klass->GetObjectSize();
8208 if (previous_size != 0) {
8209 // Make sure that we didn't originally have an incorrect size.
8210 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008211 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008212 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008213 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008214 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008215
8216 if (kIsDebugBuild) {
8217 // Make sure that the fields array is ordered by name but all reference
8218 // offsets are at the beginning as far as alignment allows.
8219 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008220 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008221 : klass->GetFirstReferenceInstanceFieldOffset();
8222 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8223 num_reference_fields *
8224 sizeof(mirror::HeapReference<mirror::Object>));
8225 MemberOffset current_ref_offset = start_ref_offset;
8226 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008227 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008228 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008229 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8230 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008231 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008232 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008233 // NOTE: The field names can be the same. This is not possible in the Java language
8234 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008235 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008236 }
8237 Primitive::Type type = field->GetTypeAsPrimitiveType();
8238 bool is_primitive = type != Primitive::kPrimNot;
8239 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8240 strcmp("referent", field->GetName()) == 0) {
8241 is_primitive = true; // We lied above, so we have to expect a lie here.
8242 }
8243 MemberOffset offset = field->GetOffsetDuringLinking();
8244 if (is_primitive) {
8245 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8246 // Shuffled before references.
8247 size_t type_size = Primitive::ComponentSize(type);
8248 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8249 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8250 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8251 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8252 }
8253 } else {
8254 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8255 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8256 sizeof(mirror::HeapReference<mirror::Object>));
8257 }
8258 }
8259 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8260 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008261 return true;
8262}
8263
Vladimir Marko76649e82014-11-10 18:32:59 +00008264// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008265void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008266 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008267 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008268 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008269 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008270 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008271 // Compute reference offsets unless our superclass overflowed.
8272 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8273 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008274 if (num_reference_fields != 0u) {
8275 // All of the fields that contain object references are guaranteed be grouped in memory
8276 // starting at an appropriately aligned address after super class object data.
8277 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8278 sizeof(mirror::HeapReference<mirror::Object>));
8279 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008280 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008281 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008282 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008283 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008284 reference_offsets |= (0xffffffffu << start_bit) &
8285 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008286 }
8287 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008288 }
8289 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008290 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008291}
8292
Vladimir Marko18090d12018-06-01 16:53:12 +01008293ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8294 ObjPtr<mirror::DexCache> dex_cache) {
8295 StackHandleScope<1> hs(Thread::Current());
8296 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8297 return DoResolveString(string_idx, h_dex_cache);
8298}
8299
8300ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8301 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008302 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008303 uint32_t utf16_length;
8304 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008305 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008306 if (string != nullptr) {
8307 dex_cache->SetResolvedString(string_idx, string);
8308 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008309 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008310}
8311
Vladimir Marko18090d12018-06-01 16:53:12 +01008312ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8313 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008314 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008315 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008316 uint32_t utf16_length;
8317 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008318 ObjPtr<mirror::String> string =
8319 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008320 if (string != nullptr) {
8321 dex_cache->SetResolvedString(string_idx, string);
8322 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008323 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008324}
8325
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008326ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008327 ObjPtr<mirror::Class> referrer) {
8328 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8329}
8330
8331ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008332 ObjPtr<mirror::DexCache> dex_cache,
8333 ObjPtr<mirror::ClassLoader> class_loader) {
8334 const DexFile& dex_file = *dex_cache->GetDexFile();
8335 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8336 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8337 ObjPtr<mirror::Class> type = nullptr;
8338 if (descriptor[1] == '\0') {
8339 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8340 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008341 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008342 } else {
8343 Thread* const self = Thread::Current();
8344 DCHECK(self != nullptr);
8345 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8346 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008347 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008348 }
8349 if (type != nullptr) {
8350 if (type->IsResolved()) {
8351 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008352 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008353 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008354 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008355 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008356 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008357}
8358
Andreas Gampe4835d212018-11-21 14:55:10 -08008359template <typename T>
8360ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008361 StackHandleScope<2> hs(Thread::Current());
8362 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8363 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8364 return DoResolveType(type_idx, dex_cache, class_loader);
8365}
8366
Andreas Gampe4835d212018-11-21 14:55:10 -08008367// Instantiate the above.
8368template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8369 ArtField* referrer);
8370template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8371 ArtMethod* referrer);
8372template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8373 ObjPtr<mirror::Class> referrer);
8374
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008375ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008376 Handle<mirror::DexCache> dex_cache,
8377 Handle<mirror::ClassLoader> class_loader) {
8378 Thread* self = Thread::Current();
8379 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8380 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8381 if (resolved != nullptr) {
8382 // TODO: we used to throw here if resolved's class loader was not the
8383 // boot class loader. This was to permit different classes with the
8384 // same name to be loaded simultaneously by different loaders
8385 dex_cache->SetResolvedType(type_idx, resolved);
8386 } else {
8387 CHECK(self->IsExceptionPending())
8388 << "Expected pending exception for failed resolution of: " << descriptor;
8389 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8390 StackHandleScope<1> hs(self);
8391 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008392 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008393 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8394 self->ClearException();
8395 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8396 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008397 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008398 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008399 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008400 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008401 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008402}
8403
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008404ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8405 ObjPtr<mirror::DexCache> dex_cache,
8406 ObjPtr<mirror::ClassLoader> class_loader,
8407 uint32_t method_idx) {
8408 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8409 // functions can optimize the search if the dex_cache is the same as the DexCache
8410 // of the class, with fall-back to name and signature search otherwise.
8411 ArtMethod* resolved = nullptr;
8412 if (klass->IsInterface()) {
8413 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8414 } else {
8415 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8416 }
8417 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008418 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008419 hiddenapi::ShouldDenyAccessToMember(resolved,
8420 hiddenapi::AccessContext(class_loader, dex_cache),
8421 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008422 resolved = nullptr;
8423 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008424 if (resolved != nullptr) {
8425 // In case of jmvti, the dex file gets verified before being registered, so first
8426 // check if it's registered before checking class tables.
8427 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008428 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8429 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008430 << "DexFile referrer: " << dex_file.GetLocation()
8431 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8432 // Be a good citizen and update the dex cache to speed subsequent calls.
8433 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008434 // Disable the following invariant check as the verifier breaks it. b/73760543
8435 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8436 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8437 // << "Method: " << resolved->PrettyMethod() << ", "
8438 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8439 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008440 }
8441 return resolved;
8442}
8443
David Brazdil4525e0b2018-04-05 16:57:32 +01008444// Returns true if `method` is either null or hidden.
8445// Does not print any warnings if it is hidden.
8446static bool CheckNoSuchMethod(ArtMethod* method,
8447 ObjPtr<mirror::DexCache> dex_cache,
8448 ObjPtr<mirror::ClassLoader> class_loader)
8449 REQUIRES_SHARED(Locks::mutator_lock_) {
8450 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008451 hiddenapi::ShouldDenyAccessToMember(method,
8452 hiddenapi::AccessContext(class_loader, dex_cache),
8453 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008454}
8455
8456ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8457 ObjPtr<mirror::DexCache> dex_cache,
8458 ObjPtr<mirror::ClassLoader> class_loader,
8459 uint32_t method_idx) {
8460 if (klass->IsInterface()) {
8461 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8462 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8463 } else {
8464 // If there was an interface method with the same signature, we would have
8465 // found it in the "copied" methods. Only DCHECK that the interface method
8466 // really does not exist.
8467 if (kIsDebugBuild) {
8468 ArtMethod* method =
8469 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8470 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8471 }
8472 return nullptr;
8473 }
8474}
8475
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008476template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008477ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008478 Handle<mirror::DexCache> dex_cache,
8479 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008480 ArtMethod* referrer,
8481 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008482 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008483 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008484 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008485 PointerSize pointer_size = image_pointer_size_;
8486 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008487 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008488 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8489 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008490 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8491 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008492 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008493 return resolved;
8494 }
Vladimir Marko89011192017-12-11 13:45:05 +00008495 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008496 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008497 ObjPtr<mirror::Class> klass = nullptr;
8498 if (valid_dex_cache_method) {
8499 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8500 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008501 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008502 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008503 // We normaly should not end up here. However the verifier currently doesn't guarantee
8504 // the invariant of having the klass in the class table. b/73760543
8505 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008506 }
Vladimir Markoba118822017-06-12 15:41:56 +01008507 } else {
8508 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008509 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008510 if (klass == nullptr) {
8511 DCHECK(Thread::Current()->IsExceptionPending());
8512 return nullptr;
8513 }
8514 }
8515
8516 // Check if the invoke type matches the class type.
8517 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008518 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008519 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008520 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008521 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008522 }
Vladimir Markoba118822017-06-12 15:41:56 +01008523
8524 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008525 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008526 }
Vladimir Markoba118822017-06-12 15:41:56 +01008527
8528 // Note: We can check for IllegalAccessError only if we have a referrer.
8529 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8530 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8531 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8532 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8533 resolved,
8534 dex_cache.Get(),
8535 method_idx,
8536 type)) {
8537 DCHECK(Thread::Current()->IsExceptionPending());
8538 return nullptr;
8539 }
8540 }
8541
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008542 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008543 if (LIKELY(resolved != nullptr) &&
8544 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8545 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008546 return resolved;
8547 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008548 // If we had a method, or if we can find one with another lookup type,
8549 // it's an incompatible-class-change error.
8550 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008551 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008552 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008553 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008554 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008555 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008556 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008557 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8558 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008559 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008560 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008561 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008562 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008563 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008564}
8565
Vladimir Marko89011192017-12-11 13:45:05 +00008566ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008567 Handle<mirror::DexCache> dex_cache,
8568 Handle<mirror::ClassLoader> class_loader) {
8569 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008570 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008571 if (resolved != nullptr) {
8572 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008573 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8574 return resolved;
8575 }
8576 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008577 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008578 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008579 if (klass == nullptr) {
8580 Thread::Current()->AssertPendingException();
8581 return nullptr;
8582 }
8583 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008584 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8585 } else {
8586 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008587 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008588 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008589 hiddenapi::ShouldDenyAccessToMember(
8590 resolved,
8591 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8592 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008593 resolved = nullptr;
8594 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008595 return resolved;
8596}
8597
Vladimir Markof44d36c2017-03-14 14:18:46 +00008598ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8599 ObjPtr<mirror::DexCache> dex_cache,
8600 ObjPtr<mirror::ClassLoader> class_loader,
8601 bool is_static) {
8602 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008603 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008604 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8605 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008606 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008607 }
8608 if (klass == nullptr) {
8609 // The class has not been resolved yet, so the field is also unresolved.
8610 return nullptr;
8611 }
8612 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008613
David Brazdil1ab0fa82018-05-04 11:28:03 +01008614 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008615}
8616
Vladimir Markoe11dd502017-12-08 14:09:45 +00008617ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008618 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008619 Handle<mirror::ClassLoader> class_loader,
8620 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008621 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008622 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008623 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008624 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008625 return resolved;
8626 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008627 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008628 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008629 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008630 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008631 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008632 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008633 }
8634
David Brazdil1ab0fa82018-05-04 11:28:03 +01008635 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008636 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008637 const char* name = dex_file.GetFieldName(field_id);
8638 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008639 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008640 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008641 return resolved;
8642}
8643
Vladimir Markoe11dd502017-12-08 14:09:45 +00008644ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008645 Handle<mirror::DexCache> dex_cache,
8646 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008647 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008648 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008649 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008650 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008651 return resolved;
8652 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008653 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008654 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008655 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008656 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008657 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008658 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008659 }
8660
David Brazdil1ab0fa82018-05-04 11:28:03 +01008661 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8662 if (resolved == nullptr) {
8663 const char* name = dex_file.GetFieldName(field_id);
8664 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008665 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008666 }
8667 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008668}
8669
David Brazdil1ab0fa82018-05-04 11:28:03 +01008670ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8671 ObjPtr<mirror::DexCache> dex_cache,
8672 ObjPtr<mirror::ClassLoader> class_loader,
8673 uint32_t field_idx,
8674 bool is_static) {
8675 ArtField* resolved = nullptr;
8676 Thread* self = is_static ? Thread::Current() : nullptr;
8677 const DexFile& dex_file = *dex_cache->GetDexFile();
8678
8679 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8680 : klass->FindInstanceField(dex_cache, field_idx);
8681
8682 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008683 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008684 const char* name = dex_file.GetFieldName(field_id);
8685 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8686 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8687 : klass->FindInstanceField(name, type);
8688 }
8689
8690 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008691 hiddenapi::ShouldDenyAccessToMember(resolved,
8692 hiddenapi::AccessContext(class_loader, dex_cache),
8693 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008694 resolved = nullptr;
8695 }
8696
8697 if (resolved != nullptr) {
8698 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8699 }
8700
8701 return resolved;
8702}
8703
8704ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8705 ObjPtr<mirror::DexCache> dex_cache,
8706 ObjPtr<mirror::ClassLoader> class_loader,
8707 uint32_t field_idx) {
8708 ArtField* resolved = nullptr;
8709 Thread* self = Thread::Current();
8710 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008711 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008712
8713 const char* name = dex_file.GetFieldName(field_id);
8714 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8715 resolved = mirror::Class::FindField(self, klass, name, type);
8716
8717 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008718 hiddenapi::ShouldDenyAccessToMember(resolved,
8719 hiddenapi::AccessContext(class_loader, dex_cache),
8720 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008721 resolved = nullptr;
8722 }
8723
8724 if (resolved != nullptr) {
8725 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8726 }
8727
8728 return resolved;
8729}
8730
Vladimir Markoaf940202017-12-08 15:01:18 +00008731ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8732 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008733 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008734 Handle<mirror::DexCache> dex_cache,
8735 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008736 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008737 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008738
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008739 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008740 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008741 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008742 }
8743
Narayan Kamath25352fc2016-08-03 12:46:58 +01008744 StackHandleScope<4> hs(self);
8745
8746 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008747 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008748 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008749 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008750 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008751 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008752 DCHECK(self->IsExceptionPending());
8753 return nullptr;
8754 }
8755
8756 // Then resolve the argument types.
8757 //
8758 // TODO: Is there a better way to figure out the number of method arguments
8759 // other than by looking at the shorty ?
8760 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8761
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008762 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008763 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8764 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008765 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008766 DCHECK(self->IsExceptionPending());
8767 return nullptr;
8768 }
8769
8770 DexFileParameterIterator it(dex_file, proto_id);
8771 int32_t i = 0;
8772 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8773 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008774 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008775 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008776 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008777 DCHECK(self->IsExceptionPending());
8778 return nullptr;
8779 }
8780
8781 method_params->Set(i++, param_class.Get());
8782 }
8783
8784 DCHECK(!it.HasNext());
8785
8786 Handle<mirror::MethodType> type = hs.NewHandle(
8787 mirror::MethodType::Create(self, return_type, method_params));
8788 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8789
8790 return type.Get();
8791}
8792
Vladimir Markoaf940202017-12-08 15:01:18 +00008793ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008794 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008795 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008796 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008797 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8798 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008799 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008800}
8801
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008802mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8803 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008804 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008805 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008806 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008807 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8808 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008809 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008810 bool is_static;
8811 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008812 switch (handle_type) {
8813 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008814 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008815 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008816 is_static = true;
8817 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008818 break;
8819 }
8820 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008821 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008822 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008823 is_static = true;
8824 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008825 break;
8826 }
8827 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008828 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008829 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008830 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008831 num_params = 2;
8832 break;
8833 }
8834 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008835 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008836 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008837 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008838 num_params = 1;
8839 break;
8840 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008841 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008842 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008843 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008844 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008845 case DexFile::MethodHandleType::kInvokeInterface:
8846 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008847 }
8848
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008849 ArtField* target_field =
8850 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8851 if (LIKELY(target_field != nullptr)) {
8852 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8853 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8854 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8855 ThrowIllegalAccessErrorField(referring_class, target_field);
8856 return nullptr;
8857 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008858 if (UNLIKELY(is_put && target_field->IsFinal())) {
8859 ThrowIllegalAccessErrorField(referring_class, target_field);
8860 return nullptr;
8861 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008862 } else {
8863 DCHECK(Thread::Current()->IsExceptionPending());
8864 return nullptr;
8865 }
8866
8867 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008868 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008869 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8870 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008871 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008872 DCHECK(self->IsExceptionPending());
8873 return nullptr;
8874 }
8875
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008876 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008877 Handle<mirror::Class> return_type;
8878 switch (handle_type) {
8879 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008880 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008881 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008882 break;
8883 }
8884 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008885 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008886 break;
8887 }
8888 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008889 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008890 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008891 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008892 break;
8893 }
8894 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008895 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008896 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008897 break;
8898 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008899 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008900 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008901 case DexFile::MethodHandleType::kInvokeConstructor:
8902 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008903 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008904 UNREACHABLE();
8905 }
8906
8907 for (int32_t i = 0; i < num_params; ++i) {
8908 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8909 DCHECK(self->IsExceptionPending());
8910 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008911 }
8912 }
8913
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008914 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008915 DCHECK(self->IsExceptionPending());
8916 return nullptr;
8917 }
8918
8919 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008920 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8921 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008922 DCHECK(self->IsExceptionPending());
8923 return nullptr;
8924 }
Orion Hodson631827d2017-04-10 14:53:47 +01008925
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008926 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8927 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8928}
8929
8930mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8931 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008932 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008933 ArtMethod* referrer) {
8934 DexFile::MethodHandleType handle_type =
8935 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8936 mirror::MethodHandle::Kind kind;
8937 uint32_t receiver_count = 0;
8938 ArtMethod* target_method = nullptr;
8939 switch (handle_type) {
8940 case DexFile::MethodHandleType::kStaticPut:
8941 case DexFile::MethodHandleType::kStaticGet:
8942 case DexFile::MethodHandleType::kInstancePut:
8943 case DexFile::MethodHandleType::kInstanceGet:
8944 UNREACHABLE();
8945 case DexFile::MethodHandleType::kInvokeStatic: {
8946 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8947 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008948 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8949 method_handle.field_or_method_idx_,
8950 referrer,
8951 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008952 break;
8953 }
8954 case DexFile::MethodHandleType::kInvokeInstance: {
8955 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8956 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008957 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8958 method_handle.field_or_method_idx_,
8959 referrer,
8960 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008961 break;
8962 }
8963 case DexFile::MethodHandleType::kInvokeConstructor: {
8964 // Constructors are currently implemented as a transform. They
8965 // are special cased later in this method.
8966 kind = mirror::MethodHandle::Kind::kInvokeTransform;
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::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008972 break;
8973 }
8974 case DexFile::MethodHandleType::kInvokeDirect: {
8975 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8976 receiver_count = 1;
8977 StackHandleScope<2> hs(self);
8978 // A constant method handle with type kInvokeDirect can refer to
8979 // a method that is private or to a method in a super class. To
8980 // disambiguate the two options, we resolve the method ignoring
8981 // the invocation type to determine if the method is private. We
8982 // then resolve again specifying the intended invocation type to
8983 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008984 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008985 hs.NewHandle(referrer->GetDexCache()),
8986 hs.NewHandle(referrer->GetClassLoader()));
8987 if (UNLIKELY(target_method == nullptr)) {
8988 break;
8989 }
8990
8991 if (target_method->IsPrivate()) {
8992 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008993 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8994 method_handle.field_or_method_idx_,
8995 referrer,
8996 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008997 } else {
8998 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008999 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9000 method_handle.field_or_method_idx_,
9001 referrer,
9002 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009003 if (UNLIKELY(target_method == nullptr)) {
9004 break;
9005 }
9006 // Find the method specified in the parent in referring class
9007 // so invoke-super invokes the method in the parent of the
9008 // referrer.
9009 target_method =
9010 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9011 kRuntimePointerSize);
9012 }
9013 break;
9014 }
9015 case DexFile::MethodHandleType::kInvokeInterface: {
9016 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9017 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009018 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9019 method_handle.field_or_method_idx_,
9020 referrer,
9021 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009022 break;
9023 }
Orion Hodson631827d2017-04-10 14:53:47 +01009024 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009025
9026 if (UNLIKELY(target_method == nullptr)) {
9027 DCHECK(Thread::Current()->IsExceptionPending());
9028 return nullptr;
9029 }
9030
9031 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9032 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9033 uint32_t access_flags = target_method->GetAccessFlags();
9034 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9035 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9036 return nullptr;
9037 }
9038
9039 // Calculate the number of parameters from the method shorty. We add the
9040 // receiver count (0 or 1) and deduct one for the return value.
9041 uint32_t shorty_length;
9042 target_method->GetShorty(&shorty_length);
9043 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9044
Orion Hodsonecd58562018-09-24 11:27:33 +01009045 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009046 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009047 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9048 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9049 if (method_params.Get() == nullptr) {
9050 DCHECK(self->IsExceptionPending());
9051 return nullptr;
9052 }
9053
Orion Hodsonecd58562018-09-24 11:27:33 +01009054 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009055 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009056 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009057 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009058 // Insert receiver. Use the class identified in the method handle rather than the declaring
9059 // class of the resolved method which may be super class or default interface method
9060 // (b/115964401).
9061 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9062 // receiver_class should have been resolved when resolving the target method.
9063 DCHECK(receiver_class != nullptr);
9064 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009065 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009066
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009067 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009068 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009069 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009070 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009071 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009072 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009073 if (nullptr == klass) {
9074 DCHECK(self->IsExceptionPending());
9075 return nullptr;
9076 }
9077 method_params->Set(index++, klass);
9078 it.Next();
9079 }
9080
Orion Hodsonecd58562018-09-24 11:27:33 +01009081 Handle<mirror::Class> return_type =
9082 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009083 if (UNLIKELY(return_type.IsNull())) {
9084 DCHECK(self->IsExceptionPending());
9085 return nullptr;
9086 }
9087
9088 Handle<mirror::MethodType>
9089 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9090 if (UNLIKELY(method_type.IsNull())) {
9091 DCHECK(self->IsExceptionPending());
9092 return nullptr;
9093 }
9094
9095 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9096 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9097 Handle<mirror::MethodHandlesLookup> lookup =
9098 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9099 return lookup->FindConstructor(self, constructor_class, method_type);
9100 }
9101
9102 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9103 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9104}
9105
Vladimir Markoaf940202017-12-08 15:01:18 +00009106ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9107 uint32_t method_handle_idx,
9108 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009109 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009110 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009111 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009112 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9113 case DexFile::MethodHandleType::kStaticPut:
9114 case DexFile::MethodHandleType::kStaticGet:
9115 case DexFile::MethodHandleType::kInstancePut:
9116 case DexFile::MethodHandleType::kInstanceGet:
9117 return ResolveMethodHandleForField(self, method_handle, referrer);
9118 case DexFile::MethodHandleType::kInvokeStatic:
9119 case DexFile::MethodHandleType::kInvokeInstance:
9120 case DexFile::MethodHandleType::kInvokeConstructor:
9121 case DexFile::MethodHandleType::kInvokeDirect:
9122 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009123 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009124 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009125}
9126
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009127bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9128 return (entry_point == GetQuickResolutionStub()) ||
9129 (quick_resolution_trampoline_ == entry_point);
9130}
9131
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009132bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9133 return (entry_point == GetQuickToInterpreterBridge()) ||
9134 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9135}
9136
9137bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9138 return (entry_point == GetQuickGenericJniStub()) ||
9139 (quick_generic_jni_trampoline_ == entry_point);
9140}
9141
David Sehra49e0532017-08-25 08:05:29 -07009142bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9143 return entry_point == GetJniDlsymLookupStub();
9144}
9145
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009146const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9147 return GetQuickGenericJniStub();
9148}
9149
Mathieu Chartiere401d142015-04-22 13:56:20 -07009150void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009151 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009152 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9153 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009154 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009155 }
9156}
9157
Alex Lightdb01a092017-04-03 15:39:55 -07009158void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9159 DCHECK(method->IsObsolete());
9160 // We cannot mess with the entrypoints of native methods because they are used to determine how
9161 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9162 if (!method->IsNative()) {
9163 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9164 }
9165}
9166
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009167void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009168 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009169 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009170 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9171 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009172 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9173 os << "Dumping registered class loaders\n";
9174 size_t class_loader_index = 0;
9175 for (const ClassLoaderData& class_loader : class_loaders_) {
9176 ObjPtr<mirror::ClassLoader> loader =
9177 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9178 if (loader != nullptr) {
9179 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9180 bool saw_one_dex_file = false;
9181 for (const DexCacheData& dex_cache : dex_caches_) {
9182 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9183 if (saw_one_dex_file) {
9184 os << ":";
9185 }
9186 saw_one_dex_file = true;
9187 os << dex_cache.dex_file->GetLocation();
9188 }
9189 }
9190 os << "]";
9191 bool found_parent = false;
9192 if (loader->GetParent() != nullptr) {
9193 size_t parent_index = 0;
9194 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9195 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9196 soa.Self()->DecodeJObject(class_loader2.weak_root));
9197 if (loader2 == loader->GetParent()) {
9198 os << ", parent #" << parent_index;
9199 found_parent = true;
9200 break;
9201 }
9202 parent_index++;
9203 }
9204 if (!found_parent) {
9205 os << ", unregistered parent of type "
9206 << loader->GetParent()->GetClass()->PrettyDescriptor();
9207 }
9208 } else {
9209 os << ", no parent";
9210 }
9211 os << "\n";
9212 }
9213 }
9214 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009215}
9216
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009217class CountClassesVisitor : public ClassLoaderVisitor {
9218 public:
9219 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9220
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009221 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009222 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009223 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009224 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009225 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9226 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009227 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009228 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009229
9230 size_t num_zygote_classes;
9231 size_t num_non_zygote_classes;
9232};
9233
9234size_t ClassLinker::NumZygoteClasses() const {
9235 CountClassesVisitor visitor;
9236 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009237 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009238}
9239
9240size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009241 CountClassesVisitor visitor;
9242 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009243 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009244}
9245
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009246size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009247 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009248 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009249 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009250}
9251
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009252pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009253 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009254}
9255
9256pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009257 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009258}
9259
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009260void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009261 DCHECK(!init_done_);
9262
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009263 DCHECK(klass != nullptr);
9264 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009265
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009266 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009267 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009268 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9269 int32_t index = static_cast<int32_t>(class_root);
9270 DCHECK(class_roots->Get(index) == nullptr);
9271 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009272}
9273
Roland Levillain0e840272018-08-23 19:55:30 +01009274void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9275 ObjPtr<mirror::Class> java_lang_Class,
9276 ClassRoot primitive_array_class_root,
9277 ClassRoot primitive_class_root,
9278 const char* descriptor) {
9279 StackHandleScope<1> hs(self);
9280 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9281 AllocPrimitiveArrayClass(self, java_lang_Class)));
9282 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9283 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9284 CheckSystemClass(self, primitive_array_class, descriptor);
9285}
9286
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009287ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9288 Thread* self,
9289 const std::vector<const DexFile*>& dex_files,
9290 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009291 Handle<mirror::ClassLoader> parent_loader,
9292 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009293
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009294 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009295
Mathieu Chartierc7853442015-03-27 14:35:38 -07009296 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009297 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009298
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009299 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009300 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009301 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009302 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009303 mirror::ObjectArray<mirror::Object>::Alloc(self,
9304 dex_elements_class.Get(),
9305 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009306 Handle<mirror::Class> h_dex_element_class =
9307 hs.NewHandle(dex_elements_class->GetComponentType());
9308
Mathieu Chartierc7853442015-03-27 14:35:38 -07009309 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009310 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009311 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009312
Andreas Gampe08883de2016-11-08 13:20:52 -08009313 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009314 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009315
Andreas Gampe08883de2016-11-08 13:20:52 -08009316 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009317 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009318
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009319 // Fill the elements array.
9320 int32_t index = 0;
9321 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009322 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009323
Calin Juravle7865ac72017-06-28 11:03:12 -07009324 // CreateWellKnownClassLoader is only used by gtests and compiler.
9325 // 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 -07009326 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9327 self,
9328 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009329 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009330 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009331
Mathieu Chartier3738e982017-05-12 16:07:28 -07009332 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9333 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009334 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009335 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009336 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009337 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009338
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009339 Handle<mirror::String> h_file_name = hs2.NewHandle(
9340 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009341 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009342 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9343
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009344 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009345 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009346 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009347
9348 h_dex_elements->Set(index, h_element.Get());
9349 index++;
9350 }
9351 DCHECK_EQ(index, h_dex_elements->GetLength());
9352
9353 // Create DexPathList.
9354 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009355 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009356 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009357 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009358 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009359 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9360 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9361 // elements.
9362 {
9363 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9364 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9365 DCHECK(native_lib_dirs != nullptr);
9366 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9367 DCHECK(list_class != nullptr);
9368 {
9369 StackHandleScope<1> h_list_scope(self);
9370 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9371 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9372 DCHECK(list_init);
9373 list_class = h_list_class.Get();
9374 }
9375 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9376 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9377 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9378 // normally never null), as long as one does not try to add elements, this will still
9379 // work.
9380 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9381 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009382
Calin Juravle7865ac72017-06-28 11:03:12 -07009383 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009384 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9385 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009386 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009387 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009388 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009389 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009390 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009391 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009392
9393 // Make a pretend boot-classpath.
9394 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009395 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009396 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009397 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009398 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009399 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009400 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009401 if (parent_loader.Get() == nullptr) {
9402 ScopedObjectAccessUnchecked soa(self);
9403 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9404 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9405 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9406 } else {
9407 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9408 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009409
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009410 ArtField* shared_libraries_field =
9411 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9412 DCHECK(shared_libraries_field != nullptr);
9413 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9414
9415 return h_class_loader.Get();
9416}
9417
9418jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9419 const std::vector<const DexFile*>& dex_files,
9420 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009421 jobject parent_loader,
9422 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009423 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9424 WellKnownClasses::dalvik_system_PathClassLoader) ||
9425 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009426 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9427 self->GetJniEnv()->IsSameObject(loader_class,
9428 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009429
9430 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9431 // We could move the jobject to the callers, but all call-sites do this...
9432 ScopedObjectAccessUnchecked soa(self);
9433
9434 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009435 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009436
9437 Handle<mirror::Class> h_loader_class =
9438 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009439 Handle<mirror::ClassLoader> h_parent =
9440 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9441 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9442 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009443
9444 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9445 self,
9446 dex_files,
9447 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009448 h_parent,
9449 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009450
9451 // Make it a global ref and return.
9452 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009453 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009454 return soa.Env()->NewGlobalRef(local_ref.get());
9455}
9456
Calin Juravle7865ac72017-06-28 11:03:12 -07009457jobject ClassLinker::CreatePathClassLoader(Thread* self,
9458 const std::vector<const DexFile*>& dex_files) {
9459 return CreateWellKnownClassLoader(self,
9460 dex_files,
9461 WellKnownClasses::dalvik_system_PathClassLoader,
9462 nullptr);
9463}
9464
Andreas Gampe8ac75952015-06-02 21:01:45 -07009465void ClassLinker::DropFindArrayClassCache() {
9466 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9467 find_array_class_cache_next_victim_ = 0;
9468}
9469
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009470void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009471 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009472 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009473 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009474 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9475 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009476 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009477 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009478 }
9479 }
9480}
9481
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009482void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9483 for (const ClassLoaderData& data : class_loaders_) {
9484 LinearAlloc* alloc = data.allocator;
9485 if (alloc != nullptr && !visitor->Visit(alloc)) {
9486 break;
9487 }
9488 }
9489}
9490
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009491void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9492 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009493 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009494 Thread* const self = Thread::Current();
9495 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009496 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009497 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009498 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009499 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9500 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009501 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009502 }
9503}
9504
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009505void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009506 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009507 std::vector<ClassLoaderData> to_delete;
9508 // Do the delete outside the lock to avoid lock violation in jit code cache.
9509 {
9510 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9511 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9512 const ClassLoaderData& data = *it;
9513 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009514 ObjPtr<mirror::ClassLoader> class_loader =
9515 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009516 if (class_loader != nullptr) {
9517 ++it;
9518 } else {
9519 VLOG(class_linker) << "Freeing class loader";
9520 to_delete.push_back(data);
9521 it = class_loaders_.erase(it);
9522 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009523 }
9524 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009525 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009526 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009527 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009528 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009529}
9530
Vladimir Marko21300532017-01-24 18:06:55 +00009531class GetResolvedClassesVisitor : public ClassVisitor {
9532 public:
9533 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9534 : result_(result),
9535 ignore_boot_classes_(ignore_boot_classes),
9536 last_resolved_classes_(result->end()),
9537 last_dex_file_(nullptr),
9538 vlog_is_on_(VLOG_IS_ON(class_linker)),
9539 extra_stats_(),
9540 last_extra_stats_(extra_stats_.end()) { }
9541
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009542 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009543 if (!klass->IsProxyClass() &&
9544 !klass->IsArrayClass() &&
9545 klass->IsResolved() &&
9546 !klass->IsErroneousResolved() &&
9547 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9548 const DexFile& dex_file = klass->GetDexFile();
9549 if (&dex_file != last_dex_file_) {
9550 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009551 DexCacheResolvedClasses resolved_classes(
9552 dex_file.GetLocation(),
9553 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9554 dex_file.GetLocationChecksum(),
9555 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009556 last_resolved_classes_ = result_->find(resolved_classes);
9557 if (last_resolved_classes_ == result_->end()) {
9558 last_resolved_classes_ = result_->insert(resolved_classes).first;
9559 }
9560 }
9561 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9562 if (UNLIKELY(vlog_is_on_) && added) {
9563 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9564 if (last_extra_stats_ == extra_stats_.end() ||
9565 last_extra_stats_->first != resolved_classes) {
9566 last_extra_stats_ = extra_stats_.find(resolved_classes);
9567 if (last_extra_stats_ == extra_stats_.end()) {
9568 last_extra_stats_ =
9569 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9570 }
9571 }
9572 }
9573 }
9574 return true;
9575 }
9576
9577 void PrintStatistics() const {
9578 if (vlog_is_on_) {
9579 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9580 auto it = extra_stats_.find(std::addressof(resolved_classes));
9581 DCHECK(it != extra_stats_.end());
9582 const ExtraStats& extra_stats = it->second;
9583 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9584 << " has " << resolved_classes.GetClasses().size() << " / "
9585 << extra_stats.number_of_class_defs_ << " resolved classes";
9586 }
9587 }
9588 }
9589
9590 private:
9591 struct ExtraStats {
9592 explicit ExtraStats(uint32_t number_of_class_defs)
9593 : number_of_class_defs_(number_of_class_defs) {}
9594 uint32_t number_of_class_defs_;
9595 };
9596
9597 std::set<DexCacheResolvedClasses>* result_;
9598 bool ignore_boot_classes_;
9599 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9600 const DexFile* last_dex_file_;
9601
9602 // Statistics.
9603 bool vlog_is_on_;
9604 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9605 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9606};
9607
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009608std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009609 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009610 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009611 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009612 std::set<DexCacheResolvedClasses> ret;
9613 VLOG(class_linker) << "Collecting resolved classes";
9614 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009615 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9616 VisitClasses(&visitor);
9617 if (VLOG_IS_ON(class_linker)) {
9618 visitor.PrintStatistics();
9619 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009620 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009621 return ret;
9622}
9623
Mathieu Chartier65975772016-08-05 10:46:36 -07009624class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9625 public:
9626 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9627 : method_(method),
9628 pointer_size_(pointer_size) {}
9629
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009630 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009631 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9632 holder_ = klass;
9633 }
9634 // Return false to stop searching if holder_ is not null.
9635 return holder_ == nullptr;
9636 }
9637
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009638 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009639 const ArtMethod* const method_;
9640 const PointerSize pointer_size_;
9641};
9642
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009643ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009644 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9645 CHECK(method->IsCopied());
9646 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9647 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009648 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009649}
9650
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009651ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9652 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009653 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009654 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009655 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009656}
9657
Roland Levillain0e840272018-08-23 19:55:30 +01009658// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009659template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009660 uint32_t method_idx,
9661 Handle<mirror::DexCache> dex_cache,
9662 Handle<mirror::ClassLoader> class_loader,
9663 ArtMethod* referrer,
9664 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009665template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009666 uint32_t method_idx,
9667 Handle<mirror::DexCache> dex_cache,
9668 Handle<mirror::ClassLoader> class_loader,
9669 ArtMethod* referrer,
9670 InvokeType type);
9671
Roland Levillain0e840272018-08-23 19:55:30 +01009672// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009673template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009674 Thread* self,
9675 ObjPtr<mirror::Class> java_lang_Class,
9676 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009677template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009678 Thread* self,
9679 ObjPtr<mirror::Class> java_lang_Class,
9680 uint32_t class_size);
9681
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009682} // namespace art