blob: c7cf43fca0e3f3ad3606a70bc2c0325694a80576 [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
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200930// Set image methods' entry point to interpreter.
931class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
932 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700933 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200934 : image_pointer_size_(image_pointer_size) {}
935
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100936 void Visit(ArtMethod* method) override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200937 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
938 CHECK(method->GetDeclaringClass() != nullptr);
939 }
940 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
941 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
942 image_pointer_size_);
943 }
944 }
945
946 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700947 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200948
949 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
950};
951
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952struct TrampolineCheckData {
953 const void* quick_resolution_trampoline;
954 const void* quick_imt_conflict_trampoline;
955 const void* quick_generic_jni_trampoline;
956 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700957 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800958 ArtMethod* m;
959 bool error;
960};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800961
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800962bool ClassLinker::InitFromBootImage(std::string* error_msg) {
963 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700964 CHECK(!init_done_);
965
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700966 Runtime* const runtime = Runtime::Current();
967 Thread* const self = Thread::Current();
968 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800969 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
970 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700971 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
972 if (!ValidPointerSize(pointer_size_unchecked)) {
973 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800974 return false;
975 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000976 const ImageHeader& image_header = spaces[0]->GetImageHeader();
977 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800978 if (!runtime->IsAotCompiler()) {
979 // Only the Aot compiler supports having an image with a different pointer size than the
980 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
981 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700982 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800983 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700984 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800985 sizeof(void*));
986 return false;
987 }
988 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000989 DCHECK(!runtime->HasResolutionMethod());
990 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
991 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
992 runtime->SetImtUnimplementedMethod(
993 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
994 runtime->SetCalleeSaveMethod(
995 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
996 CalleeSaveType::kSaveAllCalleeSaves);
997 runtime->SetCalleeSaveMethod(
998 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
999 CalleeSaveType::kSaveRefsOnly);
1000 runtime->SetCalleeSaveMethod(
1001 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1002 CalleeSaveType::kSaveRefsAndArgs);
1003 runtime->SetCalleeSaveMethod(
1004 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1005 CalleeSaveType::kSaveEverything);
1006 runtime->SetCalleeSaveMethod(
1007 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1008 CalleeSaveType::kSaveEverythingForClinit);
1009 runtime->SetCalleeSaveMethod(
1010 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1011 CalleeSaveType::kSaveEverythingForSuspendCheck);
1012
Jeff Haodcdc85b2015-12-04 14:06:18 -08001013 std::vector<const OatFile*> oat_files =
1014 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1015 DCHECK(!oat_files.empty());
1016 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001017 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1018 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1019 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1020 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1021 if (kIsDebugBuild) {
1022 // Check that the other images use the same trampoline.
1023 for (size_t i = 1; i < oat_files.size(); ++i) {
1024 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1025 const void* ith_quick_resolution_trampoline =
1026 ith_oat_header.GetQuickResolutionTrampoline();
1027 const void* ith_quick_imt_conflict_trampoline =
1028 ith_oat_header.GetQuickImtConflictTrampoline();
1029 const void* ith_quick_generic_jni_trampoline =
1030 ith_oat_header.GetQuickGenericJniTrampoline();
1031 const void* ith_quick_to_interpreter_bridge_trampoline =
1032 ith_oat_header.GetQuickToInterpreterBridge();
1033 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1034 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1035 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1036 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1037 // Make sure that all methods in this image do not contain those trampolines as
1038 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1039 TrampolineCheckData data;
1040 data.error = false;
1041 data.pointer_size = GetImagePointerSize();
1042 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1043 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1044 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1045 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1046 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001047 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1048 if (obj->IsClass()) {
1049 ObjPtr<mirror::Class> klass = obj->AsClass();
1050 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1051 const void* entrypoint =
1052 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1053 if (entrypoint == data.quick_resolution_trampoline ||
1054 entrypoint == data.quick_imt_conflict_trampoline ||
1055 entrypoint == data.quick_generic_jni_trampoline ||
1056 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1057 data.m = &m;
1058 data.error = true;
1059 return;
1060 }
1061 }
1062 }
1063 };
1064 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001065 if (data.error) {
1066 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001067 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001068 *error_msg = "Found an ArtMethod with a bad entrypoint";
1069 return false;
1070 }
1071 }
1072 }
1073 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001074
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001076 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1077 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001078 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001079
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001080 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001081 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001082 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1083 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001084 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1085 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001086
Vladimir Marko4433c432018-12-04 14:57:47 +00001087 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1088 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001089 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001090 // Boot class loader, use a null handle.
1091 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001092 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001093 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001094 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001095 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001096 /*out*/&dex_files,
1097 error_msg)) {
1098 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001099 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001100 // Append opened dex files at the end.
1101 boot_dex_files_.insert(boot_dex_files_.end(),
1102 std::make_move_iterator(dex_files.begin()),
1103 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001104 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001105 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1106 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1107 }
Ian Rogers98379392014-02-24 16:53:16 -08001108 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001109
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110 VLOG(startup) << __FUNCTION__ << " exiting";
1111 return true;
1112}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001113
Vladimir Marko4433c432018-12-04 14:57:47 +00001114void ClassLinker::AddExtraBootDexFiles(
1115 Thread* self,
1116 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1117 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1118 AppendToBootClassPath(self, *dex_file);
1119 boot_dex_files_.push_back(std::move(dex_file));
1120 }
1121}
1122
Jeff Hao5872d7c2016-04-27 11:07:41 -07001123bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001124 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001126 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1127 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128}
1129
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001130static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1131 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001132 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001133 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001134 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001135 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001136 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001137 DCHECK(dex_file_field != nullptr);
1138 DCHECK(dex_file_name_field != nullptr);
1139 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001140 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001141 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001142 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001143 // Null dex file means it was probably a jar with no dex files, return a null string.
1144 *out_name = nullptr;
1145 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001146 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001147 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001148 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001149 *out_name = name_object->AsString();
1150 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001151 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001152 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001153}
1154
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001155static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1156 ObjPtr<mirror::ClassLoader> class_loader,
1157 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1158 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001159 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001160 StackHandleScope<1> hs(soa.Self());
1161 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001162 // Get element names. Sets error to true on failure.
1163 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1164 REQUIRES_SHARED(Locks::mutator_lock_) {
1165 if (element == nullptr) {
1166 *error_msg = "Null dex element";
1167 *error = true; // Null element is a critical error.
1168 return false; // Had an error, stop the visit.
1169 }
1170 ObjPtr<mirror::String> name;
1171 if (!GetDexPathListElementName(element, &name)) {
1172 *error_msg = "Invalid dex path list element";
1173 *error = true; // Invalid element, make it a critical error.
1174 return false; // Stop the visit.
1175 }
1176 if (name != nullptr) {
1177 dex_files->push_front(name);
1178 }
1179 return true; // Continue with the next Element.
1180 };
1181 bool error = VisitClassLoaderDexElements(soa,
1182 handle,
1183 add_element_names,
1184 /*defaultReturn=*/ false);
1185 return !error;
1186}
1187
1188static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1189 ObjPtr<mirror::ClassLoader> image_class_loader,
1190 ObjPtr<mirror::ClassLoader> class_loader,
1191 std::string* error_msg)
1192 REQUIRES_SHARED(Locks::mutator_lock_) {
1193 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1194 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1195 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001196 return false;
1197 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001198 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1199 *error_msg = "Hierarchies don't match";
1200 return false;
1201 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1202 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1203 image_class_loader->PrettyTypeOf().c_str(),
1204 class_loader->PrettyTypeOf().c_str());
1205 return false;
1206 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1207 class_loader->GetClass()) {
1208 *error_msg = StringPrintf("Unknown class loader type %s",
1209 class_loader->PrettyTypeOf().c_str());
1210 // Unsupported class loader.
1211 return false;
1212 }
1213 return true;
1214}
1215
1216static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1217 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1218 std::string* error_msg)
1219 REQUIRES_SHARED(Locks::mutator_lock_) {
1220 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1221 std::equal(image_dex_files.begin(),
1222 image_dex_files.end(),
1223 loader_dex_files.begin(),
1224 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1225 REQUIRES_SHARED(Locks::mutator_lock_) {
1226 return lhs->Equals(rhs);
1227 });
1228 if (!equal) {
1229 VLOG(image) << "Image dex files " << image_dex_files.size();
1230 for (ObjPtr<mirror::String> name : image_dex_files) {
1231 VLOG(image) << name->ToModifiedUtf8();
1232 }
1233 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1234 for (ObjPtr<mirror::String> name : loader_dex_files) {
1235 VLOG(image) << name->ToModifiedUtf8();
1236 }
1237 *error_msg = "Mismatch in dex files";
1238 }
1239 return equal;
1240}
1241
1242static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1243 ObjPtr<mirror::ClassLoader> image_class_loader,
1244 ObjPtr<mirror::ClassLoader> class_loader,
1245 bool check_dex_file_names,
1246 std::string* error_msg)
1247 REQUIRES_SHARED(Locks::mutator_lock_) {
1248 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1249 return false;
1250 }
1251
1252 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1253 // No need to check further.
1254 return true;
1255 }
1256
1257 if (check_dex_file_names) {
1258 std::list<ObjPtr<mirror::String>> image_dex_files;
1259 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001260 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001261 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001262
1263 std::list<ObjPtr<mirror::String>> loader_dex_files;
1264 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1265 return false;
1266 }
1267
1268 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1269 return false;
1270 }
1271 }
1272
1273 ArtField* field =
1274 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1275 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1276 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1277 if (shared_libraries_image_loader == nullptr) {
1278 if (shared_libraries_loader != nullptr) {
1279 *error_msg = "Mismatch in shared libraries";
1280 return false;
1281 }
1282 } else if (shared_libraries_loader == nullptr) {
1283 *error_msg = "Mismatch in shared libraries";
1284 return false;
1285 } else {
1286 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1287 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1288 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1289 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1290 if (array1->GetLength() != array2->GetLength()) {
1291 *error_msg = "Mismatch in number of shared libraries";
1292 return false;
1293 }
1294
1295 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1296 // Do a full comparison of the class loaders, including comparing their dex files.
1297 if (!CompareClassLoaders(soa,
1298 array1->Get(i),
1299 array2->Get(i),
1300 /*check_dex_file_names=*/ true,
1301 error_msg)) {
1302 return false;
1303 }
1304 }
1305 }
1306
1307 // Do a full comparison of the class loaders, including comparing their dex files.
1308 if (!CompareClassLoaders(soa,
1309 image_class_loader->GetParent(),
1310 class_loader->GetParent(),
1311 /*check_dex_file_names=*/ true,
1312 error_msg)) {
1313 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001314 }
1315 return true;
1316}
1317
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001318class CHAOnDeleteUpdateClassVisitor {
1319 public:
1320 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1321 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1322 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1323 self_(Thread::Current()) {}
1324
1325 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1326 // This class is going to be unloaded. Tell CHA about it.
1327 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1328 return true;
1329 }
1330 private:
1331 const LinearAlloc* allocator_;
1332 const ClassHierarchyAnalysis* cha_;
1333 const PointerSize pointer_size_;
1334 const Thread* self_;
1335};
1336
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001337class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1338 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001339 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001340 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1341
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001342 void Visit(ArtMethod* method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001343 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001344 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001345 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001346 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001347 }
1348 }
1349
1350 private:
1351 gc::accounting::HeapBitmap* const live_bitmap_;
1352};
1353
Chris Wailes0c61be42018-09-26 17:27:34 -07001354/*
1355 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001356 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001357 */
1358class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001359 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001360 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001361 space_(space),
1362 intern_table_(*Runtime::Current()->GetInternTable()) {}
1363
Chris Wailes0c61be42018-09-26 17:27:34 -07001364 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001365 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001366 if (referred_obj != nullptr &&
1367 space_.HasAddress(referred_obj.Ptr()) &&
1368 referred_obj->IsString()) {
1369 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001370
1371 if (kIsDebugBuild) {
1372 // Saved to temporary variables to aid in debugging.
1373 ObjPtr<mirror::String> strong_lookup_result =
1374 intern_table_.LookupStrong(Thread::Current(), referred_str);
1375 ObjPtr<mirror::String> weak_lookup_result =
1376 intern_table_.LookupWeak(Thread::Current(), referred_str);
1377
1378 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1379 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001380 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001381 }
1382
Chris Wailes0c61be42018-09-26 17:27:34 -07001383 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001384 mirror::CompressedReference<mirror::Object>* root) const
1385 REQUIRES_SHARED(Locks::mutator_lock_) {
1386 if (!root->IsNull()) {
1387 VisitRoot(root);
1388 }
1389 }
1390
Chris Wailes0c61be42018-09-26 17:27:34 -07001391 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001392 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001393 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001394 }
1395
1396 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001397 void operator()(ObjPtr<mirror::Object> obj,
1398 MemberOffset offset,
1399 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001400 REQUIRES_SHARED(Locks::mutator_lock_) {
1401 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1402 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1403 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1404 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001405 ObjPtr<mirror::Object> referred_obj =
1406 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1407
1408 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001409 }
1410 }
1411
1412 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1413 ObjPtr<mirror::Reference> ref) const
1414 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001415 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001416 }
1417
Chris Wailes0c61be42018-09-26 17:27:34 -07001418 const gc::space::ImageSpace& space_;
1419 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001420};
1421
Chris Wailes0c61be42018-09-26 17:27:34 -07001422/*
1423 * This function verifies that string references in the AppImage have been
1424 * properly interned. To be considered properly interned a reference must
1425 * point to the same version of the string that the intern table does.
1426 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001427void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001428 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1429 const ImageHeader& image_header = space.GetImageHeader();
1430 const uint8_t* target_base = space.GetMemMap()->Begin();
1431 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001432
1433 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1434 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001435
1436 VerifyStringInterningVisitor visitor(space);
1437 bitmap->VisitMarkedRange(objects_begin,
1438 objects_end,
1439 [&space, &visitor](mirror::Object* obj)
1440 REQUIRES_SHARED(Locks::mutator_lock_) {
1441 if (space.HasAddress(obj)) {
1442 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001443 obj->VisitReferences</* kVisitNativeRoots= */ true,
1444 kVerifyNone,
1445 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001446 } else {
1447 // Don't visit native roots for non-dex-cache as they can't contain
1448 // native references to strings. This is verified during compilation
1449 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001450 obj->VisitReferences</* kVisitNativeRoots= */ false,
1451 kVerifyNone,
1452 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001453 }
1454 }
1455 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001456}
1457
Andreas Gampe2af99022017-04-25 08:32:59 -07001458// new_class_set is the set of classes that were read from the class table section in the image.
1459// If there was no class table section, it is null.
1460// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001461class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001462 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001463 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001464 ClassLinker* class_linker,
1465 gc::space::ImageSpace* space,
1466 Handle<mirror::ClassLoader> class_loader,
1467 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001468 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001469 REQUIRES(!Locks::dex_lock_)
1470 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001471
Chris Wailesfbeef462018-10-19 14:16:35 -07001472 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001473 REQUIRES_SHARED(Locks::mutator_lock_);
1474
1475 static void UpdateInternStrings(
1476 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001477 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001478 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1479 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001480};
1481
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001482void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001483 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001484 gc::space::ImageSpace* space,
1485 Handle<mirror::ClassLoader> class_loader,
1486 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001487 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001488 REQUIRES(!Locks::dex_lock_)
1489 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001490 ScopedTrace app_image_timing("AppImage:Updating");
1491
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001492 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001493 Runtime* const runtime = Runtime::Current();
1494 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001495 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001496 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001497 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001498 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001499 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001500 const size_t num_dex_caches = dex_caches->GetLength();
1501 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001502 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001503 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001504 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001505 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001506 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1507 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001508 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001509
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001510 if (!load_app_image_startup_cache) {
1511 dex_cache->ClearPreResolvedStrings();
1512 }
1513
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001514 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001515 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001516 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001517 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001518 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001519 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001520 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001521
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001522 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001523 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001524 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001525 DCHECK(it != new_class_set->end());
1526 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001527 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001528
Vladimir Marko1a1de672016-10-13 12:53:15 +01001529 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001530 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001531 DCHECK(it2 != new_class_set->end());
1532 DCHECK_EQ(it2->Read(), super_class);
1533 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001534
Vladimir Marko1a1de672016-10-13 12:53:15 +01001535 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1536 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001537 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1538 if (!class_linker->IsQuickResolutionStub(code) &&
1539 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001540 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001541 !m.IsNative()) {
1542 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001543 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001544 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001545
Vladimir Marko1a1de672016-10-13 12:53:15 +01001546 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1547 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001548 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1549 if (!class_linker->IsQuickResolutionStub(code) &&
1550 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001551 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001552 !m.IsNative()) {
1553 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001554 }
1555 }
1556 }
1557 }
1558 }
1559 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001560 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001561
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001562 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001563 HandleAppImageStrings(space);
1564
1565 if (kIsDebugBuild) {
1566 VerifyStringInterning(*space);
1567 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001568 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001569
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001570 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001571 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001572 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1573 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001574 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001575 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001576}
1577
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001578void AppImageLoadingHelper::UpdateInternStrings(
1579 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001580 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001581 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1582 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001583 const ImageSection& sro_section =
1584 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1585 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001586 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001587
1588 VLOG(image)
1589 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1590 << num_string_offsets;
1591
Chris Wailesfbeef462018-10-19 14:16:35 -07001592 const auto* sro_base =
1593 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001594
1595 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001596 uint32_t base_offset = sro_base[offset_index].first;
1597
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001598 if (HasDexCacheStringNativeRefTag(base_offset)) {
1599 base_offset = ClearDexCacheNativeRefTags(base_offset);
1600 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001601
1602 ObjPtr<mirror::DexCache> dex_cache =
1603 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1604 uint32_t string_index = sro_base[offset_index].second;
1605
1606 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1607 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001608 DCHECK(referred_string != nullptr);
1609
Chris Wailesfbeef462018-10-19 14:16:35 -07001610 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001611 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001612 // This doesn't use SetResolvedString to maintain consistency with how
1613 // we load the string. The index from the source string must be
1614 // re-used due to the circular nature of the cache. Because we are not
1615 // using a helper function we need to mark the GC card manually.
1616 WriteBarrier::ForEveryFieldWrite(dex_cache);
1617 dex_cache->GetStrings()[string_index].store(
1618 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001619 } else if (!use_preresolved_strings) {
1620 dex_cache->GetStrings()[string_index].store(
1621 mirror::StringDexCachePair(intern_table->InternStrong(referred_string), source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001622 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001623 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001624 if (use_preresolved_strings) {
1625 base_offset = ClearDexCacheNativeRefTags(base_offset);
1626 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001627
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001628 ObjPtr<mirror::DexCache> dex_cache =
1629 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1630 uint32_t string_index = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001631
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001632 ObjPtr<mirror::String> referred_string =
1633 dex_cache->GetPreResolvedStrings()[string_index].Read();
1634 DCHECK(referred_string != nullptr);
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001635
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001636 auto it = intern_remap.find(referred_string.Ptr());
1637 if (it != intern_remap.end()) {
1638 // Because we are not using a helper function we need to mark the GC card manually.
1639 WriteBarrier::ForEveryFieldWrite(dex_cache);
1640 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1641 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001642 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001643 } else {
1644 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001645 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001646 DCHECK_ALIGNED(raw_member_offset, 2);
1647
1648 ObjPtr<mirror::Object> obj_ptr =
1649 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1650 MemberOffset member_offset(raw_member_offset);
1651 ObjPtr<mirror::String> referred_string =
1652 obj_ptr->GetFieldObject<mirror::String,
1653 kVerifyNone,
1654 kWithoutReadBarrier,
1655 /* kIsVolatile= */ false>(member_offset);
1656 DCHECK(referred_string != nullptr);
1657
1658 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001659 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001660 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1661 /* kCheckTransaction= */ false,
1662 kVerifyNone,
1663 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001664 } else if (!use_preresolved_strings) {
1665 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1666 /* kCheckTransaction= */ false,
1667 kVerifyNone,
1668 /* kIsVolatile= */ false>(
1669 member_offset,
1670 intern_table->InternStrong(referred_string));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001671 }
1672 }
1673 }
1674}
1675
Chris Wailesfbeef462018-10-19 14:16:35 -07001676void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001677 // Iterate over the string reference offsets stored in the image and intern
1678 // the strings they point to.
1679 ScopedTrace timing("AppImage:InternString");
1680
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001681 Runtime* const runtime = Runtime::Current();
1682 InternTable* const intern_table = runtime->GetInternTable();
1683
1684 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001685
1686 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1687 // for faster lookup.
1688 // TODO: Optimize with a bitmap or bloom filter
1689 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001690 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001691 REQUIRES_SHARED(Locks::mutator_lock_)
1692 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001693 const size_t non_boot_image_strings = intern_table->CountInterns(
1694 /*visit_boot_images=*/false,
1695 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001696 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001697 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1698 // Visit the smaller of the two sets to compute the intersection.
1699 if (interns.size() < non_boot_image_strings) {
1700 for (auto it = interns.begin(); it != interns.end(); ) {
1701 ObjPtr<mirror::String> string = it->Read();
1702 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1703 if (existing == nullptr) {
1704 existing = intern_table->LookupStrongLocked(string);
1705 }
1706 if (existing != nullptr) {
1707 intern_remap.Put(string.Ptr(), existing.Ptr());
1708 it = interns.erase(it);
1709 } else {
1710 ++it;
1711 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001712 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001713 } else {
1714 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1715 REQUIRES_SHARED(Locks::mutator_lock_)
1716 REQUIRES(Locks::intern_table_lock_) {
1717 auto it = interns.find(root);
1718 if (it != interns.end()) {
1719 ObjPtr<mirror::String> existing = root.Read();
1720 intern_remap.Put(it->Read(), existing.Ptr());
1721 it = interns.erase(it);
1722 }
1723 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1724 }
1725 // Sanity check to ensure correctness.
1726 if (kIsDebugBuild) {
1727 for (GcRoot<mirror::String>& root : interns) {
1728 ObjPtr<mirror::String> string = root.Read();
1729 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1730 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001731 }
1732 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001733 };
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001734
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001735 bool update_intern_strings;
1736 if (load_startup_cache) {
Mathieu Chartiere23b3882019-02-14 07:35:43 -08001737 VLOG(image) << "AppImage:load_startup_cache";
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001738 // Only add the intern table if we are using the startup cache. Otherwise,
1739 // UpdateInternStrings adds the strings to the intern table.
1740 intern_table->AddImageStringsToTable(space, func);
1741 update_intern_strings = kIsDebugBuild || !intern_remap.empty();
1742 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
1743 } else {
1744 update_intern_strings = true;
1745 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001746
1747 // For debug builds, always run the code below to get coverage.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001748 if (update_intern_strings) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001749 // Slow path case is when there are conflicting intern strings to fix up.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001750 UpdateInternStrings(space, /*use_preresolved_strings=*/ load_startup_cache, intern_remap);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001751 }
1752}
1753
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001754static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1755 const char* location,
1756 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001757 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001758 DCHECK(error_msg != nullptr);
1759 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001760 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001761 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001762 return std::unique_ptr<const DexFile>();
1763 }
1764 std::string inner_error_msg;
1765 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1766 if (dex_file == nullptr) {
1767 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1768 location,
1769 oat_file->GetLocation().c_str(),
1770 inner_error_msg.c_str());
1771 return std::unique_ptr<const DexFile>();
1772 }
1773
1774 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1775 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1776 location,
1777 dex_file->GetLocationChecksum(),
1778 oat_dex_file->GetDexFileLocationChecksum());
1779 return std::unique_ptr<const DexFile>();
1780 }
1781 return dex_file;
1782}
1783
1784bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1785 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1786 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001787 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001788 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001789 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001790 DCHECK(dex_caches_object != nullptr);
1791 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1792 dex_caches_object->AsObjectArray<mirror::DexCache>();
1793 const OatFile* oat_file = space->GetOatFile();
1794 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001795 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001796 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1797 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1798 dex_file_location.c_str(),
1799 error_msg);
1800 if (dex_file == nullptr) {
1801 return false;
1802 }
1803 dex_cache->SetDexFile(dex_file.get());
1804 out_dex_files->push_back(std::move(dex_file));
1805 }
1806 return true;
1807}
1808
Andreas Gampe0793bec2016-12-01 11:37:33 -08001809// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1810// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001811class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001812 public:
1813 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1814 REQUIRES_SHARED(Locks::mutator_lock_) {
1815 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001816 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1817 DCHECK(obj != nullptr);
1818 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1819 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1820 if (obj->IsClass()) {
1821 auto klass = obj->AsClass();
1822 for (ArtField& field : klass->GetIFields()) {
1823 CHECK_EQ(field.GetDeclaringClass(), klass);
1824 }
1825 for (ArtField& field : klass->GetSFields()) {
1826 CHECK_EQ(field.GetDeclaringClass(), klass);
1827 }
1828 const auto pointer_size = isc.pointer_size_;
1829 for (auto& m : klass->GetMethods(pointer_size)) {
1830 isc.SanityCheckArtMethod(&m, klass);
1831 }
1832 auto* vtable = klass->GetVTable();
1833 if (vtable != nullptr) {
1834 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1835 }
1836 if (klass->ShouldHaveImt()) {
1837 ImTable* imt = klass->GetImt(pointer_size);
1838 for (size_t i = 0; i < ImTable::kSize; ++i) {
1839 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1840 }
1841 }
1842 if (klass->ShouldHaveEmbeddedVTable()) {
1843 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1844 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1845 }
1846 }
1847 mirror::IfTable* iftable = klass->GetIfTable();
1848 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1849 if (iftable->GetMethodArrayCount(i) > 0) {
1850 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1851 }
1852 }
1853 }
1854 };
1855 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001856 }
1857
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001858 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1859 ClassLinker* class_linker,
1860 mirror::MethodDexCacheType* arr,
1861 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001862 REQUIRES_SHARED(Locks::mutator_lock_) {
1863 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001864 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001865 }
1866
Andreas Gampe0793bec2016-12-01 11:37:33 -08001867 private:
1868 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1869 : spaces_(heap->GetBootImageSpaces()),
1870 pointer_size_(class_linker->GetImagePointerSize()) {
1871 space_begin_.reserve(spaces_.size());
1872 method_sections_.reserve(spaces_.size());
1873 runtime_method_sections_.reserve(spaces_.size());
1874 for (gc::space::ImageSpace* space : spaces_) {
1875 space_begin_.push_back(space->Begin());
1876 auto& header = space->GetImageHeader();
1877 method_sections_.push_back(&header.GetMethodsSection());
1878 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1879 }
1880 }
1881
1882 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1883 REQUIRES_SHARED(Locks::mutator_lock_) {
1884 if (m->IsRuntimeMethod()) {
1885 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1886 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1887 } else if (m->IsCopied()) {
1888 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1889 } else if (expected_class != nullptr) {
1890 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1891 }
1892 if (!spaces_.empty()) {
1893 bool contains = false;
1894 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1895 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1896 contains = method_sections_[i]->Contains(offset) ||
1897 runtime_method_sections_[i]->Contains(offset);
1898 }
1899 CHECK(contains) << m << " not found";
1900 }
1901 }
1902
1903 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1904 ObjPtr<mirror::Class> expected_class)
1905 REQUIRES_SHARED(Locks::mutator_lock_) {
1906 CHECK(arr != nullptr);
1907 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1908 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1909 // expected_class == null means we are a dex cache.
1910 if (expected_class != nullptr) {
1911 CHECK(method != nullptr);
1912 }
1913 if (method != nullptr) {
1914 SanityCheckArtMethod(method, expected_class);
1915 }
1916 }
1917 }
1918
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001919 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001920 REQUIRES_SHARED(Locks::mutator_lock_) {
1921 CHECK_EQ(arr != nullptr, size != 0u);
1922 if (arr != nullptr) {
1923 bool contains = false;
1924 for (auto space : spaces_) {
1925 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001926 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001927 contains = true;
1928 break;
1929 }
1930 }
1931 CHECK(contains);
1932 }
1933 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001934 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1935 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001936 // expected_class == null means we are a dex cache.
1937 if (method != nullptr) {
1938 SanityCheckArtMethod(method, nullptr);
1939 }
1940 }
1941 }
1942
1943 const std::vector<gc::space::ImageSpace*>& spaces_;
1944 const PointerSize pointer_size_;
1945
1946 // Cached sections from the spaces.
1947 std::vector<const uint8_t*> space_begin_;
1948 std::vector<const ImageSection*> method_sections_;
1949 std::vector<const ImageSection*> runtime_method_sections_;
1950};
1951
Andreas Gampebe7af222017-07-25 09:57:28 -07001952static void VerifyAppImage(const ImageHeader& header,
1953 const Handle<mirror::ClassLoader>& class_loader,
1954 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1955 ClassTable* class_table, gc::space::ImageSpace* space)
1956 REQUIRES_SHARED(Locks::mutator_lock_) {
1957 {
1958 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1959 public:
1960 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1961
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001962 void Visit(ArtMethod* method) override
Andreas Gampebe7af222017-07-25 09:57:28 -07001963 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1964 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1965 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1966 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1967 }
1968 }
1969
1970 private:
1971 ClassTable* const table_;
1972 };
1973 VerifyClassInTableArtMethodVisitor visitor(class_table);
1974 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1975 }
1976 {
1977 // Verify that all direct interfaces of classes in the class table are also resolved.
1978 std::vector<ObjPtr<mirror::Class>> classes;
1979 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1980 REQUIRES_SHARED(Locks::mutator_lock_) {
1981 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1982 classes.push_back(klass);
1983 }
1984 return true;
1985 };
1986 class_table->Visit(verify_direct_interfaces_in_table);
1987 Thread* self = Thread::Current();
1988 for (ObjPtr<mirror::Class> klass : classes) {
1989 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1990 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1991 << klass->PrettyDescriptor() << " iface #" << i;
1992 }
1993 }
1994 }
1995 // Check that all non-primitive classes in dex caches are also in the class table.
1996 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1997 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1998 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1999 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2000 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
2001 if (klass != nullptr && !klass->IsPrimitive()) {
2002 CHECK(class_table->Contains(klass))
2003 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
2004 }
2005 }
2006 }
2007}
2008
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002009bool ClassLinker::AddImageSpace(
2010 gc::space::ImageSpace* space,
2011 Handle<mirror::ClassLoader> class_loader,
2012 jobjectArray dex_elements,
2013 const char* dex_location,
2014 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
2015 std::string* error_msg) {
2016 DCHECK(out_dex_files != nullptr);
2017 DCHECK(error_msg != nullptr);
2018 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002019 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002020 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002021 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002022 DCHECK(dex_caches_object != nullptr);
2023 Runtime* const runtime = Runtime::Current();
2024 gc::Heap* const heap = runtime->GetHeap();
2025 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002026 // Check that the image is what we are expecting.
2027 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
2028 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
2029 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
2030 image_pointer_size_);
2031 return false;
2032 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002033 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2034 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2035 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2036 expected_image_roots,
2037 header.GetImageRoots()->GetLength());
2038 return false;
2039 }
2040 StackHandleScope<3> hs(self);
2041 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2042 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2043 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2044 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002045 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002046 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2047 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002048 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002049 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002050 *error_msg = StringPrintf("Expected %d class roots but got %d",
2051 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002052 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002053 return false;
2054 }
2055 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002056 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2057 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2058 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002059 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2060 return false;
2061 }
2062 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002063 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002064 if (oat_file->GetOatHeader().GetDexFileCount() !=
2065 static_cast<uint32_t>(dex_caches->GetLength())) {
2066 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2067 "image";
2068 return false;
2069 }
2070
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002071 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002072 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2073 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002074 // TODO: Only store qualified paths.
2075 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002076 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002077 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2078 dex_file_location.c_str(),
2079 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002080 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002081 return false;
2082 }
2083
2084 if (app_image) {
2085 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2086 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002087 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002088 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002089 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002090 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002091 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002092 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002093 }
2094 }
2095 } else {
2096 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002097 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2098 this,
2099 dex_cache->GetResolvedMethods(),
2100 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002101 }
2102 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002103 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002104 }
2105 out_dex_files->push_back(std::move(dex_file));
2106 }
2107
2108 if (app_image) {
2109 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002110 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002111 // Check that the class loader resolves the same way as the ones in the image.
2112 // Image class loader [A][B][C][image dex files]
2113 // Class loader = [???][dex_elements][image dex files]
2114 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002115 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002116 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2117 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2118 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002119 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2120 *error_msg = "Unexpected BootClassLoader in app image";
2121 return false;
2122 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002123 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2124 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2125 // special case the comparison of dex files of the two class loaders, but then do full
2126 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002127 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002128 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002129 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2130 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2131 if (element != nullptr) {
2132 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002133 ObjPtr<mirror::String> name;
2134 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2135 loader_dex_file_names.push_back(name);
2136 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002137 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002138 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002139 std::string temp_error_msg;
2140 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2141 bool success = GetDexFileNames(
2142 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2143 if (success) {
2144 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2145 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2146 static_cast<size_t>(dex_caches->GetLength()));
2147 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2148 image_dex_file_names.resize(image_count);
2149 success = success && CompareDexFiles(image_dex_file_names,
2150 loader_dex_file_names,
2151 &temp_error_msg);
2152 success = success && CompareClassLoaders(soa,
2153 image_class_loader.Get(),
2154 class_loader.Get(),
2155 /*check_dex_file_names=*/ false,
2156 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002157 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002158 if (!success) {
2159 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2160 temp_error_msg.c_str());
2161 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002162 }
2163 }
2164
2165 if (kSanityCheckObjects) {
2166 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2167 auto* dex_cache = dex_caches->Get(i);
2168 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2169 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2170 if (field != nullptr) {
2171 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2172 }
2173 }
2174 }
2175 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002176 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002177 }
2178 }
2179
2180 // Set entry point to interpreter if in InterpretOnly mode.
2181 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002182 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07002183 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002184 }
2185
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002186 ClassTable* class_table = nullptr;
2187 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002188 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002189 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002190 }
2191 // If we have a class table section, read it and use it for verification in
2192 // UpdateAppImageClassLoadersAndDexCaches.
2193 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002194 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002195 const bool added_class_table = class_table_section.Size() > 0u;
2196 if (added_class_table) {
2197 const uint64_t start_time2 = NanoTime();
2198 size_t read_count = 0;
2199 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2200 /*make copy*/false,
2201 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002202 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002203 }
2204 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002205 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002206
2207 {
2208 ScopedTrace trace("AppImage:UpdateClassLoaders");
2209 // Update class loader and resolved strings. If added_class_table is false, the resolved
2210 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002211 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002212 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002213 // Note: We probably don't need the read barrier unless we copy the app image objects into
2214 // the region space.
2215 ObjPtr<mirror::Class> klass(root.Read());
2216 // Do not update class loader for boot image classes where the app image
2217 // class loader is only the initiating loader but not the defining loader.
2218 // Avoid read barrier since we are comparing against null.
2219 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2220 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2221 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002222 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002223 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002224
Vladimir Marko305c38b2018-02-14 11:50:07 +00002225 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002226 // Every class in the app image has initially SubtypeCheckInfo in the
2227 // Uninitialized state.
2228 //
2229 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2230 // after class initialization is complete. The app image ClassStatus as-is
2231 // are almost all ClassStatus::Initialized, and being in the
2232 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2233 //
2234 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2235 //
2236 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002237 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002238 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2239 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002240 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002241 }
2242 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002243 }
2244 if (!oat_file->GetBssGcRoots().empty()) {
2245 // Insert oat file to class table for visiting .bss GC roots.
2246 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002247 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002248
Mathieu Chartier69731002016-03-02 16:08:31 -08002249 if (added_class_table) {
2250 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2251 class_table->AddClassSet(std::move(temp_set));
2252 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002253
Mathieu Chartier69731002016-03-02 16:08:31 -08002254 if (kIsDebugBuild && app_image) {
2255 // This verification needs to happen after the classes have been added to the class loader.
2256 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002257 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002258 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002259 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002260
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002261 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002262 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002263}
2264
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002265bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002266 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2267 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002268}
2269
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002270void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002271 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2272 // enabling tracing requires the mutator lock, there are no race conditions here.
2273 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002274 Thread* const self = Thread::Current();
2275 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002276 if (kUseReadBarrier) {
2277 // We do not track new roots for CC.
2278 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2279 kVisitRootFlagClearRootLog |
2280 kVisitRootFlagStartLoggingNewRoots |
2281 kVisitRootFlagStopLoggingNewRoots));
2282 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002283 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002284 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2285 // There is 3 GC cases to handle:
2286 // Non moving concurrent:
2287 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002288 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002289 //
2290 // Moving non-concurrent:
2291 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2292 // To prevent missing roots, this case needs to ensure that there is no
2293 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2294 // class which is in the class table.
2295 //
2296 // Moving concurrent:
2297 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2298 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002299 //
2300 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2301 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2302 // these objects.
2303 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002304 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002305 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002306 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002307 for (const ClassLoaderData& data : class_loaders_) {
2308 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2309 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2310 }
2311 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002312 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002313 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002314 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002315 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002316 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002317 // Concurrent moving GC marked new roots through the to-space invariant.
2318 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002319 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002320 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2321 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2322 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2323 if (old_ref != nullptr) {
2324 DCHECK(old_ref->IsClass());
2325 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2326 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2327 // Concurrent moving GC marked new roots through the to-space invariant.
2328 CHECK_EQ(new_ref, old_ref);
2329 }
2330 }
2331 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002332 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002333 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002334 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002335 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002336 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002337 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002338 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002339 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002340 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002341 }
2342 // We deliberately ignore the class roots in the image since we
2343 // handle image roots by using the MS/CMS rescanning of dirty cards.
2344}
2345
Brian Carlstroma663ea52011-08-19 23:33:41 -07002346// Keep in sync with InitCallback. Anything we visit, we need to
2347// reinit references to when reinitializing a ClassLinker from a
2348// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002349void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002350 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002351 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002352 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2353 // unloading if we are marking roots.
2354 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002355}
2356
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002357class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2358 public:
2359 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2360 : visitor_(visitor),
2361 done_(false) {}
2362
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002363 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002364 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002365 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002366 if (!done_ && class_table != nullptr) {
2367 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2368 if (!class_table->Visit(visitor)) {
2369 // If the visitor ClassTable returns false it means that we don't need to continue.
2370 done_ = true;
2371 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002372 }
2373 }
2374
2375 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002376 // Class visitor that limits the class visits from a ClassTable to the classes with
2377 // the provided defining class loader. This filter is used to avoid multiple visits
2378 // of the same class which can be recorded for multiple initiating class loaders.
2379 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2380 public:
2381 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2382 ClassVisitor* visitor)
2383 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2384
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002385 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002386 if (klass->GetClassLoader() != defining_class_loader_) {
2387 return true;
2388 }
2389 return (*visitor_)(klass);
2390 }
2391
2392 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2393 ClassVisitor* const visitor_;
2394 };
2395
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002396 ClassVisitor* const visitor_;
2397 // If done is true then we don't need to do any more visiting.
2398 bool done_;
2399};
2400
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002401void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002402 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002403 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2404 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002405 }
2406}
2407
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002408void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002409 Thread* const self = Thread::Current();
2410 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2411 // Not safe to have thread suspension when we are holding a lock.
2412 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002413 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002414 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002415 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002416 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002417 }
2418}
2419
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002420class GetClassesInToVector : public ClassVisitor {
2421 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002422 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002423 classes_.push_back(klass);
2424 return true;
2425 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002426 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002427};
2428
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002429class GetClassInToObjectArray : public ClassVisitor {
2430 public:
2431 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2432 : arr_(arr), index_(0) {}
2433
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002434 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002435 ++index_;
2436 if (index_ <= arr_->GetLength()) {
2437 arr_->Set(index_ - 1, klass);
2438 return true;
2439 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002440 return false;
2441 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002442
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002443 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002444 return index_ <= arr_->GetLength();
2445 }
2446
2447 private:
2448 mirror::ObjectArray<mirror::Class>* const arr_;
2449 int32_t index_;
2450};
2451
2452void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002453 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2454 // is avoiding duplicates.
2455 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002456 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002457 GetClassesInToVector accumulator;
2458 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002459 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002460 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002461 return;
2462 }
2463 }
2464 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002465 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002466 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002467 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002468 // We size the array assuming classes won't be added to the class table during the visit.
2469 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002470 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002471 size_t class_table_size;
2472 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002473 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002474 // Add 100 in case new classes get loaded when we are filling in the object array.
2475 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002476 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002477 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002478 classes.Assign(
2479 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002480 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002481 GetClassInToObjectArray accumulator(classes.Get());
2482 VisitClasses(&accumulator);
2483 if (accumulator.Succeeded()) {
2484 break;
2485 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002486 }
2487 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2488 // If the class table shrank during creation of the clases array we expect null elements. If
2489 // the class table grew then the loop repeats. If classes are created after the loop has
2490 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002491 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002492 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002493 return;
2494 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002495 }
2496 }
2497}
2498
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002499ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002500 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002501 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002502 // CHA unloading analysis is not needed. No negative consequences are expected because
2503 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002504 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002505 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002506 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002507}
2508
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002509void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002510 Runtime* const runtime = Runtime::Current();
2511 JavaVMExt* const vm = runtime->GetJavaVM();
2512 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002513 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002514 if (runtime->GetJit() != nullptr) {
2515 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2516 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002517 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002518 code_cache->RemoveMethodsIn(self, *data.allocator);
2519 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002520 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002521 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002522 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002523 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002524 // Cleanup references to single implementation ArtMethods that will be deleted.
2525 if (cleanup_cha) {
2526 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2527 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2528 }
2529
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002530 delete data.allocator;
2531 delete data.class_table;
2532}
2533
Vladimir Markobcf17522018-06-01 13:14:32 +01002534ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2535 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002536 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002537 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2538 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002539}
2540
Vladimir Markobcf17522018-06-01 13:14:32 +01002541ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2542 Thread* self,
2543 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002544 StackHandleScope<1> hs(self);
2545 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002546 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002547 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002548 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002549 self->AssertPendingOOMException();
2550 return nullptr;
2551 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002552 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002553 if (location == nullptr) {
2554 self->AssertPendingOOMException();
2555 return nullptr;
2556 }
2557 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002558 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002559}
2560
Vladimir Markobcf17522018-06-01 13:14:32 +01002561ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2562 const DexFile& dex_file,
2563 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002564 ObjPtr<mirror::String> location = nullptr;
2565 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002566 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002567 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002568 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002569 mirror::DexCache::InitializeDexCache(self,
2570 dex_cache,
2571 location,
2572 &dex_file,
2573 linear_alloc,
2574 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002575 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002576 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002577}
2578
Roland Levillain0e840272018-08-23 19:55:30 +01002579template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002580ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2581 ObjPtr<mirror::Class> java_lang_Class,
2582 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002583 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002584 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002585 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002586 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002587 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2588 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002589 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002590 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002591 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002592 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002593 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002594}
2595
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002596ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002597 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002598}
2599
Roland Levillain0e840272018-08-23 19:55:30 +01002600ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2601 ObjPtr<mirror::Class> java_lang_Class) {
2602 // We make this class non-movable for the unlikely case where it were to be
2603 // moved by a sticky-bit (minor) collection when using the Generational
2604 // Concurrent Copying (CC) collector, potentially creating a stale reference
2605 // in the `klass_` field of one of its instances allocated in the Large-Object
2606 // Space (LOS) -- see the comment about the dirty card scanning logic in
2607 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002608 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002609 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2610}
2611
Vladimir Markobcf17522018-06-01 13:14:32 +01002612ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002613 Thread* self,
2614 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002615 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002616 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002617}
2618
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002619ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2620 const char* descriptor,
2621 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002622 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002623 if (kIsDebugBuild) {
2624 StackHandleScope<1> hs(self);
2625 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2626 Thread::PoisonObjectPointersIfDebug();
2627 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002628
2629 // For temporary classes we must wait for them to be retired.
2630 if (init_done_ && klass->IsTemp()) {
2631 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002632 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002633 ThrowEarlierClassFailure(klass);
2634 return nullptr;
2635 }
2636 StackHandleScope<1> hs(self);
2637 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2638 ObjectLock<mirror::Class> lock(self, h_class);
2639 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002640 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002641 lock.WaitIgnoringInterrupts();
2642 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002643 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002644 ThrowEarlierClassFailure(h_class.Get());
2645 return nullptr;
2646 }
2647 CHECK(h_class->IsRetired());
2648 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002649 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002650 }
2651
Brian Carlstromaded5f72011-10-07 17:15:04 -07002652 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002653 size_t index = 0;
2654 // Maximum number of yield iterations until we start sleeping.
2655 static const size_t kNumYieldIterations = 1000;
2656 // How long each sleep is in us.
2657 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002658 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002659 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002660 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002661 {
2662 ObjectTryLock<mirror::Class> lock(self, h_class);
2663 // Can not use a monitor wait here since it may block when returning and deadlock if another
2664 // thread has locked klass.
2665 if (lock.Acquired()) {
2666 // Check for circular dependencies between classes, the lock is required for SetStatus.
2667 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2668 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002669 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002670 return nullptr;
2671 }
2672 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002673 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002674 {
2675 // Handle wrapper deals with klass moving.
2676 ScopedThreadSuspension sts(self, kSuspended);
2677 if (index < kNumYieldIterations) {
2678 sched_yield();
2679 } else {
2680 usleep(kSleepDurationUS);
2681 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002682 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002683 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002684 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002685
Vladimir Marko72ab6842017-01-20 19:32:50 +00002686 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002687 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002688 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002689 }
2690 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002691 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002692 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002693 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002694}
2695
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002696using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002697
2698// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002699ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002700 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002701 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002702 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002703 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002704 return ClassPathEntry(dex_file, dex_class_def);
2705 }
2706 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002707 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002708}
2709
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002710bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2711 Thread* self,
2712 const char* descriptor,
2713 size_t hash,
2714 Handle<mirror::ClassLoader> class_loader,
2715 /*out*/ ObjPtr<mirror::Class>* result) {
2716 ArtField* field =
2717 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2718 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2719 if (raw_shared_libraries == nullptr) {
2720 return true;
2721 }
2722
2723 StackHandleScope<2> hs(self);
2724 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2725 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2726 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2727 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2728 temp_loader.Assign(shared_libraries->Get(i));
2729 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2730 return false; // One of the shared libraries is not supported.
2731 }
2732 if (*result != nullptr) {
2733 return true; // Found the class up the chain.
2734 }
2735 }
2736 return true;
2737}
2738
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002739bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2740 Thread* self,
2741 const char* descriptor,
2742 size_t hash,
2743 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002744 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002745 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002746 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002747 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002748 return true;
2749 }
2750
David Brazdil05909d82018-12-06 16:25:16 +00002751 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002752 // For regular path or dex class loader the search order is:
2753 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002754 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002755 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002756
Calin Juravlecdd49122017-07-05 20:09:53 -07002757 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2758 StackHandleScope<1> hs(self);
2759 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2760 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2761 return false; // One of the parents is not supported.
2762 }
2763 if (*result != nullptr) {
2764 return true; // Found the class up the chain.
2765 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002766
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002767 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2768 return false; // One of the shared library loader is not supported.
2769 }
2770 if (*result != nullptr) {
2771 return true; // Found the class in a shared library.
2772 }
2773
Calin Juravlecdd49122017-07-05 20:09:53 -07002774 // Search the current class loader classpath.
2775 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002776 return true;
2777 }
2778
Calin Juravlecdd49122017-07-05 20:09:53 -07002779 if (IsDelegateLastClassLoader(soa, class_loader)) {
2780 // For delegate last, the search order is:
2781 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002782 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002783 // - class loader dex files
2784 // - parent
2785 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2786 if (*result != nullptr) {
2787 return true; // The class is part of the boot class path.
2788 }
2789
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002790 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2791 return false; // One of the shared library loader is not supported.
2792 }
2793 if (*result != nullptr) {
2794 return true; // Found the class in a shared library.
2795 }
2796
Calin Juravlecdd49122017-07-05 20:09:53 -07002797 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2798 if (*result != nullptr) {
2799 return true; // Found the class in the current class loader
2800 }
2801
2802 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2803 StackHandleScope<1> hs(self);
2804 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2805 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2806 }
2807
2808 // Unsupported class loader.
2809 *result = nullptr;
2810 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002811}
2812
2813// Finds the class in the boot class loader.
2814// If the class is found the method returns the resolved class. Otherwise it returns null.
2815ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2816 const char* descriptor,
2817 size_t hash) {
2818 ObjPtr<mirror::Class> result = nullptr;
2819 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2820 if (pair.second != nullptr) {
2821 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2822 if (klass != nullptr) {
2823 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002824 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002825 result = DefineClass(self,
2826 descriptor,
2827 hash,
2828 ScopedNullHandle<mirror::ClassLoader>(),
2829 *pair.first,
2830 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002831 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002832 if (result == nullptr) {
2833 CHECK(self->IsExceptionPending()) << descriptor;
2834 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002835 }
2836 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002837 return result;
2838}
Andreas Gampef865ea92015-04-13 22:14:19 -07002839
Calin Juravle415dc3d2017-06-28 11:03:12 -07002840ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2841 ScopedObjectAccessAlreadyRunnable& soa,
2842 const char* descriptor,
2843 size_t hash,
2844 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002845 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2846 IsInMemoryDexClassLoader(soa, class_loader) ||
2847 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002848 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002849
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002850 ObjPtr<mirror::Class> ret;
2851 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002852 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002853 if (dex_class_def != nullptr) {
2854 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2855 descriptor,
2856 hash,
2857 class_loader,
2858 *cp_dex_file,
2859 *dex_class_def);
2860 if (klass == nullptr) {
2861 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2862 soa.Self()->ClearException();
2863 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002864 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002865 ret = klass;
2866 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002867 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002868 return true; // Continue with the next DexFile.
2869 };
2870
2871 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2872 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002873}
2874
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002875ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2876 const char* descriptor,
2877 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002878 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002879 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002880 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002881 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002882 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002883 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2884 // for primitive classes that aren't backed by dex files.
2885 return FindPrimitiveClass(descriptor[0]);
2886 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002887 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002888 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002889 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002890 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002891 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002892 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002893 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002894 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002895 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002896 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002897 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002898 return DefineClass(self,
2899 descriptor,
2900 hash,
2901 ScopedNullHandle<mirror::ClassLoader>(),
2902 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002903 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002904 } else {
2905 // The boot class loader is searched ahead of the application class loader, failures are
2906 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2907 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002908 ObjPtr<mirror::Throwable> pre_allocated =
2909 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002910 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002911 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002912 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002913 }
2914 ObjPtr<mirror::Class> result_ptr;
2915 bool descriptor_equals;
2916 if (descriptor[0] == '[') {
2917 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2918 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2919 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2920 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002921 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002922 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002923 bool known_hierarchy =
2924 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2925 if (result_ptr != nullptr) {
2926 // The chain was understood and we found the class. We still need to add the class to
2927 // the class table to protect from racy programs that can try and redefine the path list
2928 // which would change the Class<?> returned for subsequent evaluation of const-class.
2929 DCHECK(known_hierarchy);
2930 DCHECK(result_ptr->DescriptorEquals(descriptor));
2931 descriptor_equals = true;
2932 } else {
2933 // Either the chain wasn't understood or the class wasn't found.
2934 //
2935 // If the chain was understood but we did not find the class, let the Java-side
2936 // rediscover all this and throw the exception with the right stack trace. Note that
2937 // the Java-side could still succeed for racy programs if another thread is actively
2938 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002939
Alex Light185a4612018-10-04 15:54:25 -07002940 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002941 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002942 // Oops, we can't call into java so we can't run actual class-loader code.
2943 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002944 ObjPtr<mirror::Throwable> pre_allocated =
2945 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2946 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002947 return nullptr;
2948 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002949
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002950 // Inlined DescriptorToDot(descriptor) with extra validation.
2951 //
2952 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2953 // the DescriptorEquals() check below and give a confusing error message. For example,
2954 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2955 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2956 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2957 size_t descriptor_length = strlen(descriptor);
2958 if (UNLIKELY(descriptor[0] != 'L') ||
2959 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2960 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2961 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2962 return nullptr;
2963 }
2964 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2965 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2966
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002967 ScopedLocalRef<jobject> class_loader_object(
2968 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002969 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2970 {
2971 ScopedThreadStateChange tsc(self, kNative);
2972 ScopedLocalRef<jobject> class_name_object(
2973 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2974 if (class_name_object.get() == nullptr) {
2975 DCHECK(self->IsExceptionPending()); // OOME.
2976 return nullptr;
2977 }
2978 CHECK(class_loader_object.get() != nullptr);
2979 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2980 WellKnownClasses::java_lang_ClassLoader_loadClass,
2981 class_name_object.get()));
2982 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002983 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002984 // broken loader - throw NPE to be compatible with Dalvik
2985 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2986 class_name_string.c_str()).c_str());
2987 return nullptr;
2988 }
2989 result_ptr = soa.Decode<mirror::Class>(result.get());
2990 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002991 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002992 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002993 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002994
2995 if (self->IsExceptionPending()) {
2996 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2997 // However, to comply with the RI behavior, first check if another thread succeeded.
2998 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2999 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3000 self->ClearException();
3001 return EnsureResolved(self, descriptor, result_ptr);
3002 }
3003 return nullptr;
3004 }
3005
3006 // Try to insert the class to the class table, checking for mismatch.
3007 ObjPtr<mirror::Class> old;
3008 {
3009 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3010 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3011 old = class_table->Lookup(descriptor, hash);
3012 if (old == nullptr) {
3013 old = result_ptr; // For the comparison below, after releasing the lock.
3014 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003015 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003016 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003017 } // else throw below, after releasing the lock.
3018 }
3019 }
3020 if (UNLIKELY(old != result_ptr)) {
3021 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3022 // capable class loaders. (All class loaders are considered parallel capable on Android.)
3023 mirror::Class* loader_class = class_loader->GetClass();
3024 const char* loader_class_name =
3025 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3026 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3027 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3028 << DescriptorToDot(descriptor) << "\").";
3029 return EnsureResolved(self, descriptor, old);
3030 }
3031 if (UNLIKELY(!descriptor_equals)) {
3032 std::string result_storage;
3033 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3034 std::string loader_storage;
3035 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3036 ThrowNoClassDefFoundError(
3037 "Initiating class loader of type %s returned class %s instead of %s.",
3038 DescriptorToDot(loader_class_name).c_str(),
3039 DescriptorToDot(result_name).c_str(),
3040 DescriptorToDot(descriptor).c_str());
3041 return nullptr;
3042 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003043 // Success.
3044 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003045}
3046
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003047ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3048 const char* descriptor,
3049 size_t hash,
3050 Handle<mirror::ClassLoader> class_loader,
3051 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003052 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003054 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003055
Brian Carlstromaded5f72011-10-07 17:15:04 -07003056 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003057 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003058 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003059 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003060 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003061 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003062 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003063 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003064 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003065 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003066 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003067 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003068 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003069 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003070 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003071 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003072 }
3073
Alex Lighte9f61032018-09-24 16:04:51 -07003074 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3075 // code to be executed. We put it up here so we can avoid all the allocations associated with
3076 // creating the class. This can happen with (eg) jit threads.
3077 if (!self->CanLoadClasses()) {
3078 // Make sure we don't try to load anything, potentially causing an infinite loop.
3079 ObjPtr<mirror::Throwable> pre_allocated =
3080 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3081 self->SetException(pre_allocated);
3082 return nullptr;
3083 }
3084
Andreas Gampefa4333d2017-02-14 11:10:34 -08003085 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003086 // Allocate a class with the status of not ready.
3087 // Interface object should get the right size here. Regular class will
3088 // figure out the right size later and be replaced with one of the right
3089 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003090 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003091 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003092 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003093 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003094 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003095 }
Alex Lightb0f11922017-01-23 14:25:17 -08003096 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3097 // nothing.
3098 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003099 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003100 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3101 // will only be called once.
3102 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3103 klass,
3104 class_loader,
3105 dex_file,
3106 dex_class_def,
3107 &new_dex_file,
3108 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003109 // Check to see if an exception happened during runtime callbacks. Return if so.
3110 if (self->IsExceptionPending()) {
3111 return nullptr;
3112 }
Alex Lightb0f11922017-01-23 14:25:17 -08003113 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003114 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003115 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003116 return nullptr;
3117 }
3118 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003119 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003120
Jeff Hao848f70a2014-01-15 13:49:50 -08003121 // Mark the string class by setting its access flag.
3122 if (UNLIKELY(!init_done_)) {
3123 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3124 klass->SetStringClass();
3125 }
3126 }
3127
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003128 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003129 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003130 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003131 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003132
Mathieu Chartier590fee92013-09-13 13:46:47 -07003133 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003134 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003135 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003136 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3137 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003138 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003139 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003140
Mathieu Chartierc7853442015-03-27 14:35:38 -07003141 // Load the fields and other things after we are inserted in the table. This is so that we don't
3142 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3143 // other reason is that the field roots are only visited from the class table. So we need to be
3144 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003145 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003146 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003147 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003148 // An exception occured during load, set status to erroneous while holding klass' lock in case
3149 // notification is necessary.
3150 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003151 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003152 }
3153 return nullptr;
3154 }
3155
Brian Carlstromaded5f72011-10-07 17:15:04 -07003156 // Finish loading (if necessary) by finding parents
3157 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003158 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003159 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003160 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003161 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003162 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003163 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003164 }
3165 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003166
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003167 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003168 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003169 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003170
Brian Carlstromaded5f72011-10-07 17:15:04 -07003171 // Link the class (if necessary)
3172 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003173 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003174 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003175
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003176 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003177 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003178 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003179 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003180 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003181 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003182 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003183 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003184 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003185 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003186 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003187
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003188 // Instrumentation may have updated entrypoints for all methods of all
3189 // classes. However it could not update methods of this class while we
3190 // were loading it. Now the class is resolved, we can update entrypoints
3191 // as required by instrumentation.
3192 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3193 // We must be in the kRunnable state to prevent instrumentation from
3194 // suspending all threads to update entrypoints while we are doing it
3195 // for this class.
3196 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003197 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003198 }
3199
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003200 /*
3201 * We send CLASS_PREPARE events to the debugger from here. The
3202 * definition of "preparation" is creating the static fields for a
3203 * class and initializing them to the standard default values, but not
3204 * executing any code (that comes later, during "initialization").
3205 *
3206 * We did the static preparation in LinkClass.
3207 *
3208 * The class has been prepared and resolved but possibly not yet verified
3209 * at this point.
3210 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003211 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003212
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003213 // Notify native debugger of the new class and its layout.
3214 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3215
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003216 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003217}
3218
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003219uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003220 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003221 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003222 size_t num_8 = 0;
3223 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003224 size_t num_32 = 0;
3225 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003226 ClassAccessor accessor(dex_file, dex_class_def);
3227 // We allow duplicate definitions of the same field in a class_data_item
3228 // but ignore the repeated indexes here, b/21868015.
3229 uint32_t last_field_idx = dex::kDexNoIndex;
3230 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3231 uint32_t field_idx = field.GetIndex();
3232 // Ordering enforced by DexFileVerifier.
3233 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3234 if (UNLIKELY(field_idx == last_field_idx)) {
3235 continue;
3236 }
3237 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003238 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003239 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3240 char c = descriptor[0];
3241 switch (c) {
3242 case 'L':
3243 case '[':
3244 num_ref++;
3245 break;
3246 case 'J':
3247 case 'D':
3248 num_64++;
3249 break;
3250 case 'I':
3251 case 'F':
3252 num_32++;
3253 break;
3254 case 'S':
3255 case 'C':
3256 num_16++;
3257 break;
3258 case 'B':
3259 case 'Z':
3260 num_8++;
3261 break;
3262 default:
3263 LOG(FATAL) << "Unknown descriptor: " << c;
3264 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003265 }
3266 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003267 return mirror::Class::ComputeClassSize(false,
3268 0,
3269 num_8,
3270 num_16,
3271 num_32,
3272 num_64,
3273 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003274 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003275}
3276
Alex Lightfc49fec2018-01-16 22:28:36 +00003277// Special case to get oat code without overwriting a trampoline.
3278const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003279 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003280 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003281 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003282 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003283 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3284 if (code != nullptr) {
3285 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003286 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003287 if (method->IsNative()) {
3288 // No code and native? Use generic trampoline.
3289 return GetQuickGenericJniStub();
3290 }
3291 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003292}
3293
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003294bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003295 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003296 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3297 return false;
3298 }
3299
Elliott Hughes956af0f2014-12-11 14:34:28 -08003300 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003301 return true;
3302 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003303
3304 Runtime* runtime = Runtime::Current();
3305 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3306 if (instr->InterpretOnly()) {
3307 return true;
3308 }
3309
3310 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3311 // Doing this check avoids doing compiled/interpreter transitions.
3312 return true;
3313 }
3314
Alex Light3dacdd62019-03-12 15:45:47 +00003315 if (Thread::Current()->IsForceInterpreter() ||
3316 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003317 // Force the use of interpreter when it is required by the debugger.
3318 return true;
3319 }
3320
Alex Light8f34aba2017-10-09 13:46:32 -07003321 if (Thread::Current()->IsAsyncExceptionPending()) {
3322 // Force use of interpreter to handle async-exceptions
3323 return true;
3324 }
3325
Alex Light2d441b12018-06-08 15:33:21 -07003326 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3327 const void* instr_target = instr->GetCodeForInvoke(method);
3328 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3329 return ShouldUseInterpreterEntrypoint(method, instr_target);
3330 }
3331
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003332 if (runtime->IsJavaDebuggable()) {
3333 // For simplicity, we ignore precompiled code and go to the interpreter
3334 // assuming we don't already have jitted code.
3335 // We could look at the oat file where `quick_code` is being defined,
3336 // and check whether it's been compiled debuggable, but we decided to
3337 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003338 jit::Jit* jit = Runtime::Current()->GetJit();
3339 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3340 }
3341
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003342 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003343 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003344 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003345 // since we want to JIT it (at first use) with extra stackmaps for native
3346 // debugging. We keep however all AOT code from the boot image,
3347 // since the JIT-at-first-use is blocking and would result in non-negligible
3348 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003349 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003350 }
3351
3352 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003353}
3354
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003355void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003356 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003357 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003358 if (klass->NumDirectMethods() == 0) {
3359 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003360 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003361 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003362 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003363 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003364 return; // OAT file unavailable.
3365 }
Ian Rogers19846512012-02-24 11:42:47 -08003366 }
Alex Light64ad14d2014-08-19 14:23:13 -07003367
Mathieu Chartierf8322842014-05-16 10:59:25 -07003368 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003369 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3370 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3371 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003372 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003373 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003374 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003375 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3376 klass->GetDexClassDefIndex(),
3377 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003378 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003379 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003380 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003381 if (!method->IsStatic()) {
3382 // Only update static methods.
3383 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003384 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003385 const void* quick_code = nullptr;
3386 if (has_oat_class) {
3387 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003388 quick_code = oat_method.GetQuickCode();
3389 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003390 // Check whether the method is native, in which case it's generic JNI.
3391 if (quick_code == nullptr && method->IsNative()) {
3392 quick_code = GetQuickGenericJniStub();
3393 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003394 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003395 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003396 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003397 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003398 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003399 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003400}
3401
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003402// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3403// method. Should only be called on non-invokable methods.
3404inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003405 DCHECK(method != nullptr);
3406 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003407 method->SetEntryPointFromQuickCompiledCodePtrSize(
3408 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3409 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003410}
3411
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003412static void LinkCode(ClassLinker* class_linker,
3413 ArtMethod* method,
3414 const OatFile::OatClass* oat_class,
3415 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003416 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003417 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003418 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003419 // The following code only applies to a non-compiler runtime.
3420 return;
3421 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003422 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003423 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003424 if (oat_class != nullptr) {
3425 // Every kind of method should at least get an invoke stub from the oat_method.
3426 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003427 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003428 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003429 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003430
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003431 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003432 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003433 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003434
Alex Light9139e002015-10-09 15:59:48 -07003435 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003436 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003437 return;
3438 }
Ian Rogers19846512012-02-24 11:42:47 -08003439
3440 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003441 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003442 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3443 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003444 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003445 } else if (quick_code == nullptr && method->IsNative()) {
3446 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003447 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003448 // Set entry point from compiled code if there's no code or in interpreter only mode.
3449 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003450 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003451
Ian Rogers62d6c772013-02-27 08:32:07 -08003452 if (method->IsNative()) {
3453 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003454 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003455
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003456 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003457 // We have a native method here without code. Then it should have either the generic JNI
3458 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3459 // TODO: this doesn't handle all the cases where trampolines may be installed.
3460 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003461 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3462 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003463 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003464 }
3465}
3466
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003467void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003468 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003469 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003470 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003471 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003472 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003473 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003474 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003475 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003476
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003477 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003478 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003479 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003480 klass->SetAccessFlags(access_flags);
3481 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003482 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003483 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003484
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003485 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003486 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003487}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003488
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003489LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3490 LinearAlloc* allocator,
3491 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003492 if (length == 0) {
3493 return nullptr;
3494 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003495 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3496 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3497 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003498 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003499 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003500 CHECK(ret != nullptr);
3501 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3502 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003503}
3504
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003505LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3506 LinearAlloc* allocator,
3507 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003508 if (length == 0) {
3509 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003510 }
Vladimir Marko14632852015-08-17 12:07:23 +01003511 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3512 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003513 const size_t storage_size =
3514 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003515 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003516 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003517 CHECK(ret != nullptr);
3518 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003519 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003520 }
3521 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003522}
3523
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003524LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003525 if (class_loader == nullptr) {
3526 return Runtime::Current()->GetLinearAlloc();
3527 }
3528 LinearAlloc* allocator = class_loader->GetAllocator();
3529 DCHECK(allocator != nullptr);
3530 return allocator;
3531}
3532
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003533LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003534 if (class_loader == nullptr) {
3535 return Runtime::Current()->GetLinearAlloc();
3536 }
3537 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3538 LinearAlloc* allocator = class_loader->GetAllocator();
3539 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003540 RegisterClassLoader(class_loader);
3541 allocator = class_loader->GetAllocator();
3542 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003543 }
3544 return allocator;
3545}
3546
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003547void ClassLinker::LoadClass(Thread* self,
3548 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003549 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003550 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003551 ClassAccessor accessor(dex_file,
3552 dex_class_def,
3553 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003554 if (!accessor.HasClassData()) {
3555 return;
3556 }
3557 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003558 {
3559 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3560 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003561 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003562 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003563 // We allow duplicate definitions of the same field in a class_data_item
3564 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003565 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003566 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3567 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003568 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003569 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3570 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003571 accessor.NumInstanceFields());
3572 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003573 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003574 uint32_t last_static_field_idx = 0u;
3575 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003576
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003577 // Methods
3578 bool has_oat_class = false;
3579 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3580 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3581 : OatFile::OatClass::Invalid();
3582 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3583 klass->SetMethodsPtr(
3584 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3585 accessor.NumDirectMethods(),
3586 accessor.NumVirtualMethods());
3587 size_t class_def_method_index = 0;
3588 uint32_t last_dex_method_index = dex::kDexNoIndex;
3589 size_t last_class_def_method_index = 0;
3590
3591 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3592 // methods needs to decode all of the fields.
3593 accessor.VisitFieldsAndMethods([&](
3594 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3595 uint32_t field_idx = field.GetIndex();
3596 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3597 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3598 LoadField(field, klass, &sfields->At(num_sfields));
3599 ++num_sfields;
3600 last_static_field_idx = field_idx;
3601 }
3602 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3603 uint32_t field_idx = field.GetIndex();
3604 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3605 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3606 LoadField(field, klass, &ifields->At(num_ifields));
3607 ++num_ifields;
3608 last_instance_field_idx = field_idx;
3609 }
3610 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3611 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3612 image_pointer_size_);
3613 LoadMethod(dex_file, method, klass, art_method);
3614 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3615 uint32_t it_method_index = method.GetIndex();
3616 if (last_dex_method_index == it_method_index) {
3617 // duplicate case
3618 art_method->SetMethodIndex(last_class_def_method_index);
3619 } else {
3620 art_method->SetMethodIndex(class_def_method_index);
3621 last_dex_method_index = it_method_index;
3622 last_class_def_method_index = class_def_method_index;
3623 }
3624 ++class_def_method_index;
3625 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3626 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3627 class_def_method_index - accessor.NumDirectMethods(),
3628 image_pointer_size_);
3629 LoadMethod(dex_file, method, klass, art_method);
3630 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3631 ++class_def_method_index;
3632 });
3633
3634 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003635 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003636 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3637 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3638 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003639 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3640 if (sfields != nullptr) {
3641 sfields->SetSize(num_sfields);
3642 }
3643 if (ifields != nullptr) {
3644 ifields->SetSize(num_ifields);
3645 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003646 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003647 // Set the field arrays.
3648 klass->SetSFieldsPtr(sfields);
3649 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003650 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003651 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003652 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003653 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003654 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003655 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003656}
3657
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003658void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003659 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003660 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003661 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003662 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003663 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003664
David Brazdil85865692018-10-30 17:26:20 +00003665 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3666 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003667}
3668
Mathieu Chartier268764d2016-09-13 12:09:38 -07003669void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003670 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003671 Handle<mirror::Class> klass,
3672 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003673 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003674 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003675 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003676
Mathieu Chartier268764d2016-09-13 12:09:38 -07003677 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003678 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003679 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003680 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003681
David Brazdil85865692018-10-30 17:26:20 +00003682 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3683 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003684
Ian Rogersdfb325e2013-10-30 01:00:44 -07003685 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003686 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003687 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3688 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003689 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003690 klass->SetFinalizable();
3691 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003692 std::string temp;
3693 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003694 // The Enum class declares a "final" finalize() method to prevent subclasses from
3695 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3696 // subclasses, so we exclude it here.
3697 // We also want to avoid setting the flag on Object, where we know that finalize() is
3698 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003699 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3700 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003701 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003702 }
3703 }
3704 }
3705 } else if (method_name[0] == '<') {
3706 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003707 bool is_init = (strcmp("<init>", method_name) == 0);
3708 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003709 if (UNLIKELY(!is_init && !is_clinit)) {
3710 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3711 } else {
3712 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3713 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003714 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003715 access_flags |= kAccConstructor;
3716 }
3717 }
3718 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003719 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3720 // Check if the native method is annotated with @FastNative or @CriticalNative.
3721 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3722 dex_file, dst->GetClassDef(), dex_method_idx);
3723 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003724 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003725 // Must be done after SetAccessFlags since IsAbstract depends on it.
3726 if (klass->IsInterface() && dst->IsAbstract()) {
3727 dst->CalculateAndSetImtIndex();
3728 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003729}
3730
Ian Rogers7b078e82014-09-10 14:44:24 -07003731void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003732 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003733 self,
3734 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003735 Runtime::Current()->GetLinearAlloc());
3736 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003737 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003738}
3739
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003740void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003741 ObjPtr<mirror::DexCache> dex_cache) {
3742 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003743 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003744 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003745 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003746}
3747
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003748void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003749 ObjPtr<mirror::DexCache> dex_cache,
3750 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003751 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003752 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003753 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003754 // For app images, the dex cache location may be a suffix of the dex file location since the
3755 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003756 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3757 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003758 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3759 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003760 // The following paths checks don't work on preopt when using boot dex files, where the dex
3761 // cache location is the one on device, and the dex_file's location is the one on host.
3762 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3763 CHECK_GE(dex_file_location.length(), dex_cache_length)
3764 << dex_cache_location << " " << dex_file.GetLocation();
3765 const std::string dex_file_suffix = dex_file_location.substr(
3766 dex_file_location.length() - dex_cache_length,
3767 dex_cache_length);
3768 // Example dex_cache location is SettingsProvider.apk and
3769 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3770 CHECK_EQ(dex_cache_location, dex_file_suffix);
3771 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003772 const OatFile* oat_file =
3773 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003774 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3775 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3776 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3777 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003778 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003779 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3780 DexCacheData data = *it;
3781 if (self->IsJWeakCleared(data.weak_root)) {
3782 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003783 it = dex_caches_.erase(it);
3784 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003785 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003786 it->dex_file->GetOatDexFile() != nullptr &&
3787 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003788 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003789 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003790 ++it;
3791 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003792 }
Vladimir Markob066d432018-01-03 13:14:37 +00003793 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003794 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003795 }
David Brazdila5c3a802019-03-08 14:59:41 +00003796 // Let hiddenapi assign a domain to the newly registered dex file.
3797 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3798
Vladimir Markocd556b02017-02-03 11:47:34 +00003799 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003800 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003801 DexCacheData data;
3802 data.weak_root = dex_cache_jweak;
3803 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003804 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003805 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003806 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003807 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3808 // path dex caches without an image.
3809 data.class_table->InsertStrongRoot(dex_cache);
3810 if (class_loader != nullptr) {
3811 // Since we added a strong root to the class table, do the write barrier as required for
3812 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003813 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003814 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003815 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003816}
3817
Vladimir Markocd556b02017-02-03 11:47:34 +00003818ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3819 return data.IsValid()
3820 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3821 : nullptr;
3822}
3823
3824ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3825 Thread* self,
3826 ObjPtr<mirror::DexCache> dex_cache,
3827 const DexCacheData& data,
3828 ObjPtr<mirror::ClassLoader> class_loader) {
3829 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3830 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3831 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3832 "Attempt to register dex file %s with multiple class loaders",
3833 data.dex_file->GetLocation().c_str());
3834 return nullptr;
3835 }
3836 return dex_cache;
3837}
3838
Alex Light07f06212017-06-01 14:01:43 -07003839void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3840 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003841 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003842 Thread* self = Thread::Current();
3843 StackHandleScope<2> hs(self);
3844 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3845 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3846 const DexFile* dex_file = dex_cache->GetDexFile();
3847 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3848 if (kIsDebugBuild) {
3849 DexCacheData old_data;
3850 {
3851 ReaderMutexLock mu(self, *Locks::dex_lock_);
3852 old_data = FindDexCacheDataLocked(*dex_file);
3853 }
3854 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3855 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3856 << "been registered on dex file " << dex_file->GetLocation();
3857 }
3858 ClassTable* table;
3859 {
3860 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3861 table = InsertClassTableForClassLoader(h_class_loader.Get());
3862 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003863 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3864 // a thread holding the dex lock and blocking on a condition variable regarding
3865 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003866 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003867 WriterMutexLock mu(self, *Locks::dex_lock_);
3868 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3869 table->InsertStrongRoot(h_dex_cache.Get());
3870 if (h_class_loader.Get() != nullptr) {
3871 // Since we added a strong root to the class table, do the write barrier as required for
3872 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003873 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003874 }
3875}
3876
Vladimir Markocd556b02017-02-03 11:47:34 +00003877ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3878 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003879 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003880 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003881 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003882 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003883 old_data = FindDexCacheDataLocked(dex_file);
3884 }
3885 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3886 if (old_dex_cache != nullptr) {
3887 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003888 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003889 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003890 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3891 DCHECK(linear_alloc != nullptr);
3892 ClassTable* table;
3893 {
3894 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3895 table = InsertClassTableForClassLoader(class_loader);
3896 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003897 // Don't alloc while holding the lock, since allocation may need to
3898 // suspend all threads and another thread may need the dex_lock_ to
3899 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003900 StackHandleScope<3> hs(self);
3901 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003902 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003903 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3904 self,
3905 dex_file)));
3906 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003907 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003908 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3909 // a thread holding the dex lock and blocking on a condition variable regarding
3910 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003911 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003912 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003913 old_data = FindDexCacheDataLocked(dex_file);
3914 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003915 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003916 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3917 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3918 // that the arrays are null.
3919 mirror::DexCache::InitializeDexCache(self,
3920 h_dex_cache.Get(),
3921 h_location.Get(),
3922 &dex_file,
3923 linear_alloc,
3924 image_pointer_size_);
3925 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003926 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003927 }
3928 if (old_dex_cache != nullptr) {
3929 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3930 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003931 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003932 self->ClearException();
3933 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3934 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3935 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003936 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003937 self->AssertPendingOOMException();
3938 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003939 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003940 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003941 if (h_class_loader.Get() != nullptr) {
3942 // Since we added a strong root to the class table, do the write barrier as required for
3943 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003944 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003945 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003946 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003947}
3948
Vladimir Markocd556b02017-02-03 11:47:34 +00003949bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003950 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003951 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003952}
3953
Vladimir Markocd556b02017-02-03 11:47:34 +00003954ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3955 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003956 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3957 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003958 if (dex_cache != nullptr) {
3959 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003960 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003961 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003962 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003963 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003964 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003965 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003966 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003967 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3968 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003969 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003970}
3971
Vladimir Markocd556b02017-02-03 11:47:34 +00003972ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3973 const DexFile* dex_file = dex_cache->GetDexFile();
3974 DCHECK(dex_file != nullptr);
3975 ReaderMutexLock mu(self, *Locks::dex_lock_);
3976 // Search assuming unique-ness of dex file.
3977 for (const DexCacheData& data : dex_caches_) {
3978 // Avoid decoding (and read barriers) other unrelated dex caches.
3979 if (data.dex_file == dex_file) {
3980 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3981 if (registered_dex_cache != nullptr) {
3982 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3983 return data.class_table;
3984 }
3985 }
3986 }
3987 return nullptr;
3988}
3989
3990ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3991 // Search assuming unique-ness of dex file.
3992 for (const DexCacheData& data : dex_caches_) {
3993 // Avoid decoding (and read barriers) other unrelated dex caches.
3994 if (data.dex_file == &dex_file) {
3995 return data;
3996 }
3997 }
3998 return DexCacheData();
3999}
4000
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004001ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004002 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004003 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01004004 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004005 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004006 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004007 }
Ian Rogers1f539342012-10-03 21:09:42 -07004008 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004009 StackHandleScope<1> hs(self);
4010 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004011 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004012 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
4013 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004014 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07004015 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004016 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004017 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004018 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4019 h_class.Get(),
4020 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004021 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004022 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004023}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004024
Vladimir Marko02610552018-06-04 14:38:00 +01004025inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4026 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4027}
4028
Brian Carlstrombe977852011-07-19 14:54:54 -07004029// Create an array class (i.e. the class object for the array, not the
4030// array itself). "descriptor" looks like "[C" or "[[[[B" or
4031// "[Ljava/lang/String;".
4032//
4033// If "descriptor" refers to an array of primitives, look up the
4034// primitive type's internally-generated class object.
4035//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004036// "class_loader" is the class loader of the class that's referring to
4037// us. It's used to ensure that we're looking for the element type in
4038// the right context. It does NOT become the class loader for the
4039// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004040//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004041// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004042ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4043 const char* descriptor,
4044 size_t hash,
4045 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004046 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004047 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004048 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004049
4050 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4051 // code to be executed. We put it up here so we can avoid all the allocations associated with
4052 // creating the class. This can happen with (eg) jit threads.
4053 if (!self->CanLoadClasses()) {
4054 // Make sure we don't try to load anything, potentially causing an infinite loop.
4055 ObjPtr<mirror::Throwable> pre_allocated =
4056 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4057 self->SetException(pre_allocated);
4058 return nullptr;
4059 }
4060
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004061 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4062 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004063 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004064 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004065 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004066 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4067 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004068 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004069 DCHECK(self->IsExceptionPending());
4070 return nullptr;
4071 } else {
4072 self->ClearException();
4073 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004074 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004075 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4076 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4077 return nullptr;
4078 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004079 // See if the component type is already loaded. Array classes are
4080 // always associated with the class loader of their underlying
4081 // element type -- an array of Strings goes with the loader for
4082 // java/lang/String -- so we need to look for it there. (The
4083 // caller should have checked for the existence of the class
4084 // before calling here, but they did so with *their* class loader,
4085 // not the component type's loader.)
4086 //
4087 // If we find it, the caller adds "loader" to the class' initiating
4088 // loader list, which should prevent us from going through this again.
4089 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004090 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004091 // are the same, because our caller (FindClass) just did the
4092 // lookup. (Even if we get this wrong we still have correct behavior,
4093 // because we effectively do this lookup again when we add the new
4094 // class to the hash table --- necessary because of possible races with
4095 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004096 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004097 ObjPtr<mirror::Class> new_class =
4098 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004099 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004100 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004101 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004102 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004103
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004104 // Fill out the fields in the Class.
4105 //
4106 // It is possible to execute some methods against arrays, because
4107 // all arrays are subclasses of java_lang_Object_, so we need to set
4108 // up a vtable. We can just point at the one in java_lang_Object_.
4109 //
4110 // Array classes are simple enough that we don't need to do a full
4111 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004112 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004113 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004114 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004115 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004116 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004117 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004118 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4119 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4120 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004121 } else if (strcmp(descriptor, "[Z") == 0) {
4122 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4123 } else if (strcmp(descriptor, "[B") == 0) {
4124 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4125 } else if (strcmp(descriptor, "[C") == 0) {
4126 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4127 } else if (strcmp(descriptor, "[S") == 0) {
4128 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004129 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004130 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004131 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004132 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004133 } else if (strcmp(descriptor, "[F") == 0) {
4134 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4135 } else if (strcmp(descriptor, "[D") == 0) {
4136 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004137 }
4138 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004139 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004140 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004141 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004142 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004143 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004144 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004145 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004146 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004147 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004148 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004149 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004150 new_class->SetSuperClass(java_lang_Object);
4151 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004152 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004153 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004154 if (component_type->IsPrimitive()) {
4155 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4156 } else {
4157 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4158 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004159 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004160 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4161 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4162 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004163 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004164 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004165 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004166 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004167
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004168 // All arrays have java/lang/Cloneable and java/io/Serializable as
4169 // interfaces. We need to set that up here, so that stuff like
4170 // "instanceof" works right.
4171 //
4172 // Note: The GC could run during the call to FindSystemClass,
4173 // so we need to make sure the class object is GC-valid while we're in
4174 // there. Do this by clearing the interface list so the GC will just
4175 // think that the entries are null.
4176
4177
4178 // Use the single, global copies of "interfaces" and "iftable"
4179 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004180 {
Vladimir Marko02610552018-06-04 14:38:00 +01004181 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004182 CHECK(array_iftable != nullptr);
4183 new_class->SetIfTable(array_iftable);
4184 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004185
Elliott Hughes00626c22013-06-14 15:04:14 -07004186 // Inherit access flags from the component type.
4187 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4188 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4189 access_flags &= kAccJavaFlagsMask;
4190 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004191 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004192 access_flags |= kAccAbstract | kAccFinal;
4193 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004194 // Arrays are access-checks-clean and preverified.
4195 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004196
4197 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004198
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004199 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004200 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004201 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4202 // duplicate events in case of races. Array classes don't really follow dedicated
4203 // load and prepare, anyways.
4204 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4205 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4206
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004207 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004208 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004209 }
4210 // Another thread must have loaded the class after we
4211 // started but before we finished. Abandon what we've
4212 // done.
4213 //
4214 // (Yes, this happens.)
4215
Vladimir Markobcf17522018-06-01 13:14:32 +01004216 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004217}
4218
Vladimir Marko9186b182018-11-06 14:55:54 +00004219ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4220 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004221 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004222 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4223 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4224 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4225 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4226 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4227 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4228 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4229 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4230 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004231 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004232 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004233 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004234 return GetClassRoot(class_root, this);
4235}
4236
4237ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4238 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4239 if (UNLIKELY(result == nullptr)) {
4240 std::string printable_type(PrintableChar(type));
4241 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4242 }
4243 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004244}
4245
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004246ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4247 ObjPtr<mirror::Class> klass,
4248 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004249 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004250 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004251 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004252 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004253 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004254 source += " from ";
4255 source += dex_cache->GetLocation()->ToModifiedUtf8();
4256 }
4257 LOG(INFO) << "Loaded class " << descriptor << source;
4258 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004259 {
4260 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004261 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004262 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004263 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004264 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004265 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004266 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004267 VerifyObject(klass);
4268 class_table->InsertWithHash(klass, hash);
4269 if (class_loader != nullptr) {
4270 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004271 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004272 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004273 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004274 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004275 }
4276 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004277 if (kIsDebugBuild) {
4278 // Test that copied methods correctly can find their holder.
4279 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4280 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4281 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004282 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004283 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004284}
4285
Vladimir Marko1998cd02017-01-13 13:02:58 +00004286void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004287 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4288 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4289 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4290 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004291 }
4292}
4293
Alex Lighte64300b2015-12-15 15:02:47 -08004294// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004295void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004296 LengthPrefixedArray<ArtMethod>* new_methods) {
4297 klass->SetMethodsPtrUnchecked(new_methods,
4298 klass->NumDirectMethods(),
4299 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004300 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004301 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004302}
4303
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004304ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4305 const char* descriptor,
4306 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004307 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4308}
4309
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004310ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4311 const char* descriptor,
4312 size_t hash,
4313 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004314 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4315 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4316 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004317 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004318 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004319 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004320 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004321 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004322 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004323}
4324
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004325class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4326 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004327 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004328
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004329 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004330 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004331 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004332 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004333 if (class_table != nullptr) {
4334 class_table->FreezeSnapshot();
4335 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004336 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004337};
4338
4339void ClassLinker::MoveClassTableToPreZygote() {
4340 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004341 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004342 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004343 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004344}
4345
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004346// Look up classes by hash and descriptor and put all matching ones in the result array.
4347class LookupClassesVisitor : public ClassLoaderVisitor {
4348 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004349 LookupClassesVisitor(const char* descriptor,
4350 size_t hash,
4351 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004352 : descriptor_(descriptor),
4353 hash_(hash),
4354 result_(result) {}
4355
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004356 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004357 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004358 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004359 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004360 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4361 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004362 result_->push_back(klass);
4363 }
4364 }
4365
4366 private:
4367 const char* const descriptor_;
4368 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004369 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004370};
4371
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004372void ClassLinker::LookupClasses(const char* descriptor,
4373 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004374 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004375 Thread* const self = Thread::Current();
4376 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004377 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004378 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004379 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004380 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004381 result.push_back(klass);
4382 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004383 LookupClassesVisitor visitor(descriptor, hash, &result);
4384 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004385}
4386
Alex Lightf1f10492015-10-07 16:08:36 -07004387bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4388 Handle<mirror::Class> klass,
4389 Handle<mirror::Class> supertype) {
4390 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004391 DCHECK(klass != nullptr);
4392 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004393
Alex Lightf1f10492015-10-07 16:08:36 -07004394 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4395 VerifyClass(self, supertype);
4396 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004397
4398 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4399 // The supertype is either verified, or we soft failed at AOT time.
4400 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004401 return true;
4402 }
4403 // If we got this far then we have a hard failure.
4404 std::string error_msg =
4405 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004406 klass->PrettyDescriptor().c_str(),
4407 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004408 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004409 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004410 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004411 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004412 // Set during VerifyClass call (if at all).
4413 self->ClearException();
4414 }
4415 // Change into a verify error.
4416 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004417 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004418 self->GetException()->SetCause(cause.Get());
4419 }
4420 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4421 if (Runtime::Current()->IsAotCompiler()) {
4422 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4423 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004424 // Need to grab the lock to change status.
4425 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004426 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004427 return false;
4428}
4429
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004430verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004431 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004432 {
4433 // TODO: assert that the monitor on the Class is held
4434 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004435
Andreas Gampe884f3b82016-03-30 19:52:58 -07004436 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004437 ClassStatus old_status = klass->GetStatus();
4438 while (old_status == ClassStatus::kVerifying ||
4439 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004440 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004441 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4442 // case we may see the same status again. b/62912904. This is why the check is
4443 // greater or equal.
4444 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004445 << "Class '" << klass->PrettyClass()
4446 << "' performed an illegal verification state transition from " << old_status
4447 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004448 old_status = klass->GetStatus();
4449 }
jeffhao98eacac2011-09-14 16:11:53 -07004450
Andreas Gampe884f3b82016-03-30 19:52:58 -07004451 // The class might already be erroneous, for example at compile time if we attempted to verify
4452 // this class as a parent to another.
4453 if (klass->IsErroneous()) {
4454 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004455 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004456 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004457
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004458 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004459 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004460 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004461 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004462 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004463
4464 // For AOT, don't attempt to re-verify if we have already found we should
4465 // verify at runtime.
4466 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004467 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004468 }
jeffhao98eacac2011-09-14 16:11:53 -07004469
Vladimir Marko2c64a832018-01-04 11:31:56 +00004470 if (klass->GetStatus() == ClassStatus::kResolved) {
4471 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004472 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004473 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004474 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004475 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004476 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004477 }
4478
4479 // Skip verification if disabled.
4480 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004481 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004482 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004483 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004484 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004485 }
4486
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004487 VLOG(class_linker) << "Beginning verification for class: "
4488 << klass->PrettyDescriptor()
4489 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4490
Ian Rogers9ffb0392012-09-10 11:56:50 -07004491 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004492 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004493 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4494 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004495 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004496 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004497 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004498 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004499
Alex Lightf1f10492015-10-07 16:08:36 -07004500 // Verify all default super-interfaces.
4501 //
4502 // (1) Don't bother if the superclass has already had a soft verification failure.
4503 //
4504 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4505 // recursive initialization by themselves. This is because when an interface is initialized
4506 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4507 // but choose not to for an optimization. If the interfaces is being verified due to a class
4508 // initialization (which would need all the default interfaces to be verified) the class code
4509 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004510 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004511 && !klass->IsInterface()) { // See (2)
4512 int32_t iftable_count = klass->GetIfTableCount();
4513 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4514 // Loop through all interfaces this class has defined. It doesn't matter the order.
4515 for (int32_t i = 0; i < iftable_count; i++) {
4516 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004517 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004518 // We only care if we have default interfaces and can skip if we are already verified...
4519 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4520 continue;
4521 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4522 // We had a hard failure while verifying this interface. Just return immediately.
4523 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004524 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004525 } else if (UNLIKELY(!iface->IsVerified())) {
4526 // We softly failed to verify the iface. Stop checking and clean up.
4527 // Put the iface into the supertype handle so we know what caused us to fail.
4528 supertype.Assign(iface.Get());
4529 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004530 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004531 }
4532 }
4533
Alex Lightf1f10492015-10-07 16:08:36 -07004534 // At this point if verification failed, then supertype is the "first" supertype that failed
4535 // verification (without a specific order). If verification succeeded, then supertype is either
4536 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004537 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004538 supertype.Get() == klass->GetSuperClass() ||
4539 !supertype->IsVerified());
4540
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004541 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004542 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004543 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004544 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004545
4546 VLOG(class_linker) << "Class preverified status for class "
4547 << klass->PrettyDescriptor()
4548 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4549 << ": "
4550 << preverified;
4551
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004552 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4553 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004554 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4555 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004556
Ian Rogers62d6c772013-02-27 08:32:07 -08004557 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004558 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004559 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004560 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004561 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004562
4563 // Verification is done, grab the lock again.
4564 ObjectLock<mirror::Class> lock(self, klass);
4565
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004566 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4567 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004568 VLOG(class_linker) << "Soft verification failure in class "
4569 << klass->PrettyDescriptor()
4570 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4571 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004572 }
Ian Rogers1f539342012-10-03 21:09:42 -07004573 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004574 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004575 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004576 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004577 // Even though there were no verifier failures we need to respect whether the super-class and
4578 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004579 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004580 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004581 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004582 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4583 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004584 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004585 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004586 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004587 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004588 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004589 // Soft failures at compile time should be retried at runtime. Soft
4590 // failures at runtime will be handled by slow paths in the generated
4591 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004592 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004593 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004594 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004595 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004596 // As this is a fake verified status, make sure the methods are _not_ marked
4597 // kAccSkipAccessChecks later.
4598 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004599 }
4600 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004601 } else {
David Sehr709b0702016-10-13 09:12:37 -07004602 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004603 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4604 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004605 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004606 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004607 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004608 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004609 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004610 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004611 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004612 // method.
4613 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004614 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004615 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004616
4617 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4618 // Never skip access checks if the verification soft fail is forced.
4619 // Mark the class as having a verification attempt to avoid re-running the verifier.
4620 klass->SetVerificationAttempted();
4621 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004622 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004623 }
Andreas Gampe48498592014-09-10 19:48:05 -07004624 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004625 // Done verifying. Notify the compiler about the verification status, in case the class
4626 // was verified implicitly (eg super class of a compiled class).
4627 if (Runtime::Current()->IsAotCompiler()) {
4628 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4629 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4630 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004631 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004632}
4633
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004634verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4635 Handle<mirror::Class> klass,
4636 verifier::HardFailLogMode log_level,
4637 std::string* error_msg) {
4638 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004639 return verifier::ClassVerifier::VerifyClass(self,
4640 klass.Get(),
4641 runtime->GetCompilerCallbacks(),
4642 runtime->IsAotCompiler(),
4643 log_level,
4644 Runtime::Current()->GetTargetSdkVersion(),
4645 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004646}
4647
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004648bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004649 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004650 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004651 // If we're compiling, we can only verify the class using the oat file if
4652 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004653 // the compilation unit (app - dependencies). We will let the compiler callback
4654 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004655 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004656 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004657 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004658 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004659 return false;
4660 }
4661 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004662 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004663 return false;
4664 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004665 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004666
Andreas Gampeb40d3612018-06-26 15:49:42 -07004667 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004668 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004669 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004670 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4671 // For boot classpath classes in the case we're not using a default boot image:
4672 // we don't have the infrastructure yet to query verification data on individual
4673 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4674 // verified. This should be taken into account when measuring boot time and app
4675 // startup compare to the (current) production system where both:
4676 // 1) updatable boot classpath classes, and
4677 // 2) classes in /system referencing updatable classes
4678 // will be verified at runtime.
4679 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4680 oat_file_class_status = ClassStatus::kVerified;
4681 return true;
4682 }
4683 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004684 return false;
4685 }
4686
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004687 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004688 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004689 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004690 return true;
4691 }
4692 // If we only verified a subset of the classes at compile time, we can end up with classes that
4693 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004694 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004695 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004696 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004697 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004698 // Compile time verification failed with a soft error. Compile time verification can fail
4699 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004700 // class ... {
4701 // Foo x;
4702 // .... () {
4703 // if (...) {
4704 // v1 gets assigned a type of resolved class Foo
4705 // } else {
4706 // v1 gets assigned a type of unresolved class Bar
4707 // }
4708 // iput x = v1
4709 // } }
4710 // when we merge v1 following the if-the-else it results in Conflict
4711 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4712 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4713 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4714 // at compile time).
4715 return false;
4716 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004717 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004718 // Compile time verification failed with a hard error. This is caused by invalid instructions
4719 // in the class. These errors are unrecoverable.
4720 return false;
4721 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004722 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004723 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4724 // not loading the class.
4725 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4726 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004727 return false;
4728 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004729 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004730 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004731 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004732 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004733 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004734}
4735
Alex Light5a559862016-01-29 12:24:48 -08004736void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004737 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004738 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004739 }
4740}
4741
Alex Light5a559862016-01-29 12:24:48 -08004742void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004743 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004744 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004745 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004746 return; // native or abstract method
4747 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004748 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004749 return; // nothing to process
4750 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004751 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004752 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004753 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4754 CatchHandlerIterator iterator(handlers_ptr);
4755 for (; iterator.HasNext(); iterator.Next()) {
4756 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4757 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004758 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004759 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004760 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004761 DCHECK(Thread::Current()->IsExceptionPending());
4762 Thread::Current()->ClearException();
4763 }
4764 }
4765 }
4766 handlers_ptr = iterator.EndDataPointer();
4767 }
4768}
4769
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004770ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4771 jstring name,
4772 jobjectArray interfaces,
4773 jobject loader,
4774 jobjectArray methods,
4775 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004776 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004777
4778 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4779 // code to be executed. We put it up here so we can avoid all the allocations associated with
4780 // creating the class. This can happen with (eg) jit-threads.
4781 if (!self->CanLoadClasses()) {
4782 // Make sure we don't try to load anything, potentially causing an infinite loop.
4783 ObjPtr<mirror::Throwable> pre_allocated =
4784 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4785 self->SetException(pre_allocated);
4786 return nullptr;
4787 }
4788
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004789 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004790 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004791 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004792 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004793 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004794 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004795 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004796 DCHECK(temp_klass->GetClass() != nullptr);
4797 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004798 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4799 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004800 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4801 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4802 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4803 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004804 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004805 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004806 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004807 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004808 std::string storage;
4809 const char* descriptor = temp_klass->GetDescriptor(&storage);
4810 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004811
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004812 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004813 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004814
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004815 // Insert the class before loading the fields as the field roots
4816 // (ArtField::declaring_class_) are only visited from the class
4817 // table. There can't be any suspend points between inserting the
4818 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004819 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004820 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004821
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004822 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004823 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004824 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004825 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004826
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004827 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4828 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004829 ArtField& interfaces_sfield = sfields->At(0);
4830 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004831 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004832 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004833
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004834 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004835 ArtField& throws_sfield = sfields->At(1);
4836 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004837 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004838 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004839
Ian Rogers466bb252011-10-14 03:29:56 -07004840 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004841 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004842
Alex Lighte64300b2015-12-15 15:02:47 -08004843 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004844 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004845 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004846 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004847 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004848
4849 // Create the methods array.
4850 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4851 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004852 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4853 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004854 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004855 self->AssertPendingOOMException();
4856 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004857 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004858 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004859
4860 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004861 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004862
4863 // Create virtual method using specified prototypes.
4864 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004865 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004866 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004867 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004868 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004869 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4870 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004871 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004872
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004873 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004874 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004875 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004876 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004877 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004878
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004879 // At this point the class is loaded. Publish a ClassLoad event.
4880 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4881 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4882
4883 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004884 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004885 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004886 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004887 // Link the fields and virtual methods, creating vtable and iftables.
4888 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004889 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004890 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004891 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004892 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004893 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004894 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004895 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004896 CHECK(temp_klass->IsRetired());
4897 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004898
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004899 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004900 interfaces_sfield.SetObject<false>(
4901 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004902 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004903 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4904 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004905 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004906 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004907
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004908 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4909
Vladimir Marko305c38b2018-02-14 11:50:07 +00004910 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4911 // See also ClassLinker::EnsureInitialized().
4912 if (kBitstringSubtypeCheckEnabled) {
4913 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4914 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4915 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4916 }
4917
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004918 {
4919 // Lock on klass is released. Lock new class object.
4920 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004921 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004922 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004923 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004924
4925 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004926 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004927 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004928 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4929
Ian Rogersc2b44472011-12-14 21:17:17 -08004930 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004931 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4932 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004933 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004934 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004935
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004936 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004937 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004938 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004939 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004940 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004941
4942 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004943 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004944 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004945
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004946 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004947 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004948 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004949 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004950 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004951 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004952}
4953
Mathieu Chartiere401d142015-04-22 13:56:20 -07004954void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4955 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004956 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4957 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004958
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004959 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4960 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004961 ArtMethod* proxy_constructor =
4962 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004963 DCHECK(proxy_constructor != nullptr)
4964 << "Could not find <init> method in java.lang.reflect.Proxy";
4965
Jeff Haodb8a6642014-08-14 17:18:52 -07004966 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4967 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004968 DCHECK(out != nullptr);
4969 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004970 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004971 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004972 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004973 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4974 kAccPublic |
4975 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004976 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004977
4978 // Set the original constructor method.
4979 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004980}
4981
Mathieu Chartiere401d142015-04-22 13:56:20 -07004982void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004983 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004984 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4985 CHECK_STREQ(np->GetName(), "<init>");
4986 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004987 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004988}
4989
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004990void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004991 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004992 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004993 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004994 DCHECK(out != nullptr);
4995 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004996
Alex Lighte9dd04f2016-03-16 16:09:45 -07004997 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004998 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004999 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5000 // preference to the invocation handler.
5001 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5002 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005003 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5004 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005005 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5006
5007 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5008 // method they copy might (if it's a default method).
5009 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005010
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005011 // Set the original interface method.
5012 out->SetDataPtrSize(prototype, image_pointer_size_);
5013
Ian Rogers466bb252011-10-14 03:29:56 -07005014 // At runtime the method looks like a reference and argument saving method, clone the code
5015 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005016 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005017}
Jesse Wilson95caa792011-10-12 18:14:17 -04005018
Mathieu Chartiere401d142015-04-22 13:56:20 -07005019void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005020 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005021 CHECK(!prototype->IsFinal());
5022 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005023 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005024
5025 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5026 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005027 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005028 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005029}
5030
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005031bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005032 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005033 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005034 return true;
5035 }
5036 if (!can_init_statics) {
5037 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005038 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005039 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005040 return false;
5041 }
5042 // Check if there are encoded static values needing initialization.
5043 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005044 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005045 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005046 if (dex_class_def->static_values_off_ != 0) {
5047 return false;
5048 }
5049 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005050 // If we are a class we need to initialize all interfaces with default methods when we are
5051 // initialized. Check all of them.
5052 if (!klass->IsInterface()) {
5053 size_t num_interfaces = klass->GetIfTableCount();
5054 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005055 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005056 if (iface->HasDefaultMethods() &&
5057 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5058 return false;
5059 }
5060 }
5061 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005062 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005063 if (klass->IsInterface() || !klass->HasSuperClass()) {
5064 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005065 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005066 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005067 if (!can_init_parents && !super_class->IsInitialized()) {
5068 return false;
5069 }
5070 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005071}
5072
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005073bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5074 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005075 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5076
5077 // Are we already initialized and therefore done?
5078 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5079 // an initialized class will never change its state.
5080 if (klass->IsInitialized()) {
5081 return true;
5082 }
5083
5084 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005085 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005086 return false;
5087 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005088
Ian Rogers7b078e82014-09-10 14:44:24 -07005089 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005090 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005091 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005092 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005093
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005094 // Re-check under the lock in case another thread initialized ahead of us.
5095 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005096 return true;
5097 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005098
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005099 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005100 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005101 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005102 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005103 return false;
5104 }
5105
Vladimir Marko72ab6842017-01-20 19:32:50 +00005106 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5107 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005108
5109 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005110 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005111 if (!klass->IsVerified()) {
5112 // We failed to verify, expect either the klass to be erroneous or verification failed at
5113 // compile time.
5114 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005115 // The class is erroneous. This may be a verifier error, or another thread attempted
5116 // verification and/or initialization and failed. We can distinguish those cases by
5117 // whether an exception is already pending.
5118 if (self->IsExceptionPending()) {
5119 // Check that it's a VerifyError.
5120 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005121 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005122 } else {
5123 // Check that another thread attempted initialization.
5124 DCHECK_NE(0, klass->GetClinitThreadId());
5125 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5126 // Need to rethrow the previous failure now.
5127 ThrowEarlierClassFailure(klass.Get(), true);
5128 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005129 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005130 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005131 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005132 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005133 self->AssertNoPendingException();
5134 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005135 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005136 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005137 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005138 } else {
5139 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005140 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005141
5142 // A separate thread could have moved us all the way to initialized. A "simple" example
5143 // involves a subclass of the current class being initialized at the same time (which
5144 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005145 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005146 if (klass->IsInitialized()) {
5147 return true;
5148 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005149 }
5150
Vladimir Marko2c64a832018-01-04 11:31:56 +00005151 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005152 // initializing higher up the stack or another thread has beat us
5153 // to initializing and we need to wait. Either way, this
5154 // invocation of InitializeClass will not be responsible for
5155 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005156 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005157 // Could have got an exception during verification.
5158 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005159 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005160 return false;
5161 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005162 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005163 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005164 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005165 return true;
5166 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005167 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005168 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005169 }
5170
Jeff Haoe2e40342017-07-19 10:45:18 -07005171 // Try to get the oat class's status for this class if the oat file is present. The compiler
5172 // tries to validate superclass descriptors, and writes the result into the oat file.
5173 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5174 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5175 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005176 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005177 const Runtime* runtime = Runtime::Current();
5178 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5179 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5180 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005181 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005182 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005183 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005184 return false;
5185 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005186 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005187
Vladimir Marko2c64a832018-01-04 11:31:56 +00005188 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005189 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005190
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005191 // From here out other threads may observe that we're initializing and so changes of state
5192 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005193 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005194 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005195
5196 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005197 }
5198
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005199 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005200 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005201 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005202 if (!super_class->IsInitialized()) {
5203 CHECK(!super_class->IsInterface());
5204 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005205 StackHandleScope<1> hs(self);
5206 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005207 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005208 if (!super_initialized) {
5209 // The super class was verified ahead of entering initializing, we should only be here if
5210 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005211 // For the case of aot compiler, the super class might also be initializing but we don't
5212 // want to process circular dependencies in pre-compile.
5213 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005214 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005215 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005216 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005217 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005218 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005219 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005220 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005221 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005222 return false;
5223 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005224 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005225 }
5226
Alex Lighteb7c1442015-08-31 13:17:42 -07005227 if (!klass->IsInterface()) {
5228 // Initialize interfaces with default methods for the JLS.
5229 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005230 // Only setup the (expensive) handle scope if we actually need to.
5231 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005232 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005233 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5234 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005235 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005236 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005237 CHECK(handle_scope_iface->IsInterface());
5238 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5239 // We have already done this for this interface. Skip it.
5240 continue;
5241 }
5242 // We cannot just call initialize class directly because we need to ensure that ALL
5243 // interfaces with default methods are initialized. Non-default interface initialization
5244 // will not affect other non-default super-interfaces.
5245 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5246 handle_scope_iface,
5247 can_init_statics,
5248 can_init_parents);
5249 if (!iface_initialized) {
5250 ObjectLock<mirror::Class> lock(self, klass);
5251 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005252 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005253 return false;
5254 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005255 }
5256 }
5257 }
5258
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005259 const size_t num_static_fields = klass->NumStaticFields();
5260 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005261 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005262 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005263 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005264 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005265 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005266
5267 // Eagerly fill in static fields so that the we don't have to do as many expensive
5268 // Class::FindStaticField in ResolveField.
5269 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005270 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005271 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005272 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005273 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005274 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005275 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5276 field,
5277 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5278 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005279 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005280 } else {
5281 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005282 }
5283 }
5284
Vladimir Markoe11dd502017-12-08 14:09:45 +00005285 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5286 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005287 this,
5288 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005289 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005290
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005291 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005292 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005293 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005294 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5295 if (!value_it.HasNext()) {
5296 break;
5297 }
5298 ArtField* art_field = ResolveField(field.GetIndex(),
5299 dex_cache,
5300 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005301 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005302 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005303 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005304 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005305 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005306 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005307 if (self->IsExceptionPending()) {
5308 break;
5309 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005310 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005311 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005312 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005313 }
5314 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005315
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005316
Mathieu Chartierda595be2016-08-10 13:57:39 -07005317 if (!self->IsExceptionPending()) {
5318 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5319 if (clinit != nullptr) {
5320 CHECK(can_init_statics);
5321 JValue result;
5322 clinit->Invoke(self, nullptr, 0, &result, "V");
5323 }
5324 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005325 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005326 uint64_t t1 = NanoTime();
5327
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005328 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005329 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005330 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005331
5332 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005333 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005334 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005335 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005336 } else if (Runtime::Current()->IsTransactionAborted()) {
5337 // The exception thrown when the transaction aborted has been caught and cleared
5338 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005339 VLOG(compiler) << "Return from class initializer of "
5340 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005341 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005342 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005343 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005344 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005345 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005346 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5347 RuntimeStats* thread_stats = self->GetStats();
5348 ++global_stats->class_init_count;
5349 ++thread_stats->class_init_count;
5350 global_stats->class_init_time_ns += (t1 - t0);
5351 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005352 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005353 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005354 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005355 std::string temp;
5356 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005357 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005358 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005359 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005360 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005361 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005362 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005363 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005364}
5365
Alex Lighteb7c1442015-08-31 13:17:42 -07005366// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5367// and perform the initialization only on those interfaces that contain default methods.
5368bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5369 Handle<mirror::Class> iface,
5370 bool can_init_statics,
5371 bool can_init_parents) {
5372 CHECK(iface->IsInterface());
5373 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005374 // Only create the (expensive) handle scope if we need it.
5375 if (UNLIKELY(num_direct_ifaces > 0)) {
5376 StackHandleScope<1> hs(self);
5377 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5378 // First we initialize all of iface's super-interfaces recursively.
5379 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005380 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005381 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005382 if (!super_iface->HasBeenRecursivelyInitialized()) {
5383 // Recursive step
5384 handle_super_iface.Assign(super_iface);
5385 if (!InitializeDefaultInterfaceRecursive(self,
5386 handle_super_iface,
5387 can_init_statics,
5388 can_init_parents)) {
5389 return false;
5390 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005391 }
5392 }
5393 }
5394
5395 bool result = true;
5396 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5397 // initialize if we don't have default methods.
5398 if (iface->HasDefaultMethods()) {
5399 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5400 }
5401
5402 // Mark that this interface has undergone recursive default interface initialization so we know we
5403 // can skip it on any later class initializations. We do this even if we are not a default
5404 // interface since we can still avoid the traversal. This is purely a performance optimization.
5405 if (result) {
5406 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005407 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5408 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5409 // initialization is a performance optimization (to avoid another idempotent visit
5410 // for other implementing classes/interfaces), and can be revisited later.
5411 ObjectTryLock<mirror::Class> lock(self, iface);
5412 if (lock.Acquired()) {
5413 iface->SetRecursivelyInitialized();
5414 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005415 }
5416 return result;
5417}
5418
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005419bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5420 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005421 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005422 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005423 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005424 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005425 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005426 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005427
5428 // When we wake up, repeat the test for init-in-progress. If
5429 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005430 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005431 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005432 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005433 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005434 return false;
5435 }
5436 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005437 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005438 continue;
5439 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005440 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005441 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005442 // Compile time initialization failed.
5443 return false;
5444 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005445 if (klass->IsErroneous()) {
5446 // The caller wants an exception, but it was thrown in a
5447 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005448 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005449 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005450 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005451 return false;
5452 }
5453 if (klass->IsInitialized()) {
5454 return true;
5455 }
David Sehr709b0702016-10-13 09:12:37 -07005456 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005457 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005458 }
Ian Rogers07140832014-09-30 15:43:59 -07005459 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005460}
5461
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005462static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5463 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005464 ArtMethod* method,
5465 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005466 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005467 DCHECK(Thread::Current()->IsExceptionPending());
5468 DCHECK(!m->IsProxyMethod());
5469 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005470 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5471 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005472 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005473 std::string return_type = dex_file->PrettyType(return_type_idx);
5474 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005475 ThrowWrappedLinkageError(klass.Get(),
5476 "While checking class %s method %s signature against %s %s: "
5477 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005478 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5479 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005480 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005481 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005482 return_type.c_str(), class_loader.c_str());
5483}
5484
5485static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5486 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005487 ArtMethod* method,
5488 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005489 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005490 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005491 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005492 DCHECK(Thread::Current()->IsExceptionPending());
5493 DCHECK(!m->IsProxyMethod());
5494 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005495 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5496 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005497 ThrowWrappedLinkageError(klass.Get(),
5498 "While checking class %s method %s signature against %s %s: "
5499 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005500 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5501 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005502 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005503 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005504 index, arg_type.c_str(), class_loader.c_str());
5505}
5506
5507static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5508 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005509 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005510 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005511 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005512 ThrowLinkageError(klass.Get(),
5513 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005514 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5515 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005516 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005517 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005518 error_msg.c_str());
5519}
5520
Ian Rogersb5fb2072014-12-02 17:22:02 -08005521static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005522 Handle<mirror::Class> klass,
5523 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005524 ArtMethod* method1,
5525 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005526 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005527 {
5528 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005529 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005530 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005531 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005532 return false;
5533 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005534 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005535 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005536 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005537 return false;
5538 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005539 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005540 ThrowSignatureMismatch(klass, super_klass, method1,
5541 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005542 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005543 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005544 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005545 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005546 return false;
5547 }
5548 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005549 const dex::TypeList* types1 = method1->GetParameterTypeList();
5550 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005551 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005552 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005553 ThrowSignatureMismatch(klass, super_klass, method1,
5554 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005555 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005556 return false;
5557 }
5558 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005559 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005560 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 ThrowSignatureMismatch(klass, super_klass, method1,
5562 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005563 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005564 return false;
5565 }
5566 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005567 }
5568 uint32_t num_types = types1->Size();
5569 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005570 ThrowSignatureMismatch(klass, super_klass, method1,
5571 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005572 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005573 return false;
5574 }
5575 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005576 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005577 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005578 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005579 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005580 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005581 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005582 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005583 return false;
5584 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005585 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005586 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005587 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005588 if (UNLIKELY(other_param_type == nullptr)) {
5589 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005590 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005591 return false;
5592 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005593 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005594 ThrowSignatureMismatch(klass, super_klass, method1,
5595 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5596 i,
David Sehr709b0702016-10-13 09:12:37 -07005597 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005598 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005599 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005600 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005601 return false;
5602 }
5603 }
5604 return true;
5605}
5606
5607
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005608bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005609 if (klass->IsInterface()) {
5610 return true;
5611 }
Ian Rogers151f2212014-05-06 11:27:27 -07005612 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005613 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005614 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005615 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005616 if (klass->HasSuperClass() &&
5617 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005618 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005619 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005620 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5621 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5622 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005623 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5624 klass,
5625 super_klass,
5626 m,
5627 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005628 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005629 return false;
5630 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005631 }
5632 }
5633 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005634 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005635 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5636 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5637 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005638 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005639 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5640 j, image_pointer_size_);
5641 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5642 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005643 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5644 klass,
5645 super_klass,
5646 m,
5647 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005648 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005649 return false;
5650 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005651 }
5652 }
5653 }
5654 }
5655 return true;
5656}
5657
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005658bool ClassLinker::EnsureInitialized(Thread* self,
5659 Handle<mirror::Class> c,
5660 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005661 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005662 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005663
Mathieu Chartier524507a2014-08-27 15:28:28 -07005664 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005665 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005666 return true;
5667 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005668 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5669 //
5670 // Ensure the bitstring is initialized before any of the class initialization
5671 // logic occurs. Once a class initializer starts running, objects can
5672 // escape into the heap and use the subtype checking code.
5673 //
5674 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5675 // can be used as a source for the IsSubClass check, and that all ancestors
5676 // of the class are Assigned (can be used as a target for IsSubClass check)
5677 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005678 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005679 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005680 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005681 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5682 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005683 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005684 if (!success) {
5685 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005686 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005687 }
5688 } else {
5689 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005690 }
5691 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005692}
5693
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005694void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5695 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005696 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005697 for (ArtField& field : new_class->GetIFields()) {
5698 if (field.GetDeclaringClass() == temp_class) {
5699 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005700 }
5701 }
5702
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005703 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005704 for (ArtField& field : new_class->GetSFields()) {
5705 if (field.GetDeclaringClass() == temp_class) {
5706 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005707 }
5708 }
5709
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005710 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005711 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005712 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005713 if (method.GetDeclaringClass() == temp_class) {
5714 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005715 }
5716 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005717
5718 // Make sure the remembered set and mod-union tables know that we updated some of the native
5719 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005720 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005721}
5722
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005723void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005724 CHECK(class_loader->GetAllocator() == nullptr);
5725 CHECK(class_loader->GetClassTable() == nullptr);
5726 Thread* const self = Thread::Current();
5727 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005728 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005729 // Create and set the class table.
5730 data.class_table = new ClassTable;
5731 class_loader->SetClassTable(data.class_table);
5732 // Create and set the linear allocator.
5733 data.allocator = Runtime::Current()->CreateLinearAlloc();
5734 class_loader->SetAllocator(data.allocator);
5735 // Add to the list so that we know to free the data later.
5736 class_loaders_.push_back(data);
5737}
5738
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005739ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005740 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005741 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005742 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005743 ClassTable* class_table = class_loader->GetClassTable();
5744 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005745 RegisterClassLoader(class_loader);
5746 class_table = class_loader->GetClassTable();
5747 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005748 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005749 return class_table;
5750}
5751
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005752ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005753 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005754}
5755
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005756static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005757 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005758 while (klass->HasSuperClass()) {
5759 klass = klass->GetSuperClass();
5760 if (klass->ShouldHaveImt()) {
5761 return klass->GetImt(pointer_size);
5762 }
5763 }
5764 return nullptr;
5765}
5766
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005767bool ClassLinker::LinkClass(Thread* self,
5768 const char* descriptor,
5769 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005770 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005771 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005772 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005773
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005774 if (!LinkSuperClass(klass)) {
5775 return false;
5776 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005777 ArtMethod* imt_data[ImTable::kSize];
5778 // If there are any new conflicts compared to super class.
5779 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005780 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005781 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005782 return false;
5783 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005784 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005785 return false;
5786 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005787 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005788 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005789 return false;
5790 }
5791 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005792 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005793
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005794 ImTable* imt = nullptr;
5795 if (klass->ShouldHaveImt()) {
5796 // If there are any new conflicts compared to the super class we can not make a copy. There
5797 // can be cases where both will have a conflict method at the same slot without having the same
5798 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5799 // will possibly create a table that is incorrect for either of the classes.
5800 // Same IMT with new_conflict does not happen very often.
5801 if (!new_conflict) {
5802 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5803 if (super_imt != nullptr) {
5804 bool imt_equals = true;
5805 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5806 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5807 }
5808 if (imt_equals) {
5809 imt = super_imt;
5810 }
5811 }
5812 }
5813 if (imt == nullptr) {
5814 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5815 imt = reinterpret_cast<ImTable*>(
5816 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5817 if (imt == nullptr) {
5818 return false;
5819 }
5820 imt->Populate(imt_data, image_pointer_size_);
5821 }
5822 }
5823
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005824 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5825 // We don't need to retire this class as it has no embedded tables or it was created the
5826 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005827 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005828
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005829 if (klass->ShouldHaveEmbeddedVTable()) {
5830 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005831 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005832 if (klass->ShouldHaveImt()) {
5833 klass->SetImt(imt, image_pointer_size_);
5834 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005835
5836 // Update CHA info based on whether we override methods.
5837 // Have to do this before setting the class as resolved which allows
5838 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005839 if (cha_ != nullptr) {
5840 cha_->UpdateAfterLoadingOf(klass);
5841 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005842
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005843 // This will notify waiters on klass that saw the not yet resolved
5844 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005845 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005846 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005847 } else {
5848 CHECK(!klass->IsResolved());
5849 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005850 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005851 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005852 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5853 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5854 // may not see any references to the target space and clean the card for a class if another
5855 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005856 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005857 klass->SetSFieldsPtrUnchecked(nullptr);
5858 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005859 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005860 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005861 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005862 return false;
5863 }
5864
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005865 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5866 ObjectLock<mirror::Class> lock(self, h_new_class);
5867 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005868
5869 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005870 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005871 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005872 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005873 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005874 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005875 if (class_loader != nullptr) {
5876 // We updated the class in the class table, perform the write barrier so that the GC knows
5877 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005878 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005879 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005880 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005881 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005882 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5883 }
5884 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005885
Mingyao Yang063fc772016-08-02 11:02:54 -07005886 // Update CHA info based on whether we override methods.
5887 // Have to do this before setting the class as resolved which allows
5888 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005889 if (cha_ != nullptr) {
5890 cha_->UpdateAfterLoadingOf(h_new_class);
5891 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005892
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005893 // This will notify waiters on temp class that saw the not yet resolved class in the
5894 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005895 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005896
Vladimir Marko2c64a832018-01-04 11:31:56 +00005897 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005898 // This will notify waiters on new_class that saw the not yet resolved
5899 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005900 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005901 // Return the new class.
5902 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005903 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005904 return true;
5905}
5906
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005907bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005908 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005909 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005910 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5911 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005912 // Check that a class does not inherit from itself directly.
5913 //
5914 // TODO: This is a cheap check to detect the straightforward case
5915 // of a class extending itself (b/28685551), but we should do a
5916 // proper cycle detection on loaded classes, to detect all cases
5917 // of class circularity errors (b/28830038).
5918 if (super_class_idx == class_def.class_idx_) {
5919 ThrowClassCircularityError(klass.Get(),
5920 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005921 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005922 return false;
5923 }
5924
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005925 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005926 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005927 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005928 return false;
5929 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005930 // Verify
5931 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005932 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005933 super_class->PrettyDescriptor().c_str(),
5934 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005935 return false;
5936 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005937 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005938 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005939 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005940 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005941 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005942 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005943 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005944 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005945 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005946 DCHECK(Thread::Current()->IsExceptionPending());
5947 return false;
5948 }
5949 // Verify
5950 if (!klass->CanAccess(interface)) {
5951 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005952 ThrowIllegalAccessError(klass.Get(),
5953 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005954 interface->PrettyDescriptor().c_str(),
5955 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005956 return false;
5957 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005958 }
5959 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005960 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005961 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005962 return true;
5963}
5964
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005965bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005966 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005967 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005968 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5969 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005970 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005971 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005972 return false;
5973 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005974 return true;
5975 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005976 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005977 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005978 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005979 return false;
5980 }
5981 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005982 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005983 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5984 return false;
5985 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005986 if (super->IsFinal()) {
5987 ThrowVerifyError(klass.Get(),
5988 "Superclass %s of %s is declared final",
5989 super->PrettyDescriptor().c_str(),
5990 klass->PrettyDescriptor().c_str());
5991 return false;
5992 }
5993 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005994 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005995 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005996 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005997 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005998 return false;
5999 }
6000 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006001 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006002 super->PrettyDescriptor().c_str(),
6003 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006004 return false;
6005 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006006
Brian Carlstromf3632832014-05-20 15:36:53 -07006007 // Inherit kAccClassIsFinalizable from the superclass in case this
6008 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006009 if (super->IsFinalizable()) {
6010 klass->SetFinalizable();
6011 }
6012
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006013 // Inherit class loader flag form super class.
6014 if (super->IsClassLoaderClass()) {
6015 klass->SetClassLoaderClass();
6016 }
6017
Elliott Hughes2da50362011-10-10 16:57:08 -07006018 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006019 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006020 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006021 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006022 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006023 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006024 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006025 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006026 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006027 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006028 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006029 return false;
6030 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006031
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006032 if (kIsDebugBuild) {
6033 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006034 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006035 CHECK(super->IsResolved());
6036 super = super->GetSuperClass();
6037 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006038 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006039 return true;
6040}
6041
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006042// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006043bool ClassLinker::LinkMethods(Thread* self,
6044 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006045 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006046 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006047 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006048 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006049 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6050 // need to have default methods be in the virtuals array of each class but we don't set that up
6051 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006052 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006053 // Link virtual methods then interface methods.
6054 // We set up the interface lookup table first because we need it to determine if we need to update
6055 // any vtable entries with new default method implementations.
6056 return SetupInterfaceLookupTable(self, klass, interfaces)
6057 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006058 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006059}
6060
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006061// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6062// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6063// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006064class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006065 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006066 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006067 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006068 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6069 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006070 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006071 }
6072
6073 const char* GetName() {
6074 if (name_ == nullptr) {
6075 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6076 }
6077 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006078 }
6079
Mathieu Chartiere401d142015-04-22 13:56:20 -07006080 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006081 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006082 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006083 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006084 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006085 if (dex_file_ == other_dex_file) {
6086 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6087 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006088 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006089 uint32_t other_name_len;
6090 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6091 &other_name_len);
6092 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6093 return false;
6094 }
6095 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6096 }
6097
6098 private:
6099 // Dex file for the method to compare against.
6100 const DexFile* const dex_file_;
6101 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006102 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006103 // Lazily computed name from the dex file's strings.
6104 const char* name_;
6105 // Lazily computed name length.
6106 uint32_t name_len_;
6107};
6108
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006109class LinkVirtualHashTable {
6110 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006111 LinkVirtualHashTable(Handle<mirror::Class> klass,
6112 size_t hash_size,
6113 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006114 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006115 : klass_(klass),
6116 hash_size_(hash_size),
6117 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006118 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006119 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6120 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006121
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006122 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006123 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6124 virtual_method_index, image_pointer_size_);
6125 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006126 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006127 uint32_t index = hash % hash_size_;
6128 // Linear probe until we have an empty slot.
6129 while (hash_table_[index] != invalid_index_) {
6130 if (++index == hash_size_) {
6131 index = 0;
6132 }
6133 }
6134 hash_table_[index] = virtual_method_index;
6135 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006136
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006137 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006138 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006139 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006140 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006141 size_t index = hash % hash_size_;
6142 while (true) {
6143 const uint32_t value = hash_table_[index];
6144 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6145 // the block and can safely assume not found.
6146 if (value == invalid_index_) {
6147 break;
6148 }
6149 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006150 ArtMethod* virtual_method =
6151 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6152 if (comparator->HasSameNameAndSignature(
6153 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006154 hash_table_[index] = removed_index_;
6155 return value;
6156 }
6157 }
6158 if (++index == hash_size_) {
6159 index = 0;
6160 }
6161 }
6162 return GetNotFoundIndex();
6163 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006164
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006165 static uint32_t GetNotFoundIndex() {
6166 return invalid_index_;
6167 }
6168
6169 private:
6170 static const uint32_t invalid_index_;
6171 static const uint32_t removed_index_;
6172
6173 Handle<mirror::Class> klass_;
6174 const size_t hash_size_;
6175 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006176 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006177};
6178
6179const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6180const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6181
Stephen Hines1ddd9132017-02-08 01:51:18 -08006182bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006183 Thread* self,
6184 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006185 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006186 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006187 if (klass->IsInterface()) {
6188 // No vtable.
6189 if (!IsUint<16>(num_virtual_methods)) {
6190 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6191 return false;
6192 }
6193 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006194 // Assign each method an IMT index and set the default flag.
6195 for (size_t i = 0; i < num_virtual_methods; ++i) {
6196 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6197 m->SetMethodIndex(i);
6198 if (!m->IsAbstract()) {
6199 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6200 has_defaults = true;
6201 }
6202 }
6203 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6204 // during initialization. This is a performance optimization. We could simply traverse the
6205 // virtual_methods_ array again during initialization.
6206 if (has_defaults) {
6207 klass->SetHasDefaultMethods();
6208 }
6209 return true;
6210 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006211 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6212 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006213 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006214 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006215 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006216 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006217 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006218 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006219 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006220 return false;
6221 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006222 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006223 vtable->SetElementPtrSize(
6224 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006225 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006226 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6227 // might give us new default methods). If no new interfaces then we can skip the rest since
6228 // the class cannot override any of the super-class's methods. This is required for
6229 // correctness since without it we might not update overridden default method vtable entries
6230 // correctly.
6231 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006232 klass->SetVTable(vtable.Get());
6233 return true;
6234 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006235 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006236 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006237 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006238 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006239 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6240 // might give us new default methods). See comment above.
6241 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006242 klass->SetVTable(super_vtable);
6243 return true;
6244 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006245 vtable = hs.NewHandle(
6246 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006247 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006248 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006249 return false;
6250 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006251 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006252 // How the algorithm works:
6253 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6254 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6255 // method which has not been matched to a vtable method, and j if the virtual method at the
6256 // index overrode the super virtual method at index j.
6257 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6258 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6259 // the need for the initial vtable which we later shrink back down).
6260 // 3. Add non overridden methods to the end of the vtable.
6261 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006262 // + 1 so that even if we only have new default methods we will still be able to use this hash
6263 // table (i.e. it will never have 0 size).
6264 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006265 uint32_t* hash_table_ptr;
6266 std::unique_ptr<uint32_t[]> hash_heap_storage;
6267 if (hash_table_size <= kMaxStackHash) {
6268 hash_table_ptr = reinterpret_cast<uint32_t*>(
6269 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6270 } else {
6271 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6272 hash_table_ptr = hash_heap_storage.get();
6273 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006274 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006275 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006276 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006277 DCHECK(klass->GetVirtualMethodDuringLinking(
6278 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006279 hash_table.Add(i);
6280 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006281 // 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 -07006282 // the hash table.
6283 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006284 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006285 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006286 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6287 super_method->GetAccessFlags())) {
6288 // Continue on to the next method since this one is package private and canot be overridden.
6289 // Before Android 4.1, the package-private method super_method might have been incorrectly
6290 // overridden.
6291 continue;
6292 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006293 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006294 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006295 // We remove the method so that subsequent lookups will be faster by making the hash-map
6296 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006297 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6298 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006299 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6300 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006301 if (super_method->IsFinal()) {
6302 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6303 virtual_method->PrettyMethod().c_str(),
6304 super_method->GetDeclaringClassDescriptor());
6305 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006306 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006307 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6308 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006309 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006310 // We didn't directly override this method but we might through default methods...
6311 // Check for default method update.
6312 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006313 switch (FindDefaultMethodImplementation(self,
6314 super_method,
6315 klass,
6316 /*out*/&default_method)) {
6317 case DefaultMethodSearchResult::kDefaultConflict: {
6318 // A conflict was found looking for default methods. Note this (assuming it wasn't
6319 // pre-existing) in the translations map.
6320 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6321 // Don't generate another conflict method to reduce memory use as an optimization.
6322 default_translations->insert(
6323 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6324 }
6325 break;
6326 }
6327 case DefaultMethodSearchResult::kAbstractFound: {
6328 // No conflict but method is abstract.
6329 // We note that this vtable entry must be made abstract.
6330 if (UNLIKELY(!super_method->IsAbstract())) {
6331 default_translations->insert(
6332 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6333 }
6334 break;
6335 }
6336 case DefaultMethodSearchResult::kDefaultFound: {
6337 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6338 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6339 // Found a default method implementation that is new.
6340 // TODO Refactor this add default methods to virtuals here and not in
6341 // LinkInterfaceMethods maybe.
6342 // The problem is default methods might override previously present
6343 // default-method or miranda-method vtable entries from the superclass.
6344 // Unfortunately we need these to be entries in this class's virtuals. We do not
6345 // give these entries there until LinkInterfaceMethods so we pass this map around
6346 // to let it know which vtable entries need to be updated.
6347 // Make a note that vtable entry j must be updated, store what it needs to be updated
6348 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6349 // then.
6350 default_translations->insert(
6351 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006352 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6353 << " overridden by default "
6354 << default_method->PrettyMethod()
6355 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006356 }
6357 break;
6358 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006359 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006360 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006361 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006362 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006363 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006364 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006365 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006366 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6367 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006368 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006369 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006370 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006371 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006372 local_method->SetMethodIndex(actual_count);
6373 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006374 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006375 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006376 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006377 return false;
6378 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006379 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006380 CHECK_LE(actual_count, max_count);
6381 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006382 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006383 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006384 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006385 return false;
6386 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006387 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006388 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006389 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006390 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006391 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006392 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6393 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006394 return false;
6395 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006396 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006397 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006398 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006399 return false;
6400 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006401 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006402 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6403 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006404 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006405 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006406 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006407 }
6408 return true;
6409}
6410
Alex Light9139e002015-10-09 15:59:48 -07006411// Determine if the given iface has any subinterface in the given list that declares the method
6412// specified by 'target'.
6413//
6414// Arguments
6415// - self: The thread we are running on
6416// - target: A comparator that will match any method that overrides the method we are checking for
6417// - iftable: The iftable we are searching for an overriding method on.
6418// - ifstart: The index of the interface we are checking to see if anything overrides
6419// - iface: The interface we are checking to see if anything overrides.
6420// - image_pointer_size:
6421// The image pointer size.
6422//
6423// Returns
6424// - True: There is some method that matches the target comparator defined in an interface that
6425// is a subtype of iface.
6426// - False: There is no method that matches the target comparator in any interface that is a subtype
6427// of iface.
6428static bool ContainsOverridingMethodOf(Thread* self,
6429 MethodNameAndSignatureComparator& target,
6430 Handle<mirror::IfTable> iftable,
6431 size_t ifstart,
6432 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006433 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006434 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006435 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006436 DCHECK(iface != nullptr);
6437 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006438 DCHECK_GE(ifstart, 0u);
6439 DCHECK_LT(ifstart, iftable->Count());
6440 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6441 DCHECK(iface->IsInterface());
6442
6443 size_t iftable_count = iftable->Count();
6444 StackHandleScope<1> hs(self);
6445 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6446 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6447 // Skip ifstart since our current interface obviously cannot override itself.
6448 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006449 // Iterate through every method on this interface. The order does not matter.
6450 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006451 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006452 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006453 // Check if the i'th interface is a subtype of this one.
6454 if (iface->IsAssignableFrom(current_iface.Get())) {
6455 return true;
6456 }
6457 break;
6458 }
6459 }
6460 }
6461 return false;
6462}
6463
Alex Lighteb7c1442015-08-31 13:17:42 -07006464// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006465// out_default_method and returns kDefaultFound on success. If no default method was found return
6466// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6467// default_method conflict) it will return kDefaultConflict.
6468ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6469 Thread* self,
6470 ArtMethod* target_method,
6471 Handle<mirror::Class> klass,
6472 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006473 DCHECK(self != nullptr);
6474 DCHECK(target_method != nullptr);
6475 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006476
6477 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006478
6479 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6480 // table. This lets us walk the table backwards when searching for default methods. The first one
6481 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6482 // track of it and then continue checking all other interfaces, since we need to throw an error if
6483 // we encounter conflicting default method implementations (one is not a subtype of the other).
6484 //
6485 // The order of unrelated interfaces does not matter and is not defined.
6486 size_t iftable_count = klass->GetIfTableCount();
6487 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006488 // No interfaces. We have already reset out to null so just return kAbstractFound.
6489 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006490 }
6491
Alex Light9139e002015-10-09 15:59:48 -07006492 StackHandleScope<3> hs(self);
6493 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006494 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006495 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006496 MethodNameAndSignatureComparator target_name_comparator(
6497 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6498 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006499 for (size_t k = iftable_count; k != 0; ) {
6500 --k;
6501
Alex Lighteb7c1442015-08-31 13:17:42 -07006502 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006503
6504 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006505 // Iterate through every declared method on this interface. The order does not matter.
6506 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6507 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006508 // Skip abstract methods and methods with different names.
6509 if (current_method->IsAbstract() ||
6510 !target_name_comparator.HasSameNameAndSignature(
6511 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6512 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006513 } else if (!current_method->IsPublic()) {
6514 // The verifier should have caught the non-public method for dex version 37. Just warn and
6515 // skip it since this is from before default-methods so we don't really need to care that it
6516 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006517 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6518 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006519 << "This will be a fatal error in subsequent versions of android. "
6520 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006521 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006522 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006523 // We have multiple default impls of the same method. This is a potential default conflict.
6524 // We need to check if this possibly conflicting method is either a superclass of the chosen
6525 // default implementation or is overridden by a non-default interface method. In either case
6526 // there is no conflict.
6527 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6528 !ContainsOverridingMethodOf(self,
6529 target_name_comparator,
6530 iftable,
6531 k,
6532 iface,
6533 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006534 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006535 << current_method->PrettyMethod() << " and "
6536 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6537 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006538 *out_default_method = nullptr;
6539 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006540 } else {
6541 break; // Continue checking at the next interface.
6542 }
6543 } else {
Alex Light9139e002015-10-09 15:59:48 -07006544 // chosen_iface == null
6545 if (!ContainsOverridingMethodOf(self,
6546 target_name_comparator,
6547 iftable,
6548 k,
6549 iface,
6550 image_pointer_size_)) {
6551 // Don't set this as the chosen interface if something else is overriding it (because that
6552 // other interface would be potentially chosen instead if it was default). If the other
6553 // interface was abstract then we wouldn't select this interface as chosen anyway since
6554 // the abstract method masks it.
6555 *out_default_method = current_method;
6556 chosen_iface.Assign(iface.Get());
6557 // We should now finish traversing the graph to find if we have default methods that
6558 // conflict.
6559 } else {
David Sehr709b0702016-10-13 09:12:37 -07006560 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6561 << "' was "
6562 << "skipped because it was overridden by an abstract method in a "
6563 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006564 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006565 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006566 break;
6567 }
6568 }
Alex Light9139e002015-10-09 15:59:48 -07006569 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006570 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6571 << "' selected "
6572 << "as the implementation for '" << target_method->PrettyMethod()
6573 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006574 return DefaultMethodSearchResult::kDefaultFound;
6575 } else {
6576 return DefaultMethodSearchResult::kAbstractFound;
6577 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006578}
6579
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006580ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006581 ArtMethod* conflict_method,
6582 ArtMethod* interface_method,
6583 ArtMethod* method,
6584 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006585 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006586 Runtime* const runtime = Runtime::Current();
6587 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6588 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6589
6590 // Create a new entry if the existing one is the shared conflict method.
6591 ArtMethod* new_conflict_method = new_entry
6592 ? runtime->CreateImtConflictMethod(linear_alloc)
6593 : conflict_method;
6594
6595 // Allocate a new table. Note that we will leak this table at the next conflict,
6596 // but that's a tradeoff compared to making the table fixed size.
6597 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006598 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6599 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006600 if (data == nullptr) {
6601 LOG(ERROR) << "Failed to allocate conflict table";
6602 return conflict_method;
6603 }
6604 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6605 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006606 method,
6607 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006608
6609 // Do a fence to ensure threads see the data in the table before it is assigned
6610 // to the conflict method.
6611 // Note that there is a race in the presence of multiple threads and we may leak
6612 // memory from the LinearAlloc, but that's a tradeoff compared to using
6613 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006614 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006615 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006616 return new_conflict_method;
6617}
6618
Vladimir Marko921094a2017-01-12 18:37:06 +00006619bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6620 Handle<mirror::Class> klass,
6621 Handle<mirror::IfTable> iftable) {
6622 DCHECK(!klass->IsInterface());
6623 const bool has_superclass = klass->HasSuperClass();
6624 const bool extend_super_iftable = has_superclass;
6625 const size_t ifcount = klass->GetIfTableCount();
6626 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6627 for (size_t i = 0; i < ifcount; ++i) {
6628 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6629 if (num_methods > 0) {
6630 const bool is_super = i < super_ifcount;
6631 // This is an interface implemented by a super-class. Therefore we can just copy the method
6632 // array from the superclass.
6633 const bool super_interface = is_super && extend_super_iftable;
6634 ObjPtr<mirror::PointerArray> method_array;
6635 if (super_interface) {
6636 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6637 DCHECK(if_table != nullptr);
6638 DCHECK(if_table->GetMethodArray(i) != nullptr);
6639 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006640 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6641 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006642 } else {
6643 method_array = AllocPointerArray(self, num_methods);
6644 }
6645 if (UNLIKELY(method_array == nullptr)) {
6646 self->AssertPendingOOMException();
6647 return false;
6648 }
6649 iftable->SetMethodArray(i, method_array);
6650 }
6651 }
6652 return true;
6653}
6654
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006655void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6656 ArtMethod* imt_conflict_method,
6657 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006658 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006659 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006660 // Place method in imt if entry is empty, place conflict otherwise.
6661 if (*imt_ref == unimplemented_method) {
6662 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006663 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006664 // If we are not a conflict and we have the same signature and name as the imt
6665 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006666 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6667 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006668 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006669 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006670 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006671 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006672 *imt_ref = current_method;
6673 } else {
Alex Light9139e002015-10-09 15:59:48 -07006674 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006675 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006676 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006677 } else {
6678 // Place the default conflict method. Note that there may be an existing conflict
6679 // method in the IMT, but it could be one tailored to the super class, with a
6680 // specific ImtConflictTable.
6681 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006682 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006683 }
6684}
6685
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006686void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006687 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6688 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006689 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006690 Runtime* const runtime = Runtime::Current();
6691 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6692 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006693 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006694 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006695 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006696 FillIMTFromIfTable(klass->GetIfTable(),
6697 unimplemented_method,
6698 conflict_method,
6699 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006700 /*create_conflict_tables=*/true,
6701 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006702 &new_conflict,
6703 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006704 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006705 if (!klass->ShouldHaveImt()) {
6706 return;
6707 }
6708 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6709 // we can just use the same pointer.
6710 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006711 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006712 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6713 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6714 bool same = true;
6715 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6716 ArtMethod* method = imt_data[i];
6717 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6718 if (method != super_method) {
6719 bool is_conflict_table = method->IsRuntimeMethod() &&
6720 method != unimplemented_method &&
6721 method != conflict_method;
6722 // Verify conflict contents.
6723 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6724 super_method != unimplemented_method &&
6725 super_method != conflict_method;
6726 if (!is_conflict_table || !super_conflict_table) {
6727 same = false;
6728 } else {
6729 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6730 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6731 same = same && table1->Equals(table2, image_pointer_size_);
6732 }
6733 }
6734 }
6735 if (same) {
6736 imt = super_imt;
6737 }
6738 }
6739 if (imt == nullptr) {
6740 imt = klass->GetImt(image_pointer_size_);
6741 DCHECK(imt != nullptr);
6742 imt->Populate(imt_data, image_pointer_size_);
6743 } else {
6744 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006745 }
6746}
6747
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006748ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6749 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006750 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006751 void* data = linear_alloc->Alloc(Thread::Current(),
6752 ImtConflictTable::ComputeSize(count,
6753 image_pointer_size));
6754 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6755}
6756
6757ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6758 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6759}
6760
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006761void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006762 ArtMethod* unimplemented_method,
6763 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006764 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006765 bool create_conflict_tables,
6766 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006767 /*out*/bool* new_conflict,
6768 /*out*/ArtMethod** imt) {
6769 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006770 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006771 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006772 const size_t num_virtuals = interface->NumVirtualMethods();
6773 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6774 // Virtual methods can be larger than the if table methods if there are default methods.
6775 DCHECK_GE(num_virtuals, method_array_count);
6776 if (kIsDebugBuild) {
6777 if (klass->IsInterface()) {
6778 DCHECK_EQ(method_array_count, 0u);
6779 } else {
6780 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6781 }
6782 }
6783 if (method_array_count == 0) {
6784 continue;
6785 }
6786 auto* method_array = if_table->GetMethodArray(i);
6787 for (size_t j = 0; j < method_array_count; ++j) {
6788 ArtMethod* implementation_method =
6789 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6790 if (ignore_copied_methods && implementation_method->IsCopied()) {
6791 continue;
6792 }
6793 DCHECK(implementation_method != nullptr);
6794 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6795 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6796 // or interface methods in the IMT here they will not create extra conflicts since we compare
6797 // names and signatures in SetIMTRef.
6798 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006799 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006800
6801 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6802 // the same implementation method, keep track of this to avoid creating a conflict table in
6803 // this case.
6804
6805 // Conflict table size for each IMT slot.
6806 ++conflict_counts[imt_index];
6807
6808 SetIMTRef(unimplemented_method,
6809 imt_conflict_method,
6810 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006811 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006812 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006813 }
6814 }
6815
6816 if (create_conflict_tables) {
6817 // Create the conflict tables.
6818 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006819 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006820 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006821 if (imt[i] == imt_conflict_method) {
6822 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6823 if (new_table != nullptr) {
6824 ArtMethod* new_conflict_method =
6825 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6826 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6827 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006828 } else {
6829 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006830 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006831 }
6832 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006833 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006834 }
6835 }
6836
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006837 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006838 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006839 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6840 // Virtual methods can be larger than the if table methods if there are default methods.
6841 if (method_array_count == 0) {
6842 continue;
6843 }
6844 auto* method_array = if_table->GetMethodArray(i);
6845 for (size_t j = 0; j < method_array_count; ++j) {
6846 ArtMethod* implementation_method =
6847 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6848 if (ignore_copied_methods && implementation_method->IsCopied()) {
6849 continue;
6850 }
6851 DCHECK(implementation_method != nullptr);
6852 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006853 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006854 if (!imt[imt_index]->IsRuntimeMethod() ||
6855 imt[imt_index] == unimplemented_method ||
6856 imt[imt_index] == imt_conflict_method) {
6857 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006858 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006859 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6860 const size_t num_entries = table->NumEntries(image_pointer_size_);
6861 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6862 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006863 }
6864 }
6865 }
6866}
6867
Alex Lighteb7c1442015-08-31 13:17:42 -07006868// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6869// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006870static bool NotSubinterfaceOfAny(
6871 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6872 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006873 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006874 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006875 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006876 for (ObjPtr<mirror::Class> c : classes) {
6877 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006878 return false;
6879 }
6880 }
6881 return true;
6882}
6883
6884// Fills in and flattens the interface inheritance hierarchy.
6885//
6886// By the end of this function all interfaces in the transitive closure of to_process are added to
6887// the iftable and every interface precedes all of its sub-interfaces in this list.
6888//
6889// all I, J: Interface | I <: J implies J precedes I
6890//
6891// (note A <: B means that A is a subtype of B)
6892//
6893// This returns the total number of items in the iftable. The iftable might be resized down after
6894// this call.
6895//
6896// We order this backwards so that we do not need to reorder superclass interfaces when new
6897// interfaces are added in subclass's interface tables.
6898//
6899// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6900// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6901// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6902// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006903static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006904 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006905 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006906 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006907 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006908 // This is the set of all class's already in the iftable. Used to make checking if a class has
6909 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006910 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006911 // The first super_ifcount elements are from the superclass. We note that they are already added.
6912 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006913 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006914 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6915 classes_in_iftable.insert(iface);
6916 }
6917 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006918 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006919 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6920 // At this point in the loop current-iface-list has the invariant that:
6921 // for every pair of interfaces I,J within it:
6922 // if index_of(I) < index_of(J) then I is not a subtype of J
6923
6924 // If we have already seen this element then all of its super-interfaces must already be in the
6925 // current-iface-list so we can skip adding it.
6926 if (!ContainsElement(classes_in_iftable, interface)) {
6927 // We haven't seen this interface so add all of its super-interfaces onto the
6928 // current-iface-list, skipping those already on it.
6929 int32_t ifcount = interface->GetIfTableCount();
6930 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006931 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006932 if (!ContainsElement(classes_in_iftable, super_interface)) {
6933 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6934 classes_in_iftable.insert(super_interface);
6935 iftable->SetInterface(filled_ifcount, super_interface);
6936 filled_ifcount++;
6937 }
6938 }
6939 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6940 // Place this interface onto the current-iface-list after all of its super-interfaces.
6941 classes_in_iftable.insert(interface);
6942 iftable->SetInterface(filled_ifcount, interface);
6943 filled_ifcount++;
6944 } else if (kIsDebugBuild) {
6945 // Check all super-interfaces are already in the list.
6946 int32_t ifcount = interface->GetIfTableCount();
6947 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006948 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006949 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006950 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6951 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006952 }
6953 }
6954 }
6955 if (kIsDebugBuild) {
6956 // Check that the iftable is ordered correctly.
6957 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006958 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006959 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006960 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006961 // !(if_a <: if_b)
6962 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006963 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6964 << ") extends "
6965 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006966 << "interface list.";
6967 }
6968 }
6969 }
6970 return filled_ifcount;
6971}
6972
6973bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6974 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6975 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006976 const bool has_superclass = klass->HasSuperClass();
6977 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006978 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006979 const size_t num_interfaces =
6980 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006981 if (num_interfaces == 0) {
6982 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006983 if (LIKELY(has_superclass)) {
6984 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6985 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006986 // Class implements no interfaces.
6987 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006988 return true;
6989 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006990 // Class implements same interfaces as parent, are any of these not marker interfaces?
6991 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006992 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006993 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006994 if (super_iftable->GetMethodArrayCount(i) > 0) {
6995 has_non_marker_interface = true;
6996 break;
6997 }
6998 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006999 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007000 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007001 klass->SetIfTable(super_iftable);
7002 return true;
7003 }
7004 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007005 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007006 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007007 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007008 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007009 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007010 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007011 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007012 if (UNLIKELY(!interface->IsInterface())) {
7013 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007014 ThrowIncompatibleClassChangeError(klass.Get(),
7015 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007016 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007017 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7018 return false;
7019 }
7020 ifcount += interface->GetIfTableCount();
7021 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007022 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007023 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007024 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007025 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007026 return false;
7027 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007028 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007029 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007030 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007031 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007032 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007033 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007034 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007035 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007036
7037 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7038 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7039 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007040 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007041
7042 size_t new_ifcount;
7043 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007044 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007045 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007046 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007047 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007048 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007049 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007050 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007051
7052 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007053 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007054
Ian Rogers7b078e82014-09-10 14:44:24 -07007055 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007056
Ian Rogersb52b01a2012-01-12 17:01:38 -08007057 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007058 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007059 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007060 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007061 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007062 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007063 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007064 return false;
7065 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007066 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007067 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007068 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007069 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007070 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007071 return true;
7072}
7073
Alex Light1f3925d2016-09-07 12:04:20 -07007074// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7075// of methods must be unique.
7076static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7077 return nullptr;
7078}
7079
7080template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007081static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007082 const ScopedArenaVector<ArtMethod*>& list,
7083 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007084 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007085 for (ArtMethod* method : list) {
7086 if (cmp.HasSameNameAndSignature(method)) {
7087 return method;
7088 }
7089 }
Alex Light1f3925d2016-09-07 12:04:20 -07007090 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007091}
7092
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007093namespace {
7094
Alex Light1f3925d2016-09-07 12:04:20 -07007095// Check that all vtable entries are present in this class's virtuals or are the same as a
7096// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007097void CheckClassOwnsVTableEntries(Thread* self,
7098 Handle<mirror::Class> klass,
7099 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007100 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007101 StackHandleScope<2> hs(self);
7102 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007103 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007104 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007105 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007106 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7107 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7108 CHECK(m != nullptr);
7109
Alex Lighta41a30782017-03-29 11:33:19 -07007110 if (m->GetMethodIndexDuringLinking() != i) {
7111 LOG(WARNING) << m->PrettyMethod()
7112 << " has an unexpected method index for its spot in the vtable for class"
7113 << klass->PrettyClass();
7114 }
Alex Lighte64300b2015-12-15 15:02:47 -08007115 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7116 auto is_same_method = [m] (const ArtMethod& meth) {
7117 return &meth == m;
7118 };
Alex Light3f980532017-03-17 15:10:32 -07007119 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7120 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7121 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7122 << klass->PrettyClass() << " or any of its superclasses!";
7123 }
Alex Lighte64300b2015-12-15 15:02:47 -08007124 }
7125}
7126
Alex Light1f3925d2016-09-07 12:04:20 -07007127// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7128// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007129template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007130void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007131 REQUIRES_SHARED(Locks::mutator_lock_) {
7132 StackHandleScope<1> hs(self);
7133 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7134 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007135
7136 // Observations:
7137 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7138 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7139 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7140 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7141 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7142 // * The single-pass algorithm will trade memory for speed, but that is OK.
7143
7144 CHECK_GT(num_entries, 0);
7145
7146 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7147 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7148 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7149 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7150 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7151 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7152 << m2->PrettyMethod() << " (0x" << std::hex
7153 << reinterpret_cast<uintptr_t>(m2) << ")";
7154 };
7155 struct BaseHashType {
7156 static size_t HashCombine(size_t seed, size_t val) {
7157 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7158 }
7159 };
7160
7161 // Check assuming all entries come from the same dex file.
7162 {
7163 // Find the first interesting method and its dex file.
7164 int32_t start = 0;
7165 for (; start < num_entries; ++start) {
7166 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7167 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7168 // maybe).
7169 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7170 vtable_entry->GetAccessFlags())) {
7171 continue;
7172 }
7173 break;
7174 }
7175 if (start == num_entries) {
7176 return;
7177 }
7178 const DexFile* dex_file =
7179 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7180 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7181
7182 // Helper function to avoid logging if we have to run the cross-file checks.
7183 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7184 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7185 using PairType = std::pair<uint32_t, uint16_t>;
7186 struct PairHash : BaseHashType {
7187 size_t operator()(const PairType& key) const {
7188 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7189 }
7190 };
7191 std::unordered_map<PairType, int32_t, PairHash> seen;
7192 seen.reserve(2 * num_entries);
7193 bool need_slow_path = false;
7194 bool found_dup = false;
7195 for (int i = start; i < num_entries; ++i) {
7196 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7197 // wrt/ kPointerSize.
7198 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7199 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7200 vtable_entry->GetAccessFlags())) {
7201 continue;
7202 }
7203 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7204 if (dex_file != m->GetDexFile()) {
7205 need_slow_path = true;
7206 break;
7207 }
7208 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7209 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7210 auto it = seen.find(pair);
7211 if (it != seen.end()) {
7212 found_dup = true;
7213 if (log_warn) {
7214 log_fn(it->second, i);
7215 }
7216 } else {
7217 seen.emplace(pair, i);
7218 }
7219 }
7220 return std::make_pair(need_slow_path, found_dup);
7221 };
7222 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7223 if (!result.first) {
7224 if (result.second) {
7225 check_fn(/* log_warn= */ true);
7226 }
7227 return;
7228 }
7229 }
7230
7231 // Need to check across dex files.
7232 struct Entry {
7233 size_t cached_hash = 0;
7234 const char* name = nullptr;
7235 Signature signature = Signature::NoSignature();
7236 uint32_t name_len = 0;
7237
7238 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7239 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7240 signature(dex_file->GetMethodSignature(mid)) {
7241 }
7242
7243 bool operator==(const Entry& other) const {
7244 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7245 return false;
7246 }
7247 return signature == other.signature;
7248 }
7249 };
7250 struct EntryHash {
7251 size_t operator()(const Entry& key) const {
7252 return key.cached_hash;
7253 }
7254 };
7255 std::unordered_map<Entry, int32_t, EntryHash> map;
7256 for (int32_t i = 0; i < num_entries; ++i) {
7257 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7258 // wrt/ kPointerSize.
7259 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7260 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7261 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007262 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7263 vtable_entry->GetAccessFlags())) {
7264 continue;
7265 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007266 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7267 const DexFile* dex_file = m->GetDexFile();
7268 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7269
7270 Entry e(dex_file, mid);
7271
7272 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7273 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7274 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7275 sig_hash);
7276
7277 auto it = map.find(e);
7278 if (it != map.end()) {
7279 log_fn(it->second, i);
7280 } else {
7281 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007282 }
7283 }
7284}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007285
7286void CheckVTableHasNoDuplicates(Thread* self,
7287 Handle<mirror::Class> klass,
7288 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007289 REQUIRES_SHARED(Locks::mutator_lock_) {
7290 switch (pointer_size) {
7291 case PointerSize::k64:
7292 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7293 break;
7294 case PointerSize::k32:
7295 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7296 break;
7297 }
7298}
Alex Light1f3925d2016-09-07 12:04:20 -07007299
7300static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7301 REQUIRES_SHARED(Locks::mutator_lock_) {
7302 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7303 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7304}
7305
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007306} // namespace
7307
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007308void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7309 ArtMethod* unimplemented_method,
7310 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007311 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007312 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007313 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007314 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007315 if (super_class->ShouldHaveImt()) {
7316 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7317 for (size_t i = 0; i < ImTable::kSize; ++i) {
7318 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007319 }
7320 } else {
7321 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007322 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007323 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007324 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007325 FillIMTFromIfTable(if_table,
7326 unimplemented_method,
7327 imt_conflict_method,
7328 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007329 /*create_conflict_tables=*/false,
7330 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007331 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007332 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007333 }
7334 }
7335}
7336
Vladimir Marko921094a2017-01-12 18:37:06 +00007337class ClassLinker::LinkInterfaceMethodsHelper {
7338 public:
7339 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7340 Handle<mirror::Class> klass,
7341 Thread* self,
7342 Runtime* runtime)
7343 : class_linker_(class_linker),
7344 klass_(klass),
7345 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7346 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7347 self_(self),
7348 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7349 allocator_(&stack_),
7350 default_conflict_methods_(allocator_.Adapter()),
7351 overriding_default_conflict_methods_(allocator_.Adapter()),
7352 miranda_methods_(allocator_.Adapter()),
7353 default_methods_(allocator_.Adapter()),
7354 overriding_default_methods_(allocator_.Adapter()),
7355 move_table_(allocator_.Adapter()) {
7356 }
7357
7358 ArtMethod* FindMethod(ArtMethod* interface_method,
7359 MethodNameAndSignatureComparator& interface_name_comparator,
7360 ArtMethod* vtable_impl)
7361 REQUIRES_SHARED(Locks::mutator_lock_);
7362
7363 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7364 MethodNameAndSignatureComparator& interface_name_comparator)
7365 REQUIRES_SHARED(Locks::mutator_lock_);
7366
7367 bool HasNewVirtuals() const {
7368 return !(miranda_methods_.empty() &&
7369 default_methods_.empty() &&
7370 overriding_default_methods_.empty() &&
7371 overriding_default_conflict_methods_.empty() &&
7372 default_conflict_methods_.empty());
7373 }
7374
7375 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7376
7377 ObjPtr<mirror::PointerArray> UpdateVtable(
7378 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7379 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7380
7381 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7382
7383 void UpdateIMT(ArtMethod** out_imt);
7384
7385 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7386 if (kIsDebugBuild) {
7387 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7388 // Check that there are no stale methods are in the dex cache array.
7389 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7390 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007391 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7392 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007393 CHECK(move_table_.find(m) == move_table_.end() ||
7394 // The original versions of copied methods will still be present so allow those too.
7395 // Note that if the first check passes this might fail to GetDeclaringClass().
7396 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7397 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7398 [m] (ArtMethod& meth) {
7399 return &meth == m;
7400 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7401 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7402 }
7403 }
7404 }
7405
7406 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7407 LengthPrefixedArray<ArtMethod>* methods) {
7408 if (kIsDebugBuild) {
7409 CHECK(methods != nullptr);
7410 // Put some random garbage in old methods to help find stale pointers.
7411 if (methods != old_methods && old_methods != nullptr) {
7412 // Need to make sure the GC is not running since it could be scanning the methods we are
7413 // about to overwrite.
7414 ScopedThreadStateChange tsc(self_, kSuspended);
7415 gc::ScopedGCCriticalSection gcs(self_,
7416 gc::kGcCauseClassLinker,
7417 gc::kCollectorTypeClassLinker);
7418 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7419 method_size_,
7420 method_alignment_);
7421 memset(old_methods, 0xFEu, old_size);
7422 }
7423 }
7424 }
7425
7426 private:
7427 size_t NumberOfNewVirtuals() const {
7428 return miranda_methods_.size() +
7429 default_methods_.size() +
7430 overriding_default_conflict_methods_.size() +
7431 overriding_default_methods_.size() +
7432 default_conflict_methods_.size();
7433 }
7434
7435 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7436 return !klass_->IsInterface();
7437 }
7438
7439 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7440 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7441 << "Interfaces should only have default-conflict methods appended to them.";
7442 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7443 << miranda_methods_.size()
7444 << " default_methods=" << default_methods_.size()
7445 << " overriding_default_methods=" << overriding_default_methods_.size()
7446 << " default_conflict_methods=" << default_conflict_methods_.size()
7447 << " overriding_default_conflict_methods="
7448 << overriding_default_conflict_methods_.size();
7449 }
7450
7451 ClassLinker* class_linker_;
7452 Handle<mirror::Class> klass_;
7453 size_t method_alignment_;
7454 size_t method_size_;
7455 Thread* const self_;
7456
7457 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7458 // the virtual methods array.
7459 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7460 // during cross compilation.
7461 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7462 ArenaStack stack_;
7463 ScopedArenaAllocator allocator_;
7464
7465 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7466 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7467 ScopedArenaVector<ArtMethod*> miranda_methods_;
7468 ScopedArenaVector<ArtMethod*> default_methods_;
7469 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7470
7471 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7472};
7473
7474ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7475 ArtMethod* interface_method,
7476 MethodNameAndSignatureComparator& interface_name_comparator,
7477 ArtMethod* vtable_impl) {
7478 ArtMethod* current_method = nullptr;
7479 switch (class_linker_->FindDefaultMethodImplementation(self_,
7480 interface_method,
7481 klass_,
7482 /*out*/&current_method)) {
7483 case DefaultMethodSearchResult::kDefaultConflict: {
7484 // Default method conflict.
7485 DCHECK(current_method == nullptr);
7486 ArtMethod* default_conflict_method = nullptr;
7487 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7488 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7489 default_conflict_method = vtable_impl;
7490 } else {
7491 // See if we already have a conflict method for this method.
7492 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7493 interface_name_comparator,
7494 default_conflict_methods_,
7495 overriding_default_conflict_methods_);
7496 if (LIKELY(preexisting_conflict != nullptr)) {
7497 // We already have another conflict we can reuse.
7498 default_conflict_method = preexisting_conflict;
7499 } else {
7500 // Note that we do this even if we are an interface since we need to create this and
7501 // cannot reuse another classes.
7502 // Create a new conflict method for this to use.
7503 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7504 new(default_conflict_method) ArtMethod(interface_method,
7505 class_linker_->GetImagePointerSize());
7506 if (vtable_impl == nullptr) {
7507 // Save the conflict method. We need to add it to the vtable.
7508 default_conflict_methods_.push_back(default_conflict_method);
7509 } else {
7510 // Save the conflict method but it is already in the vtable.
7511 overriding_default_conflict_methods_.push_back(default_conflict_method);
7512 }
7513 }
7514 }
7515 current_method = default_conflict_method;
7516 break;
7517 } // case kDefaultConflict
7518 case DefaultMethodSearchResult::kDefaultFound: {
7519 DCHECK(current_method != nullptr);
7520 // Found a default method.
7521 if (vtable_impl != nullptr &&
7522 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7523 // We found a default method but it was the same one we already have from our
7524 // superclass. Don't bother adding it to our vtable again.
7525 current_method = vtable_impl;
7526 } else if (LIKELY(FillTables())) {
7527 // Interfaces don't need to copy default methods since they don't have vtables.
7528 // Only record this default method if it is new to save space.
7529 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7530 // would make lookup for interface super much faster. (We would only need to scan
7531 // the iftable to find if there is a NSME or AME.)
7532 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7533 default_methods_,
7534 overriding_default_methods_);
7535 if (old == nullptr) {
7536 // We found a default method implementation and there were no conflicts.
7537 if (vtable_impl == nullptr) {
7538 // Save the default method. We need to add it to the vtable.
7539 default_methods_.push_back(current_method);
7540 } else {
7541 // Save the default method but it is already in the vtable.
7542 overriding_default_methods_.push_back(current_method);
7543 }
7544 } else {
7545 CHECK(old == current_method) << "Multiple default implementations selected!";
7546 }
7547 }
7548 break;
7549 } // case kDefaultFound
7550 case DefaultMethodSearchResult::kAbstractFound: {
7551 DCHECK(current_method == nullptr);
7552 // Abstract method masks all defaults.
7553 if (vtable_impl != nullptr &&
7554 vtable_impl->IsAbstract() &&
7555 !vtable_impl->IsDefaultConflicting()) {
7556 // We need to make this an abstract method but the version in the vtable already is so
7557 // don't do anything.
7558 current_method = vtable_impl;
7559 }
7560 break;
7561 } // case kAbstractFound
7562 }
7563 return current_method;
7564}
7565
7566ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7567 ArtMethod* interface_method,
7568 MethodNameAndSignatureComparator& interface_name_comparator) {
7569 // Find out if there is already a miranda method we can use.
7570 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7571 miranda_methods_);
7572 if (miranda_method == nullptr) {
7573 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7574 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7575 CHECK(miranda_method != nullptr);
7576 // Point the interface table at a phantom slot.
7577 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7578 miranda_methods_.push_back(miranda_method);
7579 }
7580 return miranda_method;
7581}
7582
7583void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7584 LogNewVirtuals();
7585
7586 const size_t old_method_count = klass_->NumMethods();
7587 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7588 DCHECK_NE(old_method_count, new_method_count);
7589
7590 // Attempt to realloc to save RAM if possible.
7591 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7592 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7593 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7594 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7595 // CopyFrom has internal read barriers.
7596 //
7597 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7598 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7599 method_size_,
7600 method_alignment_);
7601 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7602 method_size_,
7603 method_alignment_);
7604 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7605 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007606 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007607 self_, old_methods, old_methods_ptr_size, new_size));
7608 CHECK(methods != nullptr); // Native allocation failure aborts.
7609
7610 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7611 if (methods != old_methods) {
7612 // Maps from heap allocated miranda method to linear alloc miranda method.
7613 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7614 // Copy over the old methods.
7615 for (auto& m : klass_->GetMethods(pointer_size)) {
7616 move_table_.emplace(&m, &*out);
7617 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7618 // barriers when it copies.
7619 out->CopyFrom(&m, pointer_size);
7620 ++out;
7621 }
7622 }
7623 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7624 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7625 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007626 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7627 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007628 ArtMethod& new_method = *out;
7629 new_method.CopyFrom(mir_method, pointer_size);
7630 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7631 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7632 << "Miranda method should be abstract!";
7633 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007634 // Update the entry in the method array, as the array will be used for future lookups,
7635 // where thread suspension is allowed.
7636 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7637 // would not see them.
7638 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007639 ++out;
7640 }
7641 // We need to copy the default methods into our own method table since the runtime requires that
7642 // every method on a class's vtable be in that respective class's virtual method table.
7643 // NOTE This means that two classes might have the same implementation of a method from the same
7644 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7645 // default method found on a class with one found on the declaring interface directly and must
7646 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007647 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7648 &overriding_default_methods_}) {
7649 for (size_t i = 0; i < methods_vec->size(); ++i) {
7650 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007651 ArtMethod& new_method = *out;
7652 new_method.CopyFrom(def_method, pointer_size);
7653 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7654 // verified yet it shouldn't have methods that are skipping access checks.
7655 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7656 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007657 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007658 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7659 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7660 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7661 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007662 // Update the entry in the method array, as the array will be used for future lookups,
7663 // where thread suspension is allowed.
7664 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7665 // would not see them.
7666 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007667 ++out;
7668 }
7669 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007670 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7671 &overriding_default_conflict_methods_}) {
7672 for (size_t i = 0; i < methods_vec->size(); ++i) {
7673 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007674 ArtMethod& new_method = *out;
7675 new_method.CopyFrom(conf_method, pointer_size);
7676 // This is a type of default method (there are default method impls, just a conflict) so
7677 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7678 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7679 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007680 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7681 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007682 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007683 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007684 constexpr uint32_t kMaskFlags =
7685 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007686 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7687 DCHECK(new_method.IsDefaultConflicting());
7688 // The actual method might or might not be marked abstract since we just copied it from a
7689 // (possibly default) interface method. We need to set it entry point to be the bridge so
7690 // that the compiler will not invoke the implementation of whatever method we copied from.
7691 EnsureThrowsInvocationError(class_linker_, &new_method);
7692 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007693 // Update the entry in the method array, as the array will be used for future lookups,
7694 // where thread suspension is allowed.
7695 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7696 // would not see them.
7697 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007698 ++out;
7699 }
7700 }
7701 methods->SetSize(new_method_count);
7702 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7703}
7704
7705ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7706 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7707 ObjPtr<mirror::PointerArray> old_vtable) {
7708 // Update the vtable to the new method structures. We can skip this for interfaces since they
7709 // do not have vtables.
7710 const size_t old_vtable_count = old_vtable->GetLength();
7711 const size_t new_vtable_count = old_vtable_count +
7712 miranda_methods_.size() +
7713 default_methods_.size() +
7714 default_conflict_methods_.size();
7715
7716 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007717 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007718 if (UNLIKELY(vtable == nullptr)) {
7719 self_->AssertPendingOOMException();
7720 return nullptr;
7721 }
7722
7723 size_t vtable_pos = old_vtable_count;
7724 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7725 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7726 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7727 default_conflict_methods_,
7728 miranda_methods_}) {
7729 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007730 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007731 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7732 // fields are references into the dex file the method was defined in. Since the ArtMethod
7733 // does not store that information it uses declaring_class_->dex_cache_.
7734 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7735 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7736 ++vtable_pos;
7737 }
7738 }
7739 DCHECK_EQ(vtable_pos, new_vtable_count);
7740
7741 // Update old vtable methods. We use the default_translations map to figure out what each
7742 // vtable entry should be updated to, if they need to be at all.
7743 for (size_t i = 0; i < old_vtable_count; ++i) {
7744 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7745 // Try and find what we need to change this method to.
7746 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007747 if (translation_it != default_translations.end()) {
7748 if (translation_it->second.IsInConflict()) {
7749 // Find which conflict method we are to use for this method.
7750 MethodNameAndSignatureComparator old_method_comparator(
7751 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7752 // We only need to look through overriding_default_conflict_methods since this is an
7753 // overridden method we are fixing up here.
7754 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7755 old_method_comparator, overriding_default_conflict_methods_);
7756 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7757 translated_method = new_conflict_method;
7758 } else if (translation_it->second.IsAbstract()) {
7759 // Find which miranda method we are to use for this method.
7760 MethodNameAndSignatureComparator old_method_comparator(
7761 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7762 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7763 miranda_methods_);
7764 DCHECK(miranda_method != nullptr);
7765 translated_method = miranda_method;
7766 } else {
7767 // Normal default method (changed from an older default or abstract interface method).
7768 DCHECK(translation_it->second.IsTranslation());
7769 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007770 auto it = move_table_.find(translated_method);
7771 DCHECK(it != move_table_.end());
7772 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007773 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007774 } else {
7775 auto it = move_table_.find(translated_method);
7776 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007777 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007778
7779 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007780 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007781 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007782 if (kIsDebugBuild) {
7783 auto* methods = klass_->GetMethodsPtr();
7784 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007785 reinterpret_cast<uintptr_t>(translated_method));
7786 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007787 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7788 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007789 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007790 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007791 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007792 }
7793 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007794 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007795 return vtable;
7796}
7797
7798void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7799 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7800 const size_t ifcount = klass_->GetIfTableCount();
7801 // Go fix up all the stale iftable pointers.
7802 for (size_t i = 0; i < ifcount; ++i) {
7803 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7804 auto* method_array = iftable->GetMethodArray(i);
7805 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7806 DCHECK(m != nullptr) << klass_->PrettyClass();
7807 auto it = move_table_.find(m);
7808 if (it != move_table_.end()) {
7809 auto* new_m = it->second;
7810 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7811 method_array->SetElementPtrSize(j, new_m, pointer_size);
7812 }
7813 }
7814 }
7815}
7816
7817void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7818 // Fix up IMT next.
7819 for (size_t i = 0; i < ImTable::kSize; ++i) {
7820 auto it = move_table_.find(out_imt[i]);
7821 if (it != move_table_.end()) {
7822 out_imt[i] = it->second;
7823 }
7824 }
7825}
7826
Alex Light705ad492015-09-21 11:36:30 -07007827// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007828bool ClassLinker::LinkInterfaceMethods(
7829 Thread* self,
7830 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007831 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007832 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007833 ArtMethod** out_imt) {
7834 StackHandleScope<3> hs(self);
7835 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007836
7837 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007838 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007839 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007840 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007841 const size_t ifcount = klass->GetIfTableCount();
7842
Vladimir Marko921094a2017-01-12 18:37:06 +00007843 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007844
7845 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7846 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007847 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007848 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007849 const bool extend_super_iftable = has_superclass;
7850 if (has_superclass && fill_tables) {
7851 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007852 unimplemented_method,
7853 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007854 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007855 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007856 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007857 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7858 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007859 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007860 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7861 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007862 }
7863 }
7864
Vladimir Marko921094a2017-01-12 18:37:06 +00007865 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7866
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007867 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007868 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007869 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7870 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7871 // they will already be null. This has the additional benefit that the declarer of a miranda
7872 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007873 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007874 --i;
Alex Light9139e002015-10-09 15:59:48 -07007875 DCHECK_LT(i, ifcount);
7876
Alex Light705ad492015-09-21 11:36:30 -07007877 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007878 if (num_methods > 0) {
7879 StackHandleScope<2> hs2(self);
7880 const bool is_super = i < super_ifcount;
7881 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007882 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7883 // conflict methods. Just set this as nullptr in those cases.
7884 Handle<mirror::PointerArray> method_array(fill_tables
7885 ? hs2.NewHandle(iftable->GetMethodArray(i))
7886 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007887
Alex Lighte64300b2015-12-15 15:02:47 -08007888 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007889 ScopedNullHandle<mirror::PointerArray> null_handle;
7890 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007891 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007892
Alex Light9139e002015-10-09 15:59:48 -07007893 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7894 // and confusing. Default methods should always look through all the superclasses
7895 // because they are the last choice of an implementation. We get around this by looking
7896 // at the super-classes iftable methods (copied into method_array previously) when we are
7897 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007898 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007899 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007900 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007901 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007902 using_virtuals = true;
7903 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7904 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007905 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007906 // For a new interface, however, we need the whole vtable in case a new
7907 // interface method is implemented in the whole superclass.
7908 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007909 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007910 input_vtable_array = vtable;
7911 input_array_length = input_vtable_array->GetLength();
7912 }
Alex Lighte64300b2015-12-15 15:02:47 -08007913
Alex Lighteb7c1442015-08-31 13:17:42 -07007914 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007915 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007916 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007917 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007918 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007919 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007920 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007921 // For each method listed in the interface's method list, find the
7922 // matching method in our class's method list. We want to favor the
7923 // subclass over the superclass, which just requires walking
7924 // back from the end of the vtable. (This only matters if the
7925 // superclass defines a private method and this class redefines
7926 // it -- otherwise it would use the same vtable slot. In .dex files
7927 // those don't end up in the virtual method table, so it shouldn't
7928 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007929 //
7930 // To find defaults we need to do the same but also go over interfaces.
7931 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007932 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007933 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007934 ArtMethod* vtable_method = using_virtuals ?
7935 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007936 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7937 ArtMethod* vtable_method_for_name_comparison =
7938 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007939 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007940 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007941 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007942 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7943 // allocations.
7944 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007945 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007946 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007947 vtable_method->PrettyMethod().c_str(),
7948 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007949 return false;
Alex Light9139e002015-10-09 15:59:48 -07007950 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007951 // We might have a newer, better, default method for this, so we just skip it. If we
7952 // are still using this we will select it again when scanning for default methods. To
7953 // obviate the need to copy the method again we will make a note that we already found
7954 // a default here.
7955 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007956 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007957 break;
7958 } else {
7959 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007960 if (LIKELY(fill_tables)) {
7961 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7962 // Place method in imt if entry is empty, place conflict otherwise.
7963 SetIMTRef(unimplemented_method,
7964 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007965 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007966 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007967 /*out*/imt_ptr);
7968 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007969 break;
7970 }
7971 }
Alex Light9139e002015-10-09 15:59:48 -07007972 }
7973 // Continue on to the next method if we are done.
7974 if (LIKELY(found_impl)) {
7975 continue;
7976 } else if (LIKELY(super_interface)) {
7977 // Don't look for a default implementation when the super-method is implemented directly
7978 // by the class.
7979 //
7980 // See if we can use the superclasses method and skip searching everything else.
7981 // Note: !found_impl && super_interface
7982 CHECK(extend_super_iftable);
7983 // If this is a super_interface method it is possible we shouldn't override it because a
7984 // superclass could have implemented it directly. We get the method the superclass used
7985 // to implement this to know if we can override it with a default method. Doing this is
7986 // safe since we know that the super_iftable is filled in so we can simply pull it from
7987 // there. We don't bother if this is not a super-classes interface since in that case we
7988 // have scanned the entire vtable anyway and would have found it.
7989 // TODO This is rather dirty but it is faster than searching through the entire vtable
7990 // every time.
7991 ArtMethod* supers_method =
7992 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7993 DCHECK(supers_method != nullptr);
7994 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007995 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007996 // The method is not overridable by a default method (i.e. it is directly implemented
7997 // in some class). Therefore move onto the next interface method.
7998 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007999 } else {
8000 // If the super-classes method is override-able by a default method we need to keep
8001 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8002 // 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 -07008003 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8004 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8005 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008006 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008007 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8008 << " and not 'nullptr' or "
8009 << supers_method->PrettyMethod()
8010 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008011 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008012 }
8013 }
8014 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008015 ArtMethod* current_method = helper.FindMethod(interface_method,
8016 interface_name_comparator,
8017 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008018 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008019 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008020 // We could not find an implementation for this method and since it is a brand new
8021 // interface we searched the entire vtable (and all default methods) for an
8022 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008023 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8024 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008025 }
8026
8027 if (current_method != nullptr) {
8028 // We found a default method implementation. Record it in the iftable and IMT.
8029 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8030 SetIMTRef(unimplemented_method,
8031 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008032 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008033 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008034 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008035 }
8036 }
Alex Light705ad492015-09-21 11:36:30 -07008037 } // For each method in interface end.
8038 } // if (num_methods > 0)
8039 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008040 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008041 if (helper.HasNewVirtuals()) {
8042 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8043 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8044 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8045
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008046 // 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 -07008047 // suspension assert.
8048 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008049
Alex Light705ad492015-09-21 11:36:30 -07008050 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008051 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008052 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008053 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008054 return false;
8055 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008056 helper.UpdateIfTable(iftable);
8057 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008058 }
Alex Light705ad492015-09-21 11:36:30 -07008059
Vladimir Marko921094a2017-01-12 18:37:06 +00008060 helper.CheckNoStaleMethodsInDexCache();
8061 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008062 } else {
8063 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008064 }
Alex Light705ad492015-09-21 11:36:30 -07008065 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008066 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008067 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008068 return true;
8069}
8070
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008071bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008072 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008073 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008074}
8075
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008076bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008077 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008078 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008079}
8080
Brian Carlstromdbc05252011-09-09 01:59:59 -07008081struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008082 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008083 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008084 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008085 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008086 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008087 // 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 -07008088 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8089 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008090 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008091 if (type1 == Primitive::kPrimNot) {
8092 // Reference always goes first.
8093 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008094 }
Vladimir Markod5777482014-11-12 17:02:02 +00008095 if (type2 == Primitive::kPrimNot) {
8096 // Reference always goes first.
8097 return false;
8098 }
8099 size_t size1 = Primitive::ComponentSize(type1);
8100 size_t size2 = Primitive::ComponentSize(type2);
8101 if (size1 != size2) {
8102 // Larger primitive types go first.
8103 return size1 > size2;
8104 }
8105 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8106 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008107 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008108 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8109 // by name and for equal names by type id index.
8110 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8111 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008112 }
8113};
8114
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008115bool ClassLinker::LinkFields(Thread* self,
8116 Handle<mirror::Class> klass,
8117 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008118 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008119 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008120 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008121 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8122 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008123
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008124 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008125 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008126 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008127 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008128 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008129 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008130 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008131 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008132 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008133 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008134 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008135 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008136
David Sehr709b0702016-10-13 09:12:37 -07008137 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008138
Brian Carlstromdbc05252011-09-09 01:59:59 -07008139 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008140 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008141 //
8142 // The overall sort order order is:
8143 // 1) All object reference fields, sorted alphabetically.
8144 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8145 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8146 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8147 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8148 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8149 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8150 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8151 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8152 //
8153 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8154 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008155 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008156 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008157 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008158 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008159 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008160 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008161 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8162 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008163
Fred Shih381e4ca2014-08-25 17:24:27 -07008164 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008165 size_t current_field = 0;
8166 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008167 FieldGaps gaps;
8168
Brian Carlstromdbc05252011-09-09 01:59:59 -07008169 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008170 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008171 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008172 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008173 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008174 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008175 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008176 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8177 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008178 MemberOffset old_offset = field_offset;
8179 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8180 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8181 }
Roland Levillain14d90572015-07-16 10:52:26 +01008182 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008183 grouped_and_sorted_fields.pop_front();
8184 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008185 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008186 field_offset = MemberOffset(field_offset.Uint32Value() +
8187 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008188 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008189 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8190 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008191 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8192 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8193 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8194 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008195 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8196 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008197 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008198
Elliott Hughesadb460d2011-10-05 17:02:34 -07008199 // 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 -07008200 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008201 // We know there are no non-reference fields in the Reference classes, and we know
8202 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008203 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008204 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008205 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008206 --num_reference_fields;
8207 }
8208
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008209 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008210 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008211 if (is_static) {
8212 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008213 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008214 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008215 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008216 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008217 if (num_reference_fields == 0 || super_class == nullptr) {
8218 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008219 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008220 if (super_class == nullptr ||
8221 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8222 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008223 }
8224 }
8225 if (kIsDebugBuild) {
8226 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8227 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008228 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008229 while (cur_super != nullptr) {
8230 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8231 cur_super = cur_super->GetSuperClass();
8232 }
8233 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008234 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008235 } else {
8236 // Check that there is at least num_reference_fields other than Object.class.
8237 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008238 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008239 }
8240 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008241 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008242 std::string temp;
8243 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8244 size_t previous_size = klass->GetObjectSize();
8245 if (previous_size != 0) {
8246 // Make sure that we didn't originally have an incorrect size.
8247 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008248 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008249 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008250 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008251 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008252
8253 if (kIsDebugBuild) {
8254 // Make sure that the fields array is ordered by name but all reference
8255 // offsets are at the beginning as far as alignment allows.
8256 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008257 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008258 : klass->GetFirstReferenceInstanceFieldOffset();
8259 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8260 num_reference_fields *
8261 sizeof(mirror::HeapReference<mirror::Object>));
8262 MemberOffset current_ref_offset = start_ref_offset;
8263 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008264 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008265 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008266 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8267 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008268 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008269 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008270 // NOTE: The field names can be the same. This is not possible in the Java language
8271 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008272 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008273 }
8274 Primitive::Type type = field->GetTypeAsPrimitiveType();
8275 bool is_primitive = type != Primitive::kPrimNot;
8276 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8277 strcmp("referent", field->GetName()) == 0) {
8278 is_primitive = true; // We lied above, so we have to expect a lie here.
8279 }
8280 MemberOffset offset = field->GetOffsetDuringLinking();
8281 if (is_primitive) {
8282 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8283 // Shuffled before references.
8284 size_t type_size = Primitive::ComponentSize(type);
8285 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8286 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8287 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8288 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8289 }
8290 } else {
8291 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8292 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8293 sizeof(mirror::HeapReference<mirror::Object>));
8294 }
8295 }
8296 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8297 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008298 return true;
8299}
8300
Vladimir Marko76649e82014-11-10 18:32:59 +00008301// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008302void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008303 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008304 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008305 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008306 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008307 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008308 // Compute reference offsets unless our superclass overflowed.
8309 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8310 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008311 if (num_reference_fields != 0u) {
8312 // All of the fields that contain object references are guaranteed be grouped in memory
8313 // starting at an appropriately aligned address after super class object data.
8314 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8315 sizeof(mirror::HeapReference<mirror::Object>));
8316 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008317 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008318 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008319 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008320 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008321 reference_offsets |= (0xffffffffu << start_bit) &
8322 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008323 }
8324 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008325 }
8326 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008327 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008328}
8329
Vladimir Marko18090d12018-06-01 16:53:12 +01008330ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8331 ObjPtr<mirror::DexCache> dex_cache) {
8332 StackHandleScope<1> hs(Thread::Current());
8333 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8334 return DoResolveString(string_idx, h_dex_cache);
8335}
8336
8337ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8338 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008339 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008340 uint32_t utf16_length;
8341 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008342 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008343 if (string != nullptr) {
8344 dex_cache->SetResolvedString(string_idx, string);
8345 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008346 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008347}
8348
Vladimir Marko18090d12018-06-01 16:53:12 +01008349ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8350 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008351 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008352 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008353 uint32_t utf16_length;
8354 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008355 ObjPtr<mirror::String> string =
8356 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008357 if (string != nullptr) {
8358 dex_cache->SetResolvedString(string_idx, string);
8359 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008360 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008361}
8362
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008363ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008364 ObjPtr<mirror::Class> referrer) {
8365 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8366}
8367
8368ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008369 ObjPtr<mirror::DexCache> dex_cache,
8370 ObjPtr<mirror::ClassLoader> class_loader) {
8371 const DexFile& dex_file = *dex_cache->GetDexFile();
8372 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8373 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8374 ObjPtr<mirror::Class> type = nullptr;
8375 if (descriptor[1] == '\0') {
8376 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8377 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008378 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008379 } else {
8380 Thread* const self = Thread::Current();
8381 DCHECK(self != nullptr);
8382 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8383 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008384 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008385 }
8386 if (type != nullptr) {
8387 if (type->IsResolved()) {
8388 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008389 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008390 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008391 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008392 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008393 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008394}
8395
Andreas Gampe4835d212018-11-21 14:55:10 -08008396template <typename T>
8397ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008398 StackHandleScope<2> hs(Thread::Current());
8399 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8400 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8401 return DoResolveType(type_idx, dex_cache, class_loader);
8402}
8403
Andreas Gampe4835d212018-11-21 14:55:10 -08008404// Instantiate the above.
8405template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8406 ArtField* referrer);
8407template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8408 ArtMethod* referrer);
8409template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8410 ObjPtr<mirror::Class> referrer);
8411
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008412ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008413 Handle<mirror::DexCache> dex_cache,
8414 Handle<mirror::ClassLoader> class_loader) {
8415 Thread* self = Thread::Current();
8416 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8417 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8418 if (resolved != nullptr) {
8419 // TODO: we used to throw here if resolved's class loader was not the
8420 // boot class loader. This was to permit different classes with the
8421 // same name to be loaded simultaneously by different loaders
8422 dex_cache->SetResolvedType(type_idx, resolved);
8423 } else {
8424 CHECK(self->IsExceptionPending())
8425 << "Expected pending exception for failed resolution of: " << descriptor;
8426 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8427 StackHandleScope<1> hs(self);
8428 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008429 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008430 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8431 self->ClearException();
8432 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8433 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008434 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008435 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008436 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008437 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008438 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008439}
8440
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008441ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8442 ObjPtr<mirror::DexCache> dex_cache,
8443 ObjPtr<mirror::ClassLoader> class_loader,
8444 uint32_t method_idx) {
8445 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8446 // functions can optimize the search if the dex_cache is the same as the DexCache
8447 // of the class, with fall-back to name and signature search otherwise.
8448 ArtMethod* resolved = nullptr;
8449 if (klass->IsInterface()) {
8450 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8451 } else {
8452 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8453 }
8454 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008455 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008456 hiddenapi::ShouldDenyAccessToMember(resolved,
8457 hiddenapi::AccessContext(class_loader, dex_cache),
8458 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008459 resolved = nullptr;
8460 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008461 if (resolved != nullptr) {
8462 // In case of jmvti, the dex file gets verified before being registered, so first
8463 // check if it's registered before checking class tables.
8464 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008465 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8466 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008467 << "DexFile referrer: " << dex_file.GetLocation()
8468 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8469 // Be a good citizen and update the dex cache to speed subsequent calls.
8470 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008471 // Disable the following invariant check as the verifier breaks it. b/73760543
8472 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8473 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8474 // << "Method: " << resolved->PrettyMethod() << ", "
8475 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8476 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008477 }
8478 return resolved;
8479}
8480
David Brazdil4525e0b2018-04-05 16:57:32 +01008481// Returns true if `method` is either null or hidden.
8482// Does not print any warnings if it is hidden.
8483static bool CheckNoSuchMethod(ArtMethod* method,
8484 ObjPtr<mirror::DexCache> dex_cache,
8485 ObjPtr<mirror::ClassLoader> class_loader)
8486 REQUIRES_SHARED(Locks::mutator_lock_) {
8487 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008488 hiddenapi::ShouldDenyAccessToMember(method,
8489 hiddenapi::AccessContext(class_loader, dex_cache),
8490 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008491}
8492
8493ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8494 ObjPtr<mirror::DexCache> dex_cache,
8495 ObjPtr<mirror::ClassLoader> class_loader,
8496 uint32_t method_idx) {
8497 if (klass->IsInterface()) {
8498 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8499 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8500 } else {
8501 // If there was an interface method with the same signature, we would have
8502 // found it in the "copied" methods. Only DCHECK that the interface method
8503 // really does not exist.
8504 if (kIsDebugBuild) {
8505 ArtMethod* method =
8506 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8507 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8508 }
8509 return nullptr;
8510 }
8511}
8512
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008513template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008514ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008515 Handle<mirror::DexCache> dex_cache,
8516 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008517 ArtMethod* referrer,
8518 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008519 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008520 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008521 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008522 PointerSize pointer_size = image_pointer_size_;
8523 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008524 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008525 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8526 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008527 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8528 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008529 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008530 return resolved;
8531 }
Vladimir Marko89011192017-12-11 13:45:05 +00008532 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008533 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008534 ObjPtr<mirror::Class> klass = nullptr;
8535 if (valid_dex_cache_method) {
8536 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8537 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008538 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008539 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008540 // We normaly should not end up here. However the verifier currently doesn't guarantee
8541 // the invariant of having the klass in the class table. b/73760543
8542 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008543 }
Vladimir Markoba118822017-06-12 15:41:56 +01008544 } else {
8545 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008546 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008547 if (klass == nullptr) {
8548 DCHECK(Thread::Current()->IsExceptionPending());
8549 return nullptr;
8550 }
8551 }
8552
8553 // Check if the invoke type matches the class type.
8554 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008555 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008556 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008557 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008558 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008559 }
Vladimir Markoba118822017-06-12 15:41:56 +01008560
8561 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008562 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008563 }
Vladimir Markoba118822017-06-12 15:41:56 +01008564
8565 // Note: We can check for IllegalAccessError only if we have a referrer.
8566 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8567 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8568 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8569 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8570 resolved,
8571 dex_cache.Get(),
8572 method_idx,
8573 type)) {
8574 DCHECK(Thread::Current()->IsExceptionPending());
8575 return nullptr;
8576 }
8577 }
8578
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008579 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008580 if (LIKELY(resolved != nullptr) &&
8581 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8582 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008583 return resolved;
8584 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008585 // If we had a method, or if we can find one with another lookup type,
8586 // it's an incompatible-class-change error.
8587 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008588 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008589 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008590 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008591 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008592 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008593 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008594 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8595 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008596 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008597 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008598 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008599 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008601}
8602
Vladimir Marko89011192017-12-11 13:45:05 +00008603ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008604 Handle<mirror::DexCache> dex_cache,
8605 Handle<mirror::ClassLoader> class_loader) {
8606 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008607 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008608 if (resolved != nullptr) {
8609 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008610 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8611 return resolved;
8612 }
8613 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008614 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008615 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008616 if (klass == nullptr) {
8617 Thread::Current()->AssertPendingException();
8618 return nullptr;
8619 }
8620 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008621 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8622 } else {
8623 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008624 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008625 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008626 hiddenapi::ShouldDenyAccessToMember(
8627 resolved,
8628 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8629 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008630 resolved = nullptr;
8631 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008632 return resolved;
8633}
8634
Vladimir Markof44d36c2017-03-14 14:18:46 +00008635ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8636 ObjPtr<mirror::DexCache> dex_cache,
8637 ObjPtr<mirror::ClassLoader> class_loader,
8638 bool is_static) {
8639 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008640 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008641 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8642 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008643 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008644 }
8645 if (klass == nullptr) {
8646 // The class has not been resolved yet, so the field is also unresolved.
8647 return nullptr;
8648 }
8649 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008650
David Brazdil1ab0fa82018-05-04 11:28:03 +01008651 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008652}
8653
Vladimir Markoe11dd502017-12-08 14:09:45 +00008654ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008655 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008656 Handle<mirror::ClassLoader> class_loader,
8657 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008658 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008659 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008660 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008661 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008662 return resolved;
8663 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008664 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008665 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008666 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008667 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008668 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008669 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008670 }
8671
David Brazdil1ab0fa82018-05-04 11:28:03 +01008672 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008673 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008674 const char* name = dex_file.GetFieldName(field_id);
8675 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008676 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008677 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008678 return resolved;
8679}
8680
Vladimir Markoe11dd502017-12-08 14:09:45 +00008681ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008682 Handle<mirror::DexCache> dex_cache,
8683 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008684 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008685 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008686 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008687 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008688 return resolved;
8689 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008690 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008691 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008692 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008693 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008694 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008695 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008696 }
8697
David Brazdil1ab0fa82018-05-04 11:28:03 +01008698 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8699 if (resolved == nullptr) {
8700 const char* name = dex_file.GetFieldName(field_id);
8701 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008702 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008703 }
8704 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008705}
8706
David Brazdil1ab0fa82018-05-04 11:28:03 +01008707ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8708 ObjPtr<mirror::DexCache> dex_cache,
8709 ObjPtr<mirror::ClassLoader> class_loader,
8710 uint32_t field_idx,
8711 bool is_static) {
8712 ArtField* resolved = nullptr;
8713 Thread* self = is_static ? Thread::Current() : nullptr;
8714 const DexFile& dex_file = *dex_cache->GetDexFile();
8715
8716 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8717 : klass->FindInstanceField(dex_cache, field_idx);
8718
8719 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008720 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008721 const char* name = dex_file.GetFieldName(field_id);
8722 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8723 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8724 : klass->FindInstanceField(name, type);
8725 }
8726
8727 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008728 hiddenapi::ShouldDenyAccessToMember(resolved,
8729 hiddenapi::AccessContext(class_loader, dex_cache),
8730 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008731 resolved = nullptr;
8732 }
8733
8734 if (resolved != nullptr) {
8735 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8736 }
8737
8738 return resolved;
8739}
8740
8741ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8742 ObjPtr<mirror::DexCache> dex_cache,
8743 ObjPtr<mirror::ClassLoader> class_loader,
8744 uint32_t field_idx) {
8745 ArtField* resolved = nullptr;
8746 Thread* self = Thread::Current();
8747 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008748 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008749
8750 const char* name = dex_file.GetFieldName(field_id);
8751 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8752 resolved = mirror::Class::FindField(self, klass, name, type);
8753
8754 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008755 hiddenapi::ShouldDenyAccessToMember(resolved,
8756 hiddenapi::AccessContext(class_loader, dex_cache),
8757 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008758 resolved = nullptr;
8759 }
8760
8761 if (resolved != nullptr) {
8762 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8763 }
8764
8765 return resolved;
8766}
8767
Vladimir Markoaf940202017-12-08 15:01:18 +00008768ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8769 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008770 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008771 Handle<mirror::DexCache> dex_cache,
8772 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008773 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008774 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008775
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008776 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008777 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008778 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008779 }
8780
Narayan Kamath25352fc2016-08-03 12:46:58 +01008781 StackHandleScope<4> hs(self);
8782
8783 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008784 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008785 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008786 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008787 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008788 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008789 DCHECK(self->IsExceptionPending());
8790 return nullptr;
8791 }
8792
8793 // Then resolve the argument types.
8794 //
8795 // TODO: Is there a better way to figure out the number of method arguments
8796 // other than by looking at the shorty ?
8797 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8798
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008799 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008800 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8801 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008802 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008803 DCHECK(self->IsExceptionPending());
8804 return nullptr;
8805 }
8806
8807 DexFileParameterIterator it(dex_file, proto_id);
8808 int32_t i = 0;
8809 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8810 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008811 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008812 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008813 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008814 DCHECK(self->IsExceptionPending());
8815 return nullptr;
8816 }
8817
8818 method_params->Set(i++, param_class.Get());
8819 }
8820
8821 DCHECK(!it.HasNext());
8822
8823 Handle<mirror::MethodType> type = hs.NewHandle(
8824 mirror::MethodType::Create(self, return_type, method_params));
8825 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8826
8827 return type.Get();
8828}
8829
Vladimir Markoaf940202017-12-08 15:01:18 +00008830ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008831 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008832 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008833 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008834 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8835 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008836 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008837}
8838
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008839mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8840 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008841 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008842 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008843 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008844 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8845 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008846 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008847 bool is_static;
8848 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008849 switch (handle_type) {
8850 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008851 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008852 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008853 is_static = true;
8854 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008855 break;
8856 }
8857 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008858 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008859 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008860 is_static = true;
8861 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008862 break;
8863 }
8864 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008865 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008866 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008867 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008868 num_params = 2;
8869 break;
8870 }
8871 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008872 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008873 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008874 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008875 num_params = 1;
8876 break;
8877 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008878 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008879 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008880 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008881 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008882 case DexFile::MethodHandleType::kInvokeInterface:
8883 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008884 }
8885
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008886 ArtField* target_field =
8887 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8888 if (LIKELY(target_field != nullptr)) {
8889 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8890 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8891 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8892 ThrowIllegalAccessErrorField(referring_class, target_field);
8893 return nullptr;
8894 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008895 if (UNLIKELY(is_put && target_field->IsFinal())) {
8896 ThrowIllegalAccessErrorField(referring_class, target_field);
8897 return nullptr;
8898 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008899 } else {
8900 DCHECK(Thread::Current()->IsExceptionPending());
8901 return nullptr;
8902 }
8903
8904 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008905 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008906 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8907 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008908 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008909 DCHECK(self->IsExceptionPending());
8910 return nullptr;
8911 }
8912
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008913 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008914 Handle<mirror::Class> return_type;
8915 switch (handle_type) {
8916 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008917 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008918 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008919 break;
8920 }
8921 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008922 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008923 break;
8924 }
8925 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008926 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008927 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008928 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008929 break;
8930 }
8931 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008932 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008933 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008934 break;
8935 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008936 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008937 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008938 case DexFile::MethodHandleType::kInvokeConstructor:
8939 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008940 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008941 UNREACHABLE();
8942 }
8943
8944 for (int32_t i = 0; i < num_params; ++i) {
8945 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8946 DCHECK(self->IsExceptionPending());
8947 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008948 }
8949 }
8950
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008951 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008952 DCHECK(self->IsExceptionPending());
8953 return nullptr;
8954 }
8955
8956 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008957 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8958 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008959 DCHECK(self->IsExceptionPending());
8960 return nullptr;
8961 }
Orion Hodson631827d2017-04-10 14:53:47 +01008962
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008963 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8964 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8965}
8966
8967mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8968 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008969 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008970 ArtMethod* referrer) {
8971 DexFile::MethodHandleType handle_type =
8972 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8973 mirror::MethodHandle::Kind kind;
8974 uint32_t receiver_count = 0;
8975 ArtMethod* target_method = nullptr;
8976 switch (handle_type) {
8977 case DexFile::MethodHandleType::kStaticPut:
8978 case DexFile::MethodHandleType::kStaticGet:
8979 case DexFile::MethodHandleType::kInstancePut:
8980 case DexFile::MethodHandleType::kInstanceGet:
8981 UNREACHABLE();
8982 case DexFile::MethodHandleType::kInvokeStatic: {
8983 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8984 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008985 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8986 method_handle.field_or_method_idx_,
8987 referrer,
8988 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008989 break;
8990 }
8991 case DexFile::MethodHandleType::kInvokeInstance: {
8992 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8993 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008994 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8995 method_handle.field_or_method_idx_,
8996 referrer,
8997 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008998 break;
8999 }
9000 case DexFile::MethodHandleType::kInvokeConstructor: {
9001 // Constructors are currently implemented as a transform. They
9002 // are special cased later in this method.
9003 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9004 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009005 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9006 method_handle.field_or_method_idx_,
9007 referrer,
9008 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009009 break;
9010 }
9011 case DexFile::MethodHandleType::kInvokeDirect: {
9012 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9013 receiver_count = 1;
9014 StackHandleScope<2> hs(self);
9015 // A constant method handle with type kInvokeDirect can refer to
9016 // a method that is private or to a method in a super class. To
9017 // disambiguate the two options, we resolve the method ignoring
9018 // the invocation type to determine if the method is private. We
9019 // then resolve again specifying the intended invocation type to
9020 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009021 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009022 hs.NewHandle(referrer->GetDexCache()),
9023 hs.NewHandle(referrer->GetClassLoader()));
9024 if (UNLIKELY(target_method == nullptr)) {
9025 break;
9026 }
9027
9028 if (target_method->IsPrivate()) {
9029 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009030 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9031 method_handle.field_or_method_idx_,
9032 referrer,
9033 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009034 } else {
9035 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009036 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9037 method_handle.field_or_method_idx_,
9038 referrer,
9039 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009040 if (UNLIKELY(target_method == nullptr)) {
9041 break;
9042 }
9043 // Find the method specified in the parent in referring class
9044 // so invoke-super invokes the method in the parent of the
9045 // referrer.
9046 target_method =
9047 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9048 kRuntimePointerSize);
9049 }
9050 break;
9051 }
9052 case DexFile::MethodHandleType::kInvokeInterface: {
9053 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9054 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009055 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9056 method_handle.field_or_method_idx_,
9057 referrer,
9058 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009059 break;
9060 }
Orion Hodson631827d2017-04-10 14:53:47 +01009061 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009062
9063 if (UNLIKELY(target_method == nullptr)) {
9064 DCHECK(Thread::Current()->IsExceptionPending());
9065 return nullptr;
9066 }
9067
9068 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9069 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9070 uint32_t access_flags = target_method->GetAccessFlags();
9071 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9072 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9073 return nullptr;
9074 }
9075
9076 // Calculate the number of parameters from the method shorty. We add the
9077 // receiver count (0 or 1) and deduct one for the return value.
9078 uint32_t shorty_length;
9079 target_method->GetShorty(&shorty_length);
9080 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9081
Orion Hodsonecd58562018-09-24 11:27:33 +01009082 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009083 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009084 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9085 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9086 if (method_params.Get() == nullptr) {
9087 DCHECK(self->IsExceptionPending());
9088 return nullptr;
9089 }
9090
Orion Hodsonecd58562018-09-24 11:27:33 +01009091 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009092 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009093 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009094 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009095 // Insert receiver. Use the class identified in the method handle rather than the declaring
9096 // class of the resolved method which may be super class or default interface method
9097 // (b/115964401).
9098 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9099 // receiver_class should have been resolved when resolving the target method.
9100 DCHECK(receiver_class != nullptr);
9101 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009102 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009103
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009104 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009105 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009106 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009107 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009108 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009109 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009110 if (nullptr == klass) {
9111 DCHECK(self->IsExceptionPending());
9112 return nullptr;
9113 }
9114 method_params->Set(index++, klass);
9115 it.Next();
9116 }
9117
Orion Hodsonecd58562018-09-24 11:27:33 +01009118 Handle<mirror::Class> return_type =
9119 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009120 if (UNLIKELY(return_type.IsNull())) {
9121 DCHECK(self->IsExceptionPending());
9122 return nullptr;
9123 }
9124
9125 Handle<mirror::MethodType>
9126 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9127 if (UNLIKELY(method_type.IsNull())) {
9128 DCHECK(self->IsExceptionPending());
9129 return nullptr;
9130 }
9131
9132 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9133 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9134 Handle<mirror::MethodHandlesLookup> lookup =
9135 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9136 return lookup->FindConstructor(self, constructor_class, method_type);
9137 }
9138
9139 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9140 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9141}
9142
Vladimir Markoaf940202017-12-08 15:01:18 +00009143ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9144 uint32_t method_handle_idx,
9145 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009146 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009147 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009148 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009149 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9150 case DexFile::MethodHandleType::kStaticPut:
9151 case DexFile::MethodHandleType::kStaticGet:
9152 case DexFile::MethodHandleType::kInstancePut:
9153 case DexFile::MethodHandleType::kInstanceGet:
9154 return ResolveMethodHandleForField(self, method_handle, referrer);
9155 case DexFile::MethodHandleType::kInvokeStatic:
9156 case DexFile::MethodHandleType::kInvokeInstance:
9157 case DexFile::MethodHandleType::kInvokeConstructor:
9158 case DexFile::MethodHandleType::kInvokeDirect:
9159 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009160 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009161 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009162}
9163
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009164bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9165 return (entry_point == GetQuickResolutionStub()) ||
9166 (quick_resolution_trampoline_ == entry_point);
9167}
9168
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009169bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9170 return (entry_point == GetQuickToInterpreterBridge()) ||
9171 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9172}
9173
9174bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9175 return (entry_point == GetQuickGenericJniStub()) ||
9176 (quick_generic_jni_trampoline_ == entry_point);
9177}
9178
David Sehra49e0532017-08-25 08:05:29 -07009179bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9180 return entry_point == GetJniDlsymLookupStub();
9181}
9182
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009183const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9184 return GetQuickGenericJniStub();
9185}
9186
Mathieu Chartiere401d142015-04-22 13:56:20 -07009187void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009188 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009189 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9190 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009191 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009192 }
9193}
9194
Alex Lightdb01a092017-04-03 15:39:55 -07009195void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9196 DCHECK(method->IsObsolete());
9197 // We cannot mess with the entrypoints of native methods because they are used to determine how
9198 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9199 if (!method->IsNative()) {
9200 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9201 }
9202}
9203
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009204void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009205 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009206 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009207 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9208 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009209 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9210 os << "Dumping registered class loaders\n";
9211 size_t class_loader_index = 0;
9212 for (const ClassLoaderData& class_loader : class_loaders_) {
9213 ObjPtr<mirror::ClassLoader> loader =
9214 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9215 if (loader != nullptr) {
9216 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9217 bool saw_one_dex_file = false;
9218 for (const DexCacheData& dex_cache : dex_caches_) {
9219 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9220 if (saw_one_dex_file) {
9221 os << ":";
9222 }
9223 saw_one_dex_file = true;
9224 os << dex_cache.dex_file->GetLocation();
9225 }
9226 }
9227 os << "]";
9228 bool found_parent = false;
9229 if (loader->GetParent() != nullptr) {
9230 size_t parent_index = 0;
9231 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9232 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9233 soa.Self()->DecodeJObject(class_loader2.weak_root));
9234 if (loader2 == loader->GetParent()) {
9235 os << ", parent #" << parent_index;
9236 found_parent = true;
9237 break;
9238 }
9239 parent_index++;
9240 }
9241 if (!found_parent) {
9242 os << ", unregistered parent of type "
9243 << loader->GetParent()->GetClass()->PrettyDescriptor();
9244 }
9245 } else {
9246 os << ", no parent";
9247 }
9248 os << "\n";
9249 }
9250 }
9251 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009252}
9253
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009254class CountClassesVisitor : public ClassLoaderVisitor {
9255 public:
9256 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9257
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009258 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009259 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009260 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009261 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009262 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9263 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009264 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009265 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009266
9267 size_t num_zygote_classes;
9268 size_t num_non_zygote_classes;
9269};
9270
9271size_t ClassLinker::NumZygoteClasses() const {
9272 CountClassesVisitor visitor;
9273 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009274 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009275}
9276
9277size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009278 CountClassesVisitor visitor;
9279 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009280 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009281}
9282
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009283size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009284 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009285 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009286 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009287}
9288
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009289pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009290 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009291}
9292
9293pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009294 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009295}
9296
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009297void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009298 DCHECK(!init_done_);
9299
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009300 DCHECK(klass != nullptr);
9301 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009302
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009303 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009304 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009305 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9306 int32_t index = static_cast<int32_t>(class_root);
9307 DCHECK(class_roots->Get(index) == nullptr);
9308 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009309}
9310
Roland Levillain0e840272018-08-23 19:55:30 +01009311void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9312 ObjPtr<mirror::Class> java_lang_Class,
9313 ClassRoot primitive_array_class_root,
9314 ClassRoot primitive_class_root,
9315 const char* descriptor) {
9316 StackHandleScope<1> hs(self);
9317 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9318 AllocPrimitiveArrayClass(self, java_lang_Class)));
9319 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9320 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9321 CheckSystemClass(self, primitive_array_class, descriptor);
9322}
9323
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009324ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9325 Thread* self,
9326 const std::vector<const DexFile*>& dex_files,
9327 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009328 Handle<mirror::ClassLoader> parent_loader,
9329 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009330
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009331 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009332
Mathieu Chartierc7853442015-03-27 14:35:38 -07009333 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009334 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009335
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009336 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009337 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009338 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009339 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009340 mirror::ObjectArray<mirror::Object>::Alloc(self,
9341 dex_elements_class.Get(),
9342 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009343 Handle<mirror::Class> h_dex_element_class =
9344 hs.NewHandle(dex_elements_class->GetComponentType());
9345
Mathieu Chartierc7853442015-03-27 14:35:38 -07009346 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009347 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009348 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009349
Andreas Gampe08883de2016-11-08 13:20:52 -08009350 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009351 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009352
Andreas Gampe08883de2016-11-08 13:20:52 -08009353 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009354 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009355
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009356 // Fill the elements array.
9357 int32_t index = 0;
9358 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009359 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009360
Calin Juravle7865ac72017-06-28 11:03:12 -07009361 // CreateWellKnownClassLoader is only used by gtests and compiler.
9362 // 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 -07009363 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9364 self,
9365 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009366 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009367 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009368
Mathieu Chartier3738e982017-05-12 16:07:28 -07009369 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9370 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009371 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009372 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009373 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009374 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009375
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009376 Handle<mirror::String> h_file_name = hs2.NewHandle(
9377 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009378 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009379 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9380
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009381 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009382 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009383 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009384
9385 h_dex_elements->Set(index, h_element.Get());
9386 index++;
9387 }
9388 DCHECK_EQ(index, h_dex_elements->GetLength());
9389
9390 // Create DexPathList.
9391 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009392 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009393 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009394 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009395 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009396 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9397 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9398 // elements.
9399 {
9400 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9401 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9402 DCHECK(native_lib_dirs != nullptr);
9403 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9404 DCHECK(list_class != nullptr);
9405 {
9406 StackHandleScope<1> h_list_scope(self);
9407 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9408 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9409 DCHECK(list_init);
9410 list_class = h_list_class.Get();
9411 }
9412 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9413 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9414 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9415 // normally never null), as long as one does not try to add elements, this will still
9416 // work.
9417 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9418 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009419
Calin Juravle7865ac72017-06-28 11:03:12 -07009420 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009421 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9422 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009423 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009424 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009425 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009426 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009427 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009428 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009429
9430 // Make a pretend boot-classpath.
9431 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009432 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009433 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009434 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009435 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009436 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009437 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009438 if (parent_loader.Get() == nullptr) {
9439 ScopedObjectAccessUnchecked soa(self);
9440 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9441 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9442 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9443 } else {
9444 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9445 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009446
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009447 ArtField* shared_libraries_field =
9448 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9449 DCHECK(shared_libraries_field != nullptr);
9450 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9451
9452 return h_class_loader.Get();
9453}
9454
9455jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9456 const std::vector<const DexFile*>& dex_files,
9457 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009458 jobject parent_loader,
9459 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009460 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9461 WellKnownClasses::dalvik_system_PathClassLoader) ||
9462 self->GetJniEnv()->IsSameObject(loader_class,
9463 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
9464
9465 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9466 // We could move the jobject to the callers, but all call-sites do this...
9467 ScopedObjectAccessUnchecked soa(self);
9468
9469 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009470 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009471
9472 Handle<mirror::Class> h_loader_class =
9473 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009474 Handle<mirror::ClassLoader> h_parent =
9475 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9476 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9477 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009478
9479 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9480 self,
9481 dex_files,
9482 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009483 h_parent,
9484 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009485
9486 // Make it a global ref and return.
9487 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009488 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009489 return soa.Env()->NewGlobalRef(local_ref.get());
9490}
9491
Calin Juravle7865ac72017-06-28 11:03:12 -07009492jobject ClassLinker::CreatePathClassLoader(Thread* self,
9493 const std::vector<const DexFile*>& dex_files) {
9494 return CreateWellKnownClassLoader(self,
9495 dex_files,
9496 WellKnownClasses::dalvik_system_PathClassLoader,
9497 nullptr);
9498}
9499
Andreas Gampe8ac75952015-06-02 21:01:45 -07009500void ClassLinker::DropFindArrayClassCache() {
9501 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9502 find_array_class_cache_next_victim_ = 0;
9503}
9504
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009505void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009506 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009507 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009508 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009509 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9510 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009511 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009512 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009513 }
9514 }
9515}
9516
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009517void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9518 for (const ClassLoaderData& data : class_loaders_) {
9519 LinearAlloc* alloc = data.allocator;
9520 if (alloc != nullptr && !visitor->Visit(alloc)) {
9521 break;
9522 }
9523 }
9524}
9525
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009526void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9527 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009528 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009529 Thread* const self = Thread::Current();
9530 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009531 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009532 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009533 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009534 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9535 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009536 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009537 }
9538}
9539
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009540void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009541 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009542 std::vector<ClassLoaderData> to_delete;
9543 // Do the delete outside the lock to avoid lock violation in jit code cache.
9544 {
9545 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9546 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9547 const ClassLoaderData& data = *it;
9548 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009549 ObjPtr<mirror::ClassLoader> class_loader =
9550 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009551 if (class_loader != nullptr) {
9552 ++it;
9553 } else {
9554 VLOG(class_linker) << "Freeing class loader";
9555 to_delete.push_back(data);
9556 it = class_loaders_.erase(it);
9557 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009558 }
9559 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009560 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009561 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009562 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009563 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009564}
9565
Vladimir Marko21300532017-01-24 18:06:55 +00009566class GetResolvedClassesVisitor : public ClassVisitor {
9567 public:
9568 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9569 : result_(result),
9570 ignore_boot_classes_(ignore_boot_classes),
9571 last_resolved_classes_(result->end()),
9572 last_dex_file_(nullptr),
9573 vlog_is_on_(VLOG_IS_ON(class_linker)),
9574 extra_stats_(),
9575 last_extra_stats_(extra_stats_.end()) { }
9576
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009577 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009578 if (!klass->IsProxyClass() &&
9579 !klass->IsArrayClass() &&
9580 klass->IsResolved() &&
9581 !klass->IsErroneousResolved() &&
9582 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9583 const DexFile& dex_file = klass->GetDexFile();
9584 if (&dex_file != last_dex_file_) {
9585 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009586 DexCacheResolvedClasses resolved_classes(
9587 dex_file.GetLocation(),
9588 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9589 dex_file.GetLocationChecksum(),
9590 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009591 last_resolved_classes_ = result_->find(resolved_classes);
9592 if (last_resolved_classes_ == result_->end()) {
9593 last_resolved_classes_ = result_->insert(resolved_classes).first;
9594 }
9595 }
9596 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9597 if (UNLIKELY(vlog_is_on_) && added) {
9598 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9599 if (last_extra_stats_ == extra_stats_.end() ||
9600 last_extra_stats_->first != resolved_classes) {
9601 last_extra_stats_ = extra_stats_.find(resolved_classes);
9602 if (last_extra_stats_ == extra_stats_.end()) {
9603 last_extra_stats_ =
9604 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9605 }
9606 }
9607 }
9608 }
9609 return true;
9610 }
9611
9612 void PrintStatistics() const {
9613 if (vlog_is_on_) {
9614 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9615 auto it = extra_stats_.find(std::addressof(resolved_classes));
9616 DCHECK(it != extra_stats_.end());
9617 const ExtraStats& extra_stats = it->second;
9618 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9619 << " has " << resolved_classes.GetClasses().size() << " / "
9620 << extra_stats.number_of_class_defs_ << " resolved classes";
9621 }
9622 }
9623 }
9624
9625 private:
9626 struct ExtraStats {
9627 explicit ExtraStats(uint32_t number_of_class_defs)
9628 : number_of_class_defs_(number_of_class_defs) {}
9629 uint32_t number_of_class_defs_;
9630 };
9631
9632 std::set<DexCacheResolvedClasses>* result_;
9633 bool ignore_boot_classes_;
9634 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9635 const DexFile* last_dex_file_;
9636
9637 // Statistics.
9638 bool vlog_is_on_;
9639 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9640 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9641};
9642
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009643std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009644 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009645 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009646 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009647 std::set<DexCacheResolvedClasses> ret;
9648 VLOG(class_linker) << "Collecting resolved classes";
9649 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009650 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9651 VisitClasses(&visitor);
9652 if (VLOG_IS_ON(class_linker)) {
9653 visitor.PrintStatistics();
9654 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009655 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009656 return ret;
9657}
9658
Mathieu Chartier65975772016-08-05 10:46:36 -07009659class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9660 public:
9661 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9662 : method_(method),
9663 pointer_size_(pointer_size) {}
9664
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009665 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009666 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9667 holder_ = klass;
9668 }
9669 // Return false to stop searching if holder_ is not null.
9670 return holder_ == nullptr;
9671 }
9672
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009673 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009674 const ArtMethod* const method_;
9675 const PointerSize pointer_size_;
9676};
9677
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009678ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009679 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9680 CHECK(method->IsCopied());
9681 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9682 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009683 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009684}
9685
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009686ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9687 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009688 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009689 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009690 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009691}
9692
Roland Levillain0e840272018-08-23 19:55:30 +01009693// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009694template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009695 uint32_t method_idx,
9696 Handle<mirror::DexCache> dex_cache,
9697 Handle<mirror::ClassLoader> class_loader,
9698 ArtMethod* referrer,
9699 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009700template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009701 uint32_t method_idx,
9702 Handle<mirror::DexCache> dex_cache,
9703 Handle<mirror::ClassLoader> class_loader,
9704 ArtMethod* referrer,
9705 InvokeType type);
9706
Roland Levillain0e840272018-08-23 19:55:30 +01009707// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009708template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009709 Thread* self,
9710 ObjPtr<mirror::Class> java_lang_Class,
9711 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009712template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009713 Thread* self,
9714 ObjPtr<mirror::Class> java_lang_Class,
9715 uint32_t class_size);
9716
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009717} // namespace art