blob: 46ae545e073ff45e92b0973090b36d050dbdbeda [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"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800136#include "verifier/method_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()) {
903 verifier::MethodVerifier::Init(); // Need to prepare the verifier.
904
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 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700976 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800977 if (!runtime->IsAotCompiler()) {
978 // Only the Aot compiler supports having an image with a different pointer size than the
979 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
980 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700981 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800982 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700983 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800984 sizeof(void*));
985 return false;
986 }
987 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800988 std::vector<const OatFile*> oat_files =
989 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
990 DCHECK(!oat_files.empty());
991 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800992 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
993 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
994 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
995 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
996 if (kIsDebugBuild) {
997 // Check that the other images use the same trampoline.
998 for (size_t i = 1; i < oat_files.size(); ++i) {
999 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1000 const void* ith_quick_resolution_trampoline =
1001 ith_oat_header.GetQuickResolutionTrampoline();
1002 const void* ith_quick_imt_conflict_trampoline =
1003 ith_oat_header.GetQuickImtConflictTrampoline();
1004 const void* ith_quick_generic_jni_trampoline =
1005 ith_oat_header.GetQuickGenericJniTrampoline();
1006 const void* ith_quick_to_interpreter_bridge_trampoline =
1007 ith_oat_header.GetQuickToInterpreterBridge();
1008 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1009 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1010 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1011 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1012 // Make sure that all methods in this image do not contain those trampolines as
1013 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1014 TrampolineCheckData data;
1015 data.error = false;
1016 data.pointer_size = GetImagePointerSize();
1017 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1018 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1019 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1020 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1021 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001022 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1023 if (obj->IsClass()) {
1024 ObjPtr<mirror::Class> klass = obj->AsClass();
1025 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1026 const void* entrypoint =
1027 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1028 if (entrypoint == data.quick_resolution_trampoline ||
1029 entrypoint == data.quick_imt_conflict_trampoline ||
1030 entrypoint == data.quick_generic_jni_trampoline ||
1031 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1032 data.m = &m;
1033 data.error = true;
1034 return;
1035 }
1036 }
1037 }
1038 };
1039 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001040 if (data.error) {
1041 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001042 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001043 *error_msg = "Found an ArtMethod with a bad entrypoint";
1044 return false;
1045 }
1046 }
1047 }
1048 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001049
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001050 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001051 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1052 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001053 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001054
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001055 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001056 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001057 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1058 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001059 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1060 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001061
Vladimir Marko4433c432018-12-04 14:57:47 +00001062 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1063 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001064 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001065 // Boot class loader, use a null handle.
1066 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001067 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001068 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001069 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001070 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001071 /*out*/&dex_files,
1072 error_msg)) {
1073 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 // Append opened dex files at the end.
1076 boot_dex_files_.insert(boot_dex_files_.end(),
1077 std::make_move_iterator(dex_files.begin()),
1078 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001079 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001080 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1081 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1082 }
Ian Rogers98379392014-02-24 16:53:16 -08001083 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001084
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001085 VLOG(startup) << __FUNCTION__ << " exiting";
1086 return true;
1087}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001088
Vladimir Marko4433c432018-12-04 14:57:47 +00001089void ClassLinker::AddExtraBootDexFiles(
1090 Thread* self,
1091 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1092 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1093 AppendToBootClassPath(self, *dex_file);
1094 boot_dex_files_.push_back(std::move(dex_file));
1095 }
1096}
1097
Jeff Hao5872d7c2016-04-27 11:07:41 -07001098bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001099 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001100 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001101 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1102 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001103}
1104
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001105static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1106 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001107 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001108 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001109 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001111 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112 DCHECK(dex_file_field != nullptr);
1113 DCHECK(dex_file_name_field != nullptr);
1114 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001115 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001116 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001118 // Null dex file means it was probably a jar with no dex files, return a null string.
1119 *out_name = nullptr;
1120 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001121 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001122 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001123 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001124 *out_name = name_object->AsString();
1125 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001127 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128}
1129
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001130static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1131 ObjPtr<mirror::ClassLoader> class_loader,
1132 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1133 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001134 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001135 StackHandleScope<1> hs(soa.Self());
1136 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001137 // Get element names. Sets error to true on failure.
1138 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1139 REQUIRES_SHARED(Locks::mutator_lock_) {
1140 if (element == nullptr) {
1141 *error_msg = "Null dex element";
1142 *error = true; // Null element is a critical error.
1143 return false; // Had an error, stop the visit.
1144 }
1145 ObjPtr<mirror::String> name;
1146 if (!GetDexPathListElementName(element, &name)) {
1147 *error_msg = "Invalid dex path list element";
1148 *error = true; // Invalid element, make it a critical error.
1149 return false; // Stop the visit.
1150 }
1151 if (name != nullptr) {
1152 dex_files->push_front(name);
1153 }
1154 return true; // Continue with the next Element.
1155 };
1156 bool error = VisitClassLoaderDexElements(soa,
1157 handle,
1158 add_element_names,
1159 /*defaultReturn=*/ false);
1160 return !error;
1161}
1162
1163static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1164 ObjPtr<mirror::ClassLoader> image_class_loader,
1165 ObjPtr<mirror::ClassLoader> class_loader,
1166 std::string* error_msg)
1167 REQUIRES_SHARED(Locks::mutator_lock_) {
1168 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1169 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1170 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001171 return false;
1172 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001173 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1174 *error_msg = "Hierarchies don't match";
1175 return false;
1176 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1177 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1178 image_class_loader->PrettyTypeOf().c_str(),
1179 class_loader->PrettyTypeOf().c_str());
1180 return false;
1181 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1182 class_loader->GetClass()) {
1183 *error_msg = StringPrintf("Unknown class loader type %s",
1184 class_loader->PrettyTypeOf().c_str());
1185 // Unsupported class loader.
1186 return false;
1187 }
1188 return true;
1189}
1190
1191static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1192 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1193 std::string* error_msg)
1194 REQUIRES_SHARED(Locks::mutator_lock_) {
1195 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1196 std::equal(image_dex_files.begin(),
1197 image_dex_files.end(),
1198 loader_dex_files.begin(),
1199 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1200 REQUIRES_SHARED(Locks::mutator_lock_) {
1201 return lhs->Equals(rhs);
1202 });
1203 if (!equal) {
1204 VLOG(image) << "Image dex files " << image_dex_files.size();
1205 for (ObjPtr<mirror::String> name : image_dex_files) {
1206 VLOG(image) << name->ToModifiedUtf8();
1207 }
1208 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1209 for (ObjPtr<mirror::String> name : loader_dex_files) {
1210 VLOG(image) << name->ToModifiedUtf8();
1211 }
1212 *error_msg = "Mismatch in dex files";
1213 }
1214 return equal;
1215}
1216
1217static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1218 ObjPtr<mirror::ClassLoader> image_class_loader,
1219 ObjPtr<mirror::ClassLoader> class_loader,
1220 bool check_dex_file_names,
1221 std::string* error_msg)
1222 REQUIRES_SHARED(Locks::mutator_lock_) {
1223 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1224 return false;
1225 }
1226
1227 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1228 // No need to check further.
1229 return true;
1230 }
1231
1232 if (check_dex_file_names) {
1233 std::list<ObjPtr<mirror::String>> image_dex_files;
1234 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001235 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001236 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001237
1238 std::list<ObjPtr<mirror::String>> loader_dex_files;
1239 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1240 return false;
1241 }
1242
1243 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1244 return false;
1245 }
1246 }
1247
1248 ArtField* field =
1249 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1250 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1251 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1252 if (shared_libraries_image_loader == nullptr) {
1253 if (shared_libraries_loader != nullptr) {
1254 *error_msg = "Mismatch in shared libraries";
1255 return false;
1256 }
1257 } else if (shared_libraries_loader == nullptr) {
1258 *error_msg = "Mismatch in shared libraries";
1259 return false;
1260 } else {
1261 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1262 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1263 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1264 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1265 if (array1->GetLength() != array2->GetLength()) {
1266 *error_msg = "Mismatch in number of shared libraries";
1267 return false;
1268 }
1269
1270 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1271 // Do a full comparison of the class loaders, including comparing their dex files.
1272 if (!CompareClassLoaders(soa,
1273 array1->Get(i),
1274 array2->Get(i),
1275 /*check_dex_file_names=*/ true,
1276 error_msg)) {
1277 return false;
1278 }
1279 }
1280 }
1281
1282 // Do a full comparison of the class loaders, including comparing their dex files.
1283 if (!CompareClassLoaders(soa,
1284 image_class_loader->GetParent(),
1285 class_loader->GetParent(),
1286 /*check_dex_file_names=*/ true,
1287 error_msg)) {
1288 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 }
1290 return true;
1291}
1292
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001293class CHAOnDeleteUpdateClassVisitor {
1294 public:
1295 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1296 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1297 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1298 self_(Thread::Current()) {}
1299
1300 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1301 // This class is going to be unloaded. Tell CHA about it.
1302 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1303 return true;
1304 }
1305 private:
1306 const LinearAlloc* allocator_;
1307 const ClassHierarchyAnalysis* cha_;
1308 const PointerSize pointer_size_;
1309 const Thread* self_;
1310};
1311
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001312class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1313 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001314 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001315 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1316
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001317 void Visit(ArtMethod* method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001318 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001319 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001320 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001321 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001322 }
1323 }
1324
1325 private:
1326 gc::accounting::HeapBitmap* const live_bitmap_;
1327};
1328
Chris Wailes0c61be42018-09-26 17:27:34 -07001329/*
1330 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001331 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001332 */
1333class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001334 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001335 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001336 space_(space),
1337 intern_table_(*Runtime::Current()->GetInternTable()) {}
1338
Chris Wailes0c61be42018-09-26 17:27:34 -07001339 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001340 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001341 if (referred_obj != nullptr &&
1342 space_.HasAddress(referred_obj.Ptr()) &&
1343 referred_obj->IsString()) {
1344 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001345
1346 if (kIsDebugBuild) {
1347 // Saved to temporary variables to aid in debugging.
1348 ObjPtr<mirror::String> strong_lookup_result =
1349 intern_table_.LookupStrong(Thread::Current(), referred_str);
1350 ObjPtr<mirror::String> weak_lookup_result =
1351 intern_table_.LookupWeak(Thread::Current(), referred_str);
1352
1353 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1354 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001355 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001356 }
1357
Chris Wailes0c61be42018-09-26 17:27:34 -07001358 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001359 mirror::CompressedReference<mirror::Object>* root) const
1360 REQUIRES_SHARED(Locks::mutator_lock_) {
1361 if (!root->IsNull()) {
1362 VisitRoot(root);
1363 }
1364 }
1365
Chris Wailes0c61be42018-09-26 17:27:34 -07001366 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001367 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001368 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001369 }
1370
1371 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001372 void operator()(ObjPtr<mirror::Object> obj,
1373 MemberOffset offset,
1374 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001375 REQUIRES_SHARED(Locks::mutator_lock_) {
1376 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1377 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1378 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1379 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001380 ObjPtr<mirror::Object> referred_obj =
1381 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1382
1383 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001384 }
1385 }
1386
1387 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1388 ObjPtr<mirror::Reference> ref) const
1389 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001390 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001391 }
1392
Chris Wailes0c61be42018-09-26 17:27:34 -07001393 const gc::space::ImageSpace& space_;
1394 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001395};
1396
Chris Wailes0c61be42018-09-26 17:27:34 -07001397/*
1398 * This function verifies that string references in the AppImage have been
1399 * properly interned. To be considered properly interned a reference must
1400 * point to the same version of the string that the intern table does.
1401 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001402void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001403 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1404 const ImageHeader& image_header = space.GetImageHeader();
1405 const uint8_t* target_base = space.GetMemMap()->Begin();
1406 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001407
1408 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1409 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001410
1411 VerifyStringInterningVisitor visitor(space);
1412 bitmap->VisitMarkedRange(objects_begin,
1413 objects_end,
1414 [&space, &visitor](mirror::Object* obj)
1415 REQUIRES_SHARED(Locks::mutator_lock_) {
1416 if (space.HasAddress(obj)) {
1417 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001418 obj->VisitReferences</* kVisitNativeRoots= */ true,
1419 kVerifyNone,
1420 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001421 } else {
1422 // Don't visit native roots for non-dex-cache as they can't contain
1423 // native references to strings. This is verified during compilation
1424 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001425 obj->VisitReferences</* kVisitNativeRoots= */ false,
1426 kVerifyNone,
1427 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001428 }
1429 }
1430 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001431}
1432
Andreas Gampe2af99022017-04-25 08:32:59 -07001433// new_class_set is the set of classes that were read from the class table section in the image.
1434// If there was no class table section, it is null.
1435// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001436class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001437 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001438 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001439 ClassLinker* class_linker,
1440 gc::space::ImageSpace* space,
1441 Handle<mirror::ClassLoader> class_loader,
1442 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001443 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001444 REQUIRES(!Locks::dex_lock_)
1445 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001446
Chris Wailesfbeef462018-10-19 14:16:35 -07001447 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001448 REQUIRES_SHARED(Locks::mutator_lock_);
1449
1450 static void UpdateInternStrings(
1451 gc::space::ImageSpace* space,
1452 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1453 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001454};
1455
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001456void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001457 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001458 gc::space::ImageSpace* space,
1459 Handle<mirror::ClassLoader> class_loader,
1460 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001461 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001462 REQUIRES(!Locks::dex_lock_)
1463 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001464 ScopedTrace app_image_timing("AppImage:Updating");
1465
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001466 Thread* const self = Thread::Current();
1467 gc::Heap* const heap = Runtime::Current()->GetHeap();
1468 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001469 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001470 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001471 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001472 const size_t num_dex_caches = dex_caches->GetLength();
1473 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001474 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001475 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001476 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001477 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001478 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1479 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001480 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001481
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001482 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001483 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001484 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001485 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001486 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001487 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001488 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001489
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001490 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001491 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001492 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001493 DCHECK(it != new_class_set->end());
1494 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001495 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001496
Vladimir Marko1a1de672016-10-13 12:53:15 +01001497 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001498 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001499 DCHECK(it2 != new_class_set->end());
1500 DCHECK_EQ(it2->Read(), super_class);
1501 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001502
Vladimir Marko1a1de672016-10-13 12:53:15 +01001503 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1504 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001505 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1506 if (!class_linker->IsQuickResolutionStub(code) &&
1507 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001508 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001509 !m.IsNative()) {
1510 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001511 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001512 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001513
Vladimir Marko1a1de672016-10-13 12:53:15 +01001514 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1515 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001516 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1517 if (!class_linker->IsQuickResolutionStub(code) &&
1518 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001519 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001520 !m.IsNative()) {
1521 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001522 }
1523 }
1524 }
1525 }
1526 }
1527 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001528 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001529
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001530 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001531 HandleAppImageStrings(space);
1532
1533 if (kIsDebugBuild) {
1534 VerifyStringInterning(*space);
1535 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001536 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001537
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001538 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001539 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001540 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1541 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001542 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001543 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001544}
1545
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001546void AppImageLoadingHelper::UpdateInternStrings(
1547 gc::space::ImageSpace* space,
1548 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1549 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001550 const ImageSection& sro_section =
1551 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1552 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001553
1554 VLOG(image)
1555 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1556 << num_string_offsets;
1557
Chris Wailesfbeef462018-10-19 14:16:35 -07001558 const auto* sro_base =
1559 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001560
1561 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001562 uint32_t base_offset = sro_base[offset_index].first;
1563
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001564 if (HasDexCacheStringNativeRefTag(base_offset)) {
1565 base_offset = ClearDexCacheNativeRefTags(base_offset);
1566 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001567
1568 ObjPtr<mirror::DexCache> dex_cache =
1569 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1570 uint32_t string_index = sro_base[offset_index].second;
1571
1572 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1573 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001574 DCHECK(referred_string != nullptr);
1575
Chris Wailesfbeef462018-10-19 14:16:35 -07001576 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001577 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001578 // This doesn't use SetResolvedString to maintain consistency with how
1579 // we load the string. The index from the source string must be
1580 // re-used due to the circular nature of the cache. Because we are not
1581 // using a helper function we need to mark the GC card manually.
1582 WriteBarrier::ForEveryFieldWrite(dex_cache);
1583 dex_cache->GetStrings()[string_index].store(
1584 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001585 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001586 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1587 base_offset = ClearDexCacheNativeRefTags(base_offset);
1588 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001589
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001590 ObjPtr<mirror::DexCache> dex_cache =
1591 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1592 uint32_t string_index = sro_base[offset_index].second;
1593
1594 ObjPtr<mirror::String> referred_string =
1595 dex_cache->GetPreResolvedStrings()[string_index].Read();
1596 DCHECK(referred_string != nullptr);
1597
1598 auto it = intern_remap.find(referred_string.Ptr());
1599 if (it != intern_remap.end()) {
1600 // Because we are not using a helper function we need to mark the GC card manually.
1601 WriteBarrier::ForEveryFieldWrite(dex_cache);
1602 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1603 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001604 } else {
1605 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001606 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001607 DCHECK_ALIGNED(raw_member_offset, 2);
1608
1609 ObjPtr<mirror::Object> obj_ptr =
1610 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1611 MemberOffset member_offset(raw_member_offset);
1612 ObjPtr<mirror::String> referred_string =
1613 obj_ptr->GetFieldObject<mirror::String,
1614 kVerifyNone,
1615 kWithoutReadBarrier,
1616 /* kIsVolatile= */ false>(member_offset);
1617 DCHECK(referred_string != nullptr);
1618
1619 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001620 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001621 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1622 /* kCheckTransaction= */ false,
1623 kVerifyNone,
1624 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001625 }
1626 }
1627 }
1628}
1629
Chris Wailesfbeef462018-10-19 14:16:35 -07001630void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001631 // Iterate over the string reference offsets stored in the image and intern
1632 // the strings they point to.
1633 ScopedTrace timing("AppImage:InternString");
1634
Chris Wailesfbeef462018-10-19 14:16:35 -07001635 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001636
1637 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1638 // for faster lookup.
1639 // TODO: Optimize with a bitmap or bloom filter
1640 SafeMap<mirror::String*, mirror::String*> intern_remap;
1641 intern_table->AddImageStringsToTable(space, [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001642 REQUIRES_SHARED(Locks::mutator_lock_)
1643 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001644 const size_t non_boot_image_strings = intern_table->CountInterns(
1645 /*visit_boot_images=*/false,
1646 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001647 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001648 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1649 // Visit the smaller of the two sets to compute the intersection.
1650 if (interns.size() < non_boot_image_strings) {
1651 for (auto it = interns.begin(); it != interns.end(); ) {
1652 ObjPtr<mirror::String> string = it->Read();
1653 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1654 if (existing == nullptr) {
1655 existing = intern_table->LookupStrongLocked(string);
1656 }
1657 if (existing != nullptr) {
1658 intern_remap.Put(string.Ptr(), existing.Ptr());
1659 it = interns.erase(it);
1660 } else {
1661 ++it;
1662 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001663 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001664 } else {
1665 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1666 REQUIRES_SHARED(Locks::mutator_lock_)
1667 REQUIRES(Locks::intern_table_lock_) {
1668 auto it = interns.find(root);
1669 if (it != interns.end()) {
1670 ObjPtr<mirror::String> existing = root.Read();
1671 intern_remap.Put(it->Read(), existing.Ptr());
1672 it = interns.erase(it);
1673 }
1674 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1675 }
1676 // Sanity check to ensure correctness.
1677 if (kIsDebugBuild) {
1678 for (GcRoot<mirror::String>& root : interns) {
1679 ObjPtr<mirror::String> string = root.Read();
1680 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1681 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001682 }
1683 }
1684 });
1685
Chris Wailesfbeef462018-10-19 14:16:35 -07001686 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001687
1688 // For debug builds, always run the code below to get coverage.
1689 if (kIsDebugBuild || !intern_remap.empty()) {
1690 // Slow path case is when there are conflicting intern strings to fix up.
1691 UpdateInternStrings(space, intern_remap);
1692 }
1693}
1694
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001695static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1696 const char* location,
1697 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001698 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001699 DCHECK(error_msg != nullptr);
1700 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001701 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001702 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001703 return std::unique_ptr<const DexFile>();
1704 }
1705 std::string inner_error_msg;
1706 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1707 if (dex_file == nullptr) {
1708 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1709 location,
1710 oat_file->GetLocation().c_str(),
1711 inner_error_msg.c_str());
1712 return std::unique_ptr<const DexFile>();
1713 }
1714
1715 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1716 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1717 location,
1718 dex_file->GetLocationChecksum(),
1719 oat_dex_file->GetDexFileLocationChecksum());
1720 return std::unique_ptr<const DexFile>();
1721 }
1722 return dex_file;
1723}
1724
1725bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1726 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1727 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001728 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001729 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001730 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001731 DCHECK(dex_caches_object != nullptr);
1732 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1733 dex_caches_object->AsObjectArray<mirror::DexCache>();
1734 const OatFile* oat_file = space->GetOatFile();
1735 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001736 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001737 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1738 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1739 dex_file_location.c_str(),
1740 error_msg);
1741 if (dex_file == nullptr) {
1742 return false;
1743 }
1744 dex_cache->SetDexFile(dex_file.get());
1745 out_dex_files->push_back(std::move(dex_file));
1746 }
1747 return true;
1748}
1749
Andreas Gampe0793bec2016-12-01 11:37:33 -08001750// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1751// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001752class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001753 public:
1754 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1755 REQUIRES_SHARED(Locks::mutator_lock_) {
1756 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001757 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1758 DCHECK(obj != nullptr);
1759 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1760 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1761 if (obj->IsClass()) {
1762 auto klass = obj->AsClass();
1763 for (ArtField& field : klass->GetIFields()) {
1764 CHECK_EQ(field.GetDeclaringClass(), klass);
1765 }
1766 for (ArtField& field : klass->GetSFields()) {
1767 CHECK_EQ(field.GetDeclaringClass(), klass);
1768 }
1769 const auto pointer_size = isc.pointer_size_;
1770 for (auto& m : klass->GetMethods(pointer_size)) {
1771 isc.SanityCheckArtMethod(&m, klass);
1772 }
1773 auto* vtable = klass->GetVTable();
1774 if (vtable != nullptr) {
1775 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1776 }
1777 if (klass->ShouldHaveImt()) {
1778 ImTable* imt = klass->GetImt(pointer_size);
1779 for (size_t i = 0; i < ImTable::kSize; ++i) {
1780 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1781 }
1782 }
1783 if (klass->ShouldHaveEmbeddedVTable()) {
1784 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1785 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1786 }
1787 }
1788 mirror::IfTable* iftable = klass->GetIfTable();
1789 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1790 if (iftable->GetMethodArrayCount(i) > 0) {
1791 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1792 }
1793 }
1794 }
1795 };
1796 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001797 }
1798
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001799 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1800 ClassLinker* class_linker,
1801 mirror::MethodDexCacheType* arr,
1802 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001803 REQUIRES_SHARED(Locks::mutator_lock_) {
1804 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001805 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001806 }
1807
Andreas Gampe0793bec2016-12-01 11:37:33 -08001808 private:
1809 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1810 : spaces_(heap->GetBootImageSpaces()),
1811 pointer_size_(class_linker->GetImagePointerSize()) {
1812 space_begin_.reserve(spaces_.size());
1813 method_sections_.reserve(spaces_.size());
1814 runtime_method_sections_.reserve(spaces_.size());
1815 for (gc::space::ImageSpace* space : spaces_) {
1816 space_begin_.push_back(space->Begin());
1817 auto& header = space->GetImageHeader();
1818 method_sections_.push_back(&header.GetMethodsSection());
1819 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1820 }
1821 }
1822
1823 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1824 REQUIRES_SHARED(Locks::mutator_lock_) {
1825 if (m->IsRuntimeMethod()) {
1826 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1827 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1828 } else if (m->IsCopied()) {
1829 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1830 } else if (expected_class != nullptr) {
1831 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1832 }
1833 if (!spaces_.empty()) {
1834 bool contains = false;
1835 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1836 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1837 contains = method_sections_[i]->Contains(offset) ||
1838 runtime_method_sections_[i]->Contains(offset);
1839 }
1840 CHECK(contains) << m << " not found";
1841 }
1842 }
1843
1844 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1845 ObjPtr<mirror::Class> expected_class)
1846 REQUIRES_SHARED(Locks::mutator_lock_) {
1847 CHECK(arr != nullptr);
1848 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1849 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1850 // expected_class == null means we are a dex cache.
1851 if (expected_class != nullptr) {
1852 CHECK(method != nullptr);
1853 }
1854 if (method != nullptr) {
1855 SanityCheckArtMethod(method, expected_class);
1856 }
1857 }
1858 }
1859
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001860 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001861 REQUIRES_SHARED(Locks::mutator_lock_) {
1862 CHECK_EQ(arr != nullptr, size != 0u);
1863 if (arr != nullptr) {
1864 bool contains = false;
1865 for (auto space : spaces_) {
1866 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001867 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001868 contains = true;
1869 break;
1870 }
1871 }
1872 CHECK(contains);
1873 }
1874 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001875 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1876 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001877 // expected_class == null means we are a dex cache.
1878 if (method != nullptr) {
1879 SanityCheckArtMethod(method, nullptr);
1880 }
1881 }
1882 }
1883
1884 const std::vector<gc::space::ImageSpace*>& spaces_;
1885 const PointerSize pointer_size_;
1886
1887 // Cached sections from the spaces.
1888 std::vector<const uint8_t*> space_begin_;
1889 std::vector<const ImageSection*> method_sections_;
1890 std::vector<const ImageSection*> runtime_method_sections_;
1891};
1892
Andreas Gampebe7af222017-07-25 09:57:28 -07001893static void VerifyAppImage(const ImageHeader& header,
1894 const Handle<mirror::ClassLoader>& class_loader,
1895 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1896 ClassTable* class_table, gc::space::ImageSpace* space)
1897 REQUIRES_SHARED(Locks::mutator_lock_) {
1898 {
1899 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1900 public:
1901 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1902
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001903 void Visit(ArtMethod* method) override
Andreas Gampebe7af222017-07-25 09:57:28 -07001904 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1905 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1906 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1907 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1908 }
1909 }
1910
1911 private:
1912 ClassTable* const table_;
1913 };
1914 VerifyClassInTableArtMethodVisitor visitor(class_table);
1915 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1916 }
1917 {
1918 // Verify that all direct interfaces of classes in the class table are also resolved.
1919 std::vector<ObjPtr<mirror::Class>> classes;
1920 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1921 REQUIRES_SHARED(Locks::mutator_lock_) {
1922 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1923 classes.push_back(klass);
1924 }
1925 return true;
1926 };
1927 class_table->Visit(verify_direct_interfaces_in_table);
1928 Thread* self = Thread::Current();
1929 for (ObjPtr<mirror::Class> klass : classes) {
1930 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1931 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1932 << klass->PrettyDescriptor() << " iface #" << i;
1933 }
1934 }
1935 }
1936 // Check that all non-primitive classes in dex caches are also in the class table.
1937 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1938 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1939 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1940 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1941 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1942 if (klass != nullptr && !klass->IsPrimitive()) {
1943 CHECK(class_table->Contains(klass))
1944 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1945 }
1946 }
1947 }
1948}
1949
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001950bool ClassLinker::AddImageSpace(
1951 gc::space::ImageSpace* space,
1952 Handle<mirror::ClassLoader> class_loader,
1953 jobjectArray dex_elements,
1954 const char* dex_location,
1955 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1956 std::string* error_msg) {
1957 DCHECK(out_dex_files != nullptr);
1958 DCHECK(error_msg != nullptr);
1959 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001960 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001961 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001962 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 DCHECK(dex_caches_object != nullptr);
1964 Runtime* const runtime = Runtime::Current();
1965 gc::Heap* const heap = runtime->GetHeap();
1966 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001967 // Check that the image is what we are expecting.
1968 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1969 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1970 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1971 image_pointer_size_);
1972 return false;
1973 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001974 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1975 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1976 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1977 expected_image_roots,
1978 header.GetImageRoots()->GetLength());
1979 return false;
1980 }
1981 StackHandleScope<3> hs(self);
1982 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1983 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1984 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1985 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001986 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001987 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1988 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001989 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001990 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001991 *error_msg = StringPrintf("Expected %d class roots but got %d",
1992 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001993 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001994 return false;
1995 }
1996 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001997 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1998 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1999 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002000 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2001 return false;
2002 }
2003 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002004 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002005 if (oat_file->GetOatHeader().GetDexFileCount() !=
2006 static_cast<uint32_t>(dex_caches->GetLength())) {
2007 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2008 "image";
2009 return false;
2010 }
2011
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002012 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002013 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2014 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 // TODO: Only store qualified paths.
2016 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002017 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002018 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2019 dex_file_location.c_str(),
2020 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002021 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002022 return false;
2023 }
2024
2025 if (app_image) {
2026 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2027 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002028 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002029 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002030 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002031 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002032 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002033 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002034 }
2035 }
2036 } else {
2037 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002038 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2039 this,
2040 dex_cache->GetResolvedMethods(),
2041 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002042 }
2043 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002044 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002045 }
2046 out_dex_files->push_back(std::move(dex_file));
2047 }
2048
2049 if (app_image) {
2050 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002051 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002052 // Check that the class loader resolves the same way as the ones in the image.
2053 // Image class loader [A][B][C][image dex files]
2054 // Class loader = [???][dex_elements][image dex files]
2055 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002056 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002057 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2058 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2059 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002060 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2061 *error_msg = "Unexpected BootClassLoader in app image";
2062 return false;
2063 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002064 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2065 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2066 // special case the comparison of dex files of the two class loaders, but then do full
2067 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002068 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002069 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002070 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2071 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2072 if (element != nullptr) {
2073 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002074 ObjPtr<mirror::String> name;
2075 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2076 loader_dex_file_names.push_back(name);
2077 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002078 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002079 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002080 std::string temp_error_msg;
2081 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2082 bool success = GetDexFileNames(
2083 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2084 if (success) {
2085 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2086 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2087 static_cast<size_t>(dex_caches->GetLength()));
2088 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2089 image_dex_file_names.resize(image_count);
2090 success = success && CompareDexFiles(image_dex_file_names,
2091 loader_dex_file_names,
2092 &temp_error_msg);
2093 success = success && CompareClassLoaders(soa,
2094 image_class_loader.Get(),
2095 class_loader.Get(),
2096 /*check_dex_file_names=*/ false,
2097 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002098 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002099 if (!success) {
2100 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2101 temp_error_msg.c_str());
2102 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002103 }
2104 }
2105
2106 if (kSanityCheckObjects) {
2107 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2108 auto* dex_cache = dex_caches->Get(i);
2109 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2110 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2111 if (field != nullptr) {
2112 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2113 }
2114 }
2115 }
2116 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002117 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002118 }
2119 }
2120
2121 // Set entry point to interpreter if in InterpretOnly mode.
2122 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002123 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07002124 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002125 }
2126
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002127 ClassTable* class_table = nullptr;
2128 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002129 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002130 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002131 }
2132 // If we have a class table section, read it and use it for verification in
2133 // UpdateAppImageClassLoadersAndDexCaches.
2134 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002135 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002136 const bool added_class_table = class_table_section.Size() > 0u;
2137 if (added_class_table) {
2138 const uint64_t start_time2 = NanoTime();
2139 size_t read_count = 0;
2140 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2141 /*make copy*/false,
2142 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002143 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002144 }
2145 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002146 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002147
2148 {
2149 ScopedTrace trace("AppImage:UpdateClassLoaders");
2150 // Update class loader and resolved strings. If added_class_table is false, the resolved
2151 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002152 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002153 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002154 // Note: We probably don't need the read barrier unless we copy the app image objects into
2155 // the region space.
2156 ObjPtr<mirror::Class> klass(root.Read());
2157 // Do not update class loader for boot image classes where the app image
2158 // class loader is only the initiating loader but not the defining loader.
2159 // Avoid read barrier since we are comparing against null.
2160 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2161 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2162 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002163 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002164 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002165
Vladimir Marko305c38b2018-02-14 11:50:07 +00002166 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002167 // Every class in the app image has initially SubtypeCheckInfo in the
2168 // Uninitialized state.
2169 //
2170 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2171 // after class initialization is complete. The app image ClassStatus as-is
2172 // are almost all ClassStatus::Initialized, and being in the
2173 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2174 //
2175 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2176 //
2177 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002178 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002179 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2180 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002181 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002182 }
2183 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002184 }
2185 if (!oat_file->GetBssGcRoots().empty()) {
2186 // Insert oat file to class table for visiting .bss GC roots.
2187 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002188 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002189
Mathieu Chartier69731002016-03-02 16:08:31 -08002190 if (added_class_table) {
2191 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2192 class_table->AddClassSet(std::move(temp_set));
2193 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002194
Mathieu Chartier69731002016-03-02 16:08:31 -08002195 if (kIsDebugBuild && app_image) {
2196 // This verification needs to happen after the classes have been added to the class loader.
2197 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002198 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002199 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002200 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002201
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002202 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002203 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002204}
2205
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002206bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002207 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2208 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002209}
2210
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002211void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002212 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2213 // enabling tracing requires the mutator lock, there are no race conditions here.
2214 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002215 Thread* const self = Thread::Current();
2216 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002217 if (kUseReadBarrier) {
2218 // We do not track new roots for CC.
2219 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2220 kVisitRootFlagClearRootLog |
2221 kVisitRootFlagStartLoggingNewRoots |
2222 kVisitRootFlagStopLoggingNewRoots));
2223 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002224 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002225 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2226 // There is 3 GC cases to handle:
2227 // Non moving concurrent:
2228 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002229 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002230 //
2231 // Moving non-concurrent:
2232 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2233 // To prevent missing roots, this case needs to ensure that there is no
2234 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2235 // class which is in the class table.
2236 //
2237 // Moving concurrent:
2238 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2239 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002240 //
2241 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2242 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2243 // these objects.
2244 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002245 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002246 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002247 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002248 for (const ClassLoaderData& data : class_loaders_) {
2249 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2250 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2251 }
2252 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002253 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002254 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002255 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002256 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002257 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002258 // Concurrent moving GC marked new roots through the to-space invariant.
2259 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002260 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002261 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2262 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2263 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2264 if (old_ref != nullptr) {
2265 DCHECK(old_ref->IsClass());
2266 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2267 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2268 // Concurrent moving GC marked new roots through the to-space invariant.
2269 CHECK_EQ(new_ref, old_ref);
2270 }
2271 }
2272 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002273 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002274 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002275 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002276 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002277 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002278 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002279 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002280 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002281 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002282 }
2283 // We deliberately ignore the class roots in the image since we
2284 // handle image roots by using the MS/CMS rescanning of dirty cards.
2285}
2286
Brian Carlstroma663ea52011-08-19 23:33:41 -07002287// Keep in sync with InitCallback. Anything we visit, we need to
2288// reinit references to when reinitializing a ClassLinker from a
2289// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002290void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002291 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002292 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002293 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2294 // unloading if we are marking roots.
2295 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002296}
2297
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002298class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2299 public:
2300 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2301 : visitor_(visitor),
2302 done_(false) {}
2303
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002304 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002305 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002306 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002307 if (!done_ && class_table != nullptr) {
2308 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2309 if (!class_table->Visit(visitor)) {
2310 // If the visitor ClassTable returns false it means that we don't need to continue.
2311 done_ = true;
2312 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002313 }
2314 }
2315
2316 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002317 // Class visitor that limits the class visits from a ClassTable to the classes with
2318 // the provided defining class loader. This filter is used to avoid multiple visits
2319 // of the same class which can be recorded for multiple initiating class loaders.
2320 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2321 public:
2322 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2323 ClassVisitor* visitor)
2324 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2325
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002326 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002327 if (klass->GetClassLoader() != defining_class_loader_) {
2328 return true;
2329 }
2330 return (*visitor_)(klass);
2331 }
2332
2333 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2334 ClassVisitor* const visitor_;
2335 };
2336
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002337 ClassVisitor* const visitor_;
2338 // If done is true then we don't need to do any more visiting.
2339 bool done_;
2340};
2341
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002342void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002343 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002344 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2345 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002346 }
2347}
2348
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002349void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002350 Thread* const self = Thread::Current();
2351 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2352 // Not safe to have thread suspension when we are holding a lock.
2353 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002354 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002355 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002356 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002357 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002358 }
2359}
2360
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002361class GetClassesInToVector : public ClassVisitor {
2362 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002363 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002364 classes_.push_back(klass);
2365 return true;
2366 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002367 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002368};
2369
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002370class GetClassInToObjectArray : public ClassVisitor {
2371 public:
2372 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2373 : arr_(arr), index_(0) {}
2374
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002375 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002376 ++index_;
2377 if (index_ <= arr_->GetLength()) {
2378 arr_->Set(index_ - 1, klass);
2379 return true;
2380 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002381 return false;
2382 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002383
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002384 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002385 return index_ <= arr_->GetLength();
2386 }
2387
2388 private:
2389 mirror::ObjectArray<mirror::Class>* const arr_;
2390 int32_t index_;
2391};
2392
2393void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002394 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2395 // is avoiding duplicates.
2396 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002397 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002398 GetClassesInToVector accumulator;
2399 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002400 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002401 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002402 return;
2403 }
2404 }
2405 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002406 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002407 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002408 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002409 // We size the array assuming classes won't be added to the class table during the visit.
2410 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002411 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002412 size_t class_table_size;
2413 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002414 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002415 // Add 100 in case new classes get loaded when we are filling in the object array.
2416 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002417 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002418 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002419 classes.Assign(
2420 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002421 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002422 GetClassInToObjectArray accumulator(classes.Get());
2423 VisitClasses(&accumulator);
2424 if (accumulator.Succeeded()) {
2425 break;
2426 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002427 }
2428 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2429 // If the class table shrank during creation of the clases array we expect null elements. If
2430 // the class table grew then the loop repeats. If classes are created after the loop has
2431 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002432 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002433 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002434 return;
2435 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002436 }
2437 }
2438}
2439
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002440ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002441 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002442 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002443 // CHA unloading analysis is not needed. No negative consequences are expected because
2444 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002445 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002446 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002447 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002448}
2449
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002450void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002451 Runtime* const runtime = Runtime::Current();
2452 JavaVMExt* const vm = runtime->GetJavaVM();
2453 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002454 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002455 if (runtime->GetJit() != nullptr) {
2456 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2457 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002458 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002459 code_cache->RemoveMethodsIn(self, *data.allocator);
2460 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002461 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002462 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002463 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002464 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002465 // Cleanup references to single implementation ArtMethods that will be deleted.
2466 if (cleanup_cha) {
2467 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2468 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2469 }
2470
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002471 delete data.allocator;
2472 delete data.class_table;
2473}
2474
Vladimir Markobcf17522018-06-01 13:14:32 +01002475ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2476 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002477 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002478 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2479 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002480}
2481
Vladimir Markobcf17522018-06-01 13:14:32 +01002482ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2483 Thread* self,
2484 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002485 StackHandleScope<1> hs(self);
2486 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002487 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002488 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002489 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002490 self->AssertPendingOOMException();
2491 return nullptr;
2492 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002493 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002494 if (location == nullptr) {
2495 self->AssertPendingOOMException();
2496 return nullptr;
2497 }
2498 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002499 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002500}
2501
Vladimir Markobcf17522018-06-01 13:14:32 +01002502ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2503 const DexFile& dex_file,
2504 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002505 ObjPtr<mirror::String> location = nullptr;
2506 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002507 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002508 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002509 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002510 mirror::DexCache::InitializeDexCache(self,
2511 dex_cache,
2512 location,
2513 &dex_file,
2514 linear_alloc,
2515 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002516 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002517 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002518}
2519
Roland Levillain0e840272018-08-23 19:55:30 +01002520template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002521ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2522 ObjPtr<mirror::Class> java_lang_Class,
2523 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002524 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002525 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002526 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002527 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002528 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2529 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002530 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002531 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002532 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002533 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002534 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002535}
2536
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002537ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002538 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002539}
2540
Roland Levillain0e840272018-08-23 19:55:30 +01002541ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2542 ObjPtr<mirror::Class> java_lang_Class) {
2543 // We make this class non-movable for the unlikely case where it were to be
2544 // moved by a sticky-bit (minor) collection when using the Generational
2545 // Concurrent Copying (CC) collector, potentially creating a stale reference
2546 // in the `klass_` field of one of its instances allocated in the Large-Object
2547 // Space (LOS) -- see the comment about the dirty card scanning logic in
2548 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002549 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002550 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2551}
2552
Vladimir Markobcf17522018-06-01 13:14:32 +01002553ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002554 Thread* self,
2555 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002556 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002557 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002558}
2559
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002560ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2561 const char* descriptor,
2562 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002563 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002564 if (kIsDebugBuild) {
2565 StackHandleScope<1> hs(self);
2566 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2567 Thread::PoisonObjectPointersIfDebug();
2568 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002569
2570 // For temporary classes we must wait for them to be retired.
2571 if (init_done_ && klass->IsTemp()) {
2572 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002573 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002574 ThrowEarlierClassFailure(klass);
2575 return nullptr;
2576 }
2577 StackHandleScope<1> hs(self);
2578 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2579 ObjectLock<mirror::Class> lock(self, h_class);
2580 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002581 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002582 lock.WaitIgnoringInterrupts();
2583 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002584 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002585 ThrowEarlierClassFailure(h_class.Get());
2586 return nullptr;
2587 }
2588 CHECK(h_class->IsRetired());
2589 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002590 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002591 }
2592
Brian Carlstromaded5f72011-10-07 17:15:04 -07002593 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002594 size_t index = 0;
2595 // Maximum number of yield iterations until we start sleeping.
2596 static const size_t kNumYieldIterations = 1000;
2597 // How long each sleep is in us.
2598 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002599 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002600 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002601 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002602 {
2603 ObjectTryLock<mirror::Class> lock(self, h_class);
2604 // Can not use a monitor wait here since it may block when returning and deadlock if another
2605 // thread has locked klass.
2606 if (lock.Acquired()) {
2607 // Check for circular dependencies between classes, the lock is required for SetStatus.
2608 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2609 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002610 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002611 return nullptr;
2612 }
2613 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002614 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002615 {
2616 // Handle wrapper deals with klass moving.
2617 ScopedThreadSuspension sts(self, kSuspended);
2618 if (index < kNumYieldIterations) {
2619 sched_yield();
2620 } else {
2621 usleep(kSleepDurationUS);
2622 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002623 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002624 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002625 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002626
Vladimir Marko72ab6842017-01-20 19:32:50 +00002627 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002628 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002629 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002630 }
2631 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002632 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002633 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002634 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002635}
2636
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002637using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002638
2639// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002640ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002641 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002642 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002643 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002644 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002645 return ClassPathEntry(dex_file, dex_class_def);
2646 }
2647 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002648 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002649}
2650
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002651bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2652 Thread* self,
2653 const char* descriptor,
2654 size_t hash,
2655 Handle<mirror::ClassLoader> class_loader,
2656 /*out*/ ObjPtr<mirror::Class>* result) {
2657 ArtField* field =
2658 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2659 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2660 if (raw_shared_libraries == nullptr) {
2661 return true;
2662 }
2663
2664 StackHandleScope<2> hs(self);
2665 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2666 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2667 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2668 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2669 temp_loader.Assign(shared_libraries->Get(i));
2670 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2671 return false; // One of the shared libraries is not supported.
2672 }
2673 if (*result != nullptr) {
2674 return true; // Found the class up the chain.
2675 }
2676 }
2677 return true;
2678}
2679
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002680bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2681 Thread* self,
2682 const char* descriptor,
2683 size_t hash,
2684 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002685 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002686 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002687 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002688 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002689 return true;
2690 }
2691
David Brazdil05909d82018-12-06 16:25:16 +00002692 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002693 // For regular path or dex class loader the search order is:
2694 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002695 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002696 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002697
Calin Juravlecdd49122017-07-05 20:09:53 -07002698 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2699 StackHandleScope<1> hs(self);
2700 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2701 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2702 return false; // One of the parents is not supported.
2703 }
2704 if (*result != nullptr) {
2705 return true; // Found the class up the chain.
2706 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002707
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002708 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2709 return false; // One of the shared library loader is not supported.
2710 }
2711 if (*result != nullptr) {
2712 return true; // Found the class in a shared library.
2713 }
2714
Calin Juravlecdd49122017-07-05 20:09:53 -07002715 // Search the current class loader classpath.
2716 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002717 return true;
2718 }
2719
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 if (IsDelegateLastClassLoader(soa, class_loader)) {
2721 // For delegate last, the search order is:
2722 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002723 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002724 // - class loader dex files
2725 // - parent
2726 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2727 if (*result != nullptr) {
2728 return true; // The class is part of the boot class path.
2729 }
2730
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002731 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2732 return false; // One of the shared library loader is not supported.
2733 }
2734 if (*result != nullptr) {
2735 return true; // Found the class in a shared library.
2736 }
2737
Calin Juravlecdd49122017-07-05 20:09:53 -07002738 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2739 if (*result != nullptr) {
2740 return true; // Found the class in the current class loader
2741 }
2742
2743 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2744 StackHandleScope<1> hs(self);
2745 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2746 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2747 }
2748
2749 // Unsupported class loader.
2750 *result = nullptr;
2751 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002752}
2753
2754// Finds the class in the boot class loader.
2755// If the class is found the method returns the resolved class. Otherwise it returns null.
2756ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2757 const char* descriptor,
2758 size_t hash) {
2759 ObjPtr<mirror::Class> result = nullptr;
2760 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2761 if (pair.second != nullptr) {
2762 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2763 if (klass != nullptr) {
2764 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002765 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002766 result = DefineClass(self,
2767 descriptor,
2768 hash,
2769 ScopedNullHandle<mirror::ClassLoader>(),
2770 *pair.first,
2771 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002772 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002773 if (result == nullptr) {
2774 CHECK(self->IsExceptionPending()) << descriptor;
2775 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002776 }
2777 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002778 return result;
2779}
Andreas Gampef865ea92015-04-13 22:14:19 -07002780
Calin Juravle415dc3d2017-06-28 11:03:12 -07002781ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2782 ScopedObjectAccessAlreadyRunnable& soa,
2783 const char* descriptor,
2784 size_t hash,
2785 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002786 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2787 IsInMemoryDexClassLoader(soa, class_loader) ||
2788 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002789 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002790
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002791 ObjPtr<mirror::Class> ret;
2792 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002793 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002794 if (dex_class_def != nullptr) {
2795 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2796 descriptor,
2797 hash,
2798 class_loader,
2799 *cp_dex_file,
2800 *dex_class_def);
2801 if (klass == nullptr) {
2802 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2803 soa.Self()->ClearException();
2804 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002805 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002806 ret = klass;
2807 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002808 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002809 return true; // Continue with the next DexFile.
2810 };
2811
2812 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2813 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002814}
2815
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002816ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2817 const char* descriptor,
2818 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002819 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002820 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002821 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002822 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002823 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002824 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2825 // for primitive classes that aren't backed by dex files.
2826 return FindPrimitiveClass(descriptor[0]);
2827 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002828 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002829 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002830 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002831 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002832 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002833 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002834 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002835 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002836 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002837 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002838 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002839 return DefineClass(self,
2840 descriptor,
2841 hash,
2842 ScopedNullHandle<mirror::ClassLoader>(),
2843 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002844 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002845 } else {
2846 // The boot class loader is searched ahead of the application class loader, failures are
2847 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2848 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002849 ObjPtr<mirror::Throwable> pre_allocated =
2850 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002851 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002852 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002853 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002854 }
2855 ObjPtr<mirror::Class> result_ptr;
2856 bool descriptor_equals;
2857 if (descriptor[0] == '[') {
2858 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2859 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2860 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2861 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002862 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002863 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002864 bool known_hierarchy =
2865 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2866 if (result_ptr != nullptr) {
2867 // The chain was understood and we found the class. We still need to add the class to
2868 // the class table to protect from racy programs that can try and redefine the path list
2869 // which would change the Class<?> returned for subsequent evaluation of const-class.
2870 DCHECK(known_hierarchy);
2871 DCHECK(result_ptr->DescriptorEquals(descriptor));
2872 descriptor_equals = true;
2873 } else {
2874 // Either the chain wasn't understood or the class wasn't found.
2875 //
2876 // If the chain was understood but we did not find the class, let the Java-side
2877 // rediscover all this and throw the exception with the right stack trace. Note that
2878 // the Java-side could still succeed for racy programs if another thread is actively
2879 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002880
Alex Light185a4612018-10-04 15:54:25 -07002881 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002882 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002883 // Oops, we can't call into java so we can't run actual class-loader code.
2884 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002885 ObjPtr<mirror::Throwable> pre_allocated =
2886 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2887 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002888 return nullptr;
2889 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002890
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002891 // Inlined DescriptorToDot(descriptor) with extra validation.
2892 //
2893 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2894 // the DescriptorEquals() check below and give a confusing error message. For example,
2895 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2896 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2897 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2898 size_t descriptor_length = strlen(descriptor);
2899 if (UNLIKELY(descriptor[0] != 'L') ||
2900 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2901 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2902 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2903 return nullptr;
2904 }
2905 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2906 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2907
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002908 ScopedLocalRef<jobject> class_loader_object(
2909 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002910 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2911 {
2912 ScopedThreadStateChange tsc(self, kNative);
2913 ScopedLocalRef<jobject> class_name_object(
2914 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2915 if (class_name_object.get() == nullptr) {
2916 DCHECK(self->IsExceptionPending()); // OOME.
2917 return nullptr;
2918 }
2919 CHECK(class_loader_object.get() != nullptr);
2920 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2921 WellKnownClasses::java_lang_ClassLoader_loadClass,
2922 class_name_object.get()));
2923 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002924 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002925 // broken loader - throw NPE to be compatible with Dalvik
2926 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2927 class_name_string.c_str()).c_str());
2928 return nullptr;
2929 }
2930 result_ptr = soa.Decode<mirror::Class>(result.get());
2931 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002932 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002933 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002934 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002935
2936 if (self->IsExceptionPending()) {
2937 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2938 // However, to comply with the RI behavior, first check if another thread succeeded.
2939 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2940 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2941 self->ClearException();
2942 return EnsureResolved(self, descriptor, result_ptr);
2943 }
2944 return nullptr;
2945 }
2946
2947 // Try to insert the class to the class table, checking for mismatch.
2948 ObjPtr<mirror::Class> old;
2949 {
2950 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2951 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2952 old = class_table->Lookup(descriptor, hash);
2953 if (old == nullptr) {
2954 old = result_ptr; // For the comparison below, after releasing the lock.
2955 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002956 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002957 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002958 } // else throw below, after releasing the lock.
2959 }
2960 }
2961 if (UNLIKELY(old != result_ptr)) {
2962 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2963 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2964 mirror::Class* loader_class = class_loader->GetClass();
2965 const char* loader_class_name =
2966 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2967 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2968 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2969 << DescriptorToDot(descriptor) << "\").";
2970 return EnsureResolved(self, descriptor, old);
2971 }
2972 if (UNLIKELY(!descriptor_equals)) {
2973 std::string result_storage;
2974 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2975 std::string loader_storage;
2976 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2977 ThrowNoClassDefFoundError(
2978 "Initiating class loader of type %s returned class %s instead of %s.",
2979 DescriptorToDot(loader_class_name).c_str(),
2980 DescriptorToDot(result_name).c_str(),
2981 DescriptorToDot(descriptor).c_str());
2982 return nullptr;
2983 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002984 // Success.
2985 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002986}
2987
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002988ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
2989 const char* descriptor,
2990 size_t hash,
2991 Handle<mirror::ClassLoader> class_loader,
2992 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002993 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002994 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002995 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002996
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002998 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002999 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003000 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003001 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003002 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003003 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003004 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003005 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003006 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003007 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003008 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003009 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003010 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003011 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003012 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003013 }
3014
Alex Lighte9f61032018-09-24 16:04:51 -07003015 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3016 // code to be executed. We put it up here so we can avoid all the allocations associated with
3017 // creating the class. This can happen with (eg) jit threads.
3018 if (!self->CanLoadClasses()) {
3019 // Make sure we don't try to load anything, potentially causing an infinite loop.
3020 ObjPtr<mirror::Throwable> pre_allocated =
3021 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3022 self->SetException(pre_allocated);
3023 return nullptr;
3024 }
3025
Andreas Gampefa4333d2017-02-14 11:10:34 -08003026 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003027 // Allocate a class with the status of not ready.
3028 // Interface object should get the right size here. Regular class will
3029 // figure out the right size later and be replaced with one of the right
3030 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003031 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003033 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003034 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003035 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003036 }
Alex Lightb0f11922017-01-23 14:25:17 -08003037 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3038 // nothing.
3039 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003040 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003041 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3042 // will only be called once.
3043 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3044 klass,
3045 class_loader,
3046 dex_file,
3047 dex_class_def,
3048 &new_dex_file,
3049 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003050 // Check to see if an exception happened during runtime callbacks. Return if so.
3051 if (self->IsExceptionPending()) {
3052 return nullptr;
3053 }
Alex Lightb0f11922017-01-23 14:25:17 -08003054 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003055 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003056 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003057 return nullptr;
3058 }
3059 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003060 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003061
Jeff Hao848f70a2014-01-15 13:49:50 -08003062 // Mark the string class by setting its access flag.
3063 if (UNLIKELY(!init_done_)) {
3064 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3065 klass->SetStringClass();
3066 }
3067 }
3068
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003069 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003070 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003071 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003072 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003073
Mathieu Chartier590fee92013-09-13 13:46:47 -07003074 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003075 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003076 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003077 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3078 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003079 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003080 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003081
Mathieu Chartierc7853442015-03-27 14:35:38 -07003082 // Load the fields and other things after we are inserted in the table. This is so that we don't
3083 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3084 // other reason is that the field roots are only visited from the class table. So we need to be
3085 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003086 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003087 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003088 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003089 // An exception occured during load, set status to erroneous while holding klass' lock in case
3090 // notification is necessary.
3091 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003092 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003093 }
3094 return nullptr;
3095 }
3096
Brian Carlstromaded5f72011-10-07 17:15:04 -07003097 // Finish loading (if necessary) by finding parents
3098 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003099 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003100 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003101 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003102 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003103 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003104 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003105 }
3106 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003107
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003108 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003109 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003110 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003111
Brian Carlstromaded5f72011-10-07 17:15:04 -07003112 // Link the class (if necessary)
3113 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003114 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003115 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003116
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003117 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003118 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003119 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003120 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003121 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003122 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003123 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003124 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003125 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003126 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003127 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003128
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003129 // Instrumentation may have updated entrypoints for all methods of all
3130 // classes. However it could not update methods of this class while we
3131 // were loading it. Now the class is resolved, we can update entrypoints
3132 // as required by instrumentation.
3133 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3134 // We must be in the kRunnable state to prevent instrumentation from
3135 // suspending all threads to update entrypoints while we are doing it
3136 // for this class.
3137 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003138 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003139 }
3140
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003141 /*
3142 * We send CLASS_PREPARE events to the debugger from here. The
3143 * definition of "preparation" is creating the static fields for a
3144 * class and initializing them to the standard default values, but not
3145 * executing any code (that comes later, during "initialization").
3146 *
3147 * We did the static preparation in LinkClass.
3148 *
3149 * The class has been prepared and resolved but possibly not yet verified
3150 * at this point.
3151 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003152 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003153
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003154 // Notify native debugger of the new class and its layout.
3155 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3156
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003157 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003158}
3159
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003160uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003161 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003162 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003163 size_t num_8 = 0;
3164 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003165 size_t num_32 = 0;
3166 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003167 ClassAccessor accessor(dex_file, dex_class_def);
3168 // We allow duplicate definitions of the same field in a class_data_item
3169 // but ignore the repeated indexes here, b/21868015.
3170 uint32_t last_field_idx = dex::kDexNoIndex;
3171 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3172 uint32_t field_idx = field.GetIndex();
3173 // Ordering enforced by DexFileVerifier.
3174 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3175 if (UNLIKELY(field_idx == last_field_idx)) {
3176 continue;
3177 }
3178 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003179 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003180 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3181 char c = descriptor[0];
3182 switch (c) {
3183 case 'L':
3184 case '[':
3185 num_ref++;
3186 break;
3187 case 'J':
3188 case 'D':
3189 num_64++;
3190 break;
3191 case 'I':
3192 case 'F':
3193 num_32++;
3194 break;
3195 case 'S':
3196 case 'C':
3197 num_16++;
3198 break;
3199 case 'B':
3200 case 'Z':
3201 num_8++;
3202 break;
3203 default:
3204 LOG(FATAL) << "Unknown descriptor: " << c;
3205 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003206 }
3207 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003208 return mirror::Class::ComputeClassSize(false,
3209 0,
3210 num_8,
3211 num_16,
3212 num_32,
3213 num_64,
3214 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003215 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003216}
3217
Alex Lightfc49fec2018-01-16 22:28:36 +00003218// Special case to get oat code without overwriting a trampoline.
3219const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003220 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003221 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003222 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003223 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003224 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3225 if (code != nullptr) {
3226 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003227 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003228 if (method->IsNative()) {
3229 // No code and native? Use generic trampoline.
3230 return GetQuickGenericJniStub();
3231 }
3232 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003233}
3234
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003235bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003236 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003237 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3238 return false;
3239 }
3240
Elliott Hughes956af0f2014-12-11 14:34:28 -08003241 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003242 return true;
3243 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003244
3245 Runtime* runtime = Runtime::Current();
3246 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3247 if (instr->InterpretOnly()) {
3248 return true;
3249 }
3250
3251 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3252 // Doing this check avoids doing compiled/interpreter transitions.
3253 return true;
3254 }
3255
3256 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
3257 // Force the use of interpreter when it is required by the debugger.
3258 return true;
3259 }
3260
Alex Light8f34aba2017-10-09 13:46:32 -07003261 if (Thread::Current()->IsAsyncExceptionPending()) {
3262 // Force use of interpreter to handle async-exceptions
3263 return true;
3264 }
3265
Alex Light2d441b12018-06-08 15:33:21 -07003266 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3267 const void* instr_target = instr->GetCodeForInvoke(method);
3268 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3269 return ShouldUseInterpreterEntrypoint(method, instr_target);
3270 }
3271
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003272 if (runtime->IsJavaDebuggable()) {
3273 // For simplicity, we ignore precompiled code and go to the interpreter
3274 // assuming we don't already have jitted code.
3275 // We could look at the oat file where `quick_code` is being defined,
3276 // and check whether it's been compiled debuggable, but we decided to
3277 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003278 jit::Jit* jit = Runtime::Current()->GetJit();
3279 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3280 }
3281
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003282 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003283 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003284 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003285 // since we want to JIT it (at first use) with extra stackmaps for native
3286 // debugging. We keep however all AOT code from the boot image,
3287 // since the JIT-at-first-use is blocking and would result in non-negligible
3288 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003289 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003290 }
3291
3292 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003293}
3294
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003295void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003296 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003297 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003298 if (klass->NumDirectMethods() == 0) {
3299 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003300 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003301 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003302 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003303 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003304 return; // OAT file unavailable.
3305 }
Ian Rogers19846512012-02-24 11:42:47 -08003306 }
Alex Light64ad14d2014-08-19 14:23:13 -07003307
Mathieu Chartierf8322842014-05-16 10:59:25 -07003308 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003309 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3310 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3311 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003312 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003313 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003314 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003315 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3316 klass->GetDexClassDefIndex(),
3317 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003318 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003319 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003320 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003321 if (!method->IsStatic()) {
3322 // Only update static methods.
3323 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003324 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003325 const void* quick_code = nullptr;
3326 if (has_oat_class) {
3327 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003328 quick_code = oat_method.GetQuickCode();
3329 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003330 // Check whether the method is native, in which case it's generic JNI.
3331 if (quick_code == nullptr && method->IsNative()) {
3332 quick_code = GetQuickGenericJniStub();
3333 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003334 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003335 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003336 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003337 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003338 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003339 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003340}
3341
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003342// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3343// method. Should only be called on non-invokable methods.
3344inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003345 DCHECK(method != nullptr);
3346 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003347 method->SetEntryPointFromQuickCompiledCodePtrSize(
3348 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3349 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003350}
3351
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003352static void LinkCode(ClassLinker* class_linker,
3353 ArtMethod* method,
3354 const OatFile::OatClass* oat_class,
3355 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003356 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003357 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003358 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003359 // The following code only applies to a non-compiler runtime.
3360 return;
3361 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003362 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003363 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003364 if (oat_class != nullptr) {
3365 // Every kind of method should at least get an invoke stub from the oat_method.
3366 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003367 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003368 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003369 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003370
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003371 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003372 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003373 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003374
Alex Light9139e002015-10-09 15:59:48 -07003375 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003376 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003377 return;
3378 }
Ian Rogers19846512012-02-24 11:42:47 -08003379
3380 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003381 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003382 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3383 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003384 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003385 } else if (quick_code == nullptr && method->IsNative()) {
3386 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003387 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003388 // Set entry point from compiled code if there's no code or in interpreter only mode.
3389 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003390 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003391
Ian Rogers62d6c772013-02-27 08:32:07 -08003392 if (method->IsNative()) {
3393 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003394 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003395
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003396 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003397 // We have a native method here without code. Then it should have either the generic JNI
3398 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3399 // TODO: this doesn't handle all the cases where trampolines may be installed.
3400 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003401 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3402 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003403 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003404 }
3405}
3406
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003407void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003408 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003409 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003410 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003411 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003412 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003413 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003414 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003415 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003416
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003417 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003418 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003419 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003420 klass->SetAccessFlags(access_flags);
3421 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003422 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003423 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003424
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003425 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003426 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003427}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003428
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003429LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3430 LinearAlloc* allocator,
3431 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003432 if (length == 0) {
3433 return nullptr;
3434 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003435 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3436 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3437 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003438 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003439 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003440 CHECK(ret != nullptr);
3441 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3442 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003443}
3444
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003445LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3446 LinearAlloc* allocator,
3447 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003448 if (length == 0) {
3449 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003450 }
Vladimir Marko14632852015-08-17 12:07:23 +01003451 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3452 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003453 const size_t storage_size =
3454 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003455 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003456 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003457 CHECK(ret != nullptr);
3458 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003459 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003460 }
3461 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003462}
3463
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003464LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003465 if (class_loader == nullptr) {
3466 return Runtime::Current()->GetLinearAlloc();
3467 }
3468 LinearAlloc* allocator = class_loader->GetAllocator();
3469 DCHECK(allocator != nullptr);
3470 return allocator;
3471}
3472
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003473LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003474 if (class_loader == nullptr) {
3475 return Runtime::Current()->GetLinearAlloc();
3476 }
3477 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3478 LinearAlloc* allocator = class_loader->GetAllocator();
3479 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003480 RegisterClassLoader(class_loader);
3481 allocator = class_loader->GetAllocator();
3482 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003483 }
3484 return allocator;
3485}
3486
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003487void ClassLinker::LoadClass(Thread* self,
3488 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003489 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003490 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003491 ClassAccessor accessor(dex_file,
3492 dex_class_def,
3493 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003494 if (!accessor.HasClassData()) {
3495 return;
3496 }
3497 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003498 {
3499 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3500 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003501 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003502 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003503 // We allow duplicate definitions of the same field in a class_data_item
3504 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003505 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003506 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3507 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003508 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003509 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3510 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003511 accessor.NumInstanceFields());
3512 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003513 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003514 uint32_t last_static_field_idx = 0u;
3515 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003516
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003517 // Methods
3518 bool has_oat_class = false;
3519 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3520 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3521 : OatFile::OatClass::Invalid();
3522 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3523 klass->SetMethodsPtr(
3524 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3525 accessor.NumDirectMethods(),
3526 accessor.NumVirtualMethods());
3527 size_t class_def_method_index = 0;
3528 uint32_t last_dex_method_index = dex::kDexNoIndex;
3529 size_t last_class_def_method_index = 0;
3530
3531 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3532 // methods needs to decode all of the fields.
3533 accessor.VisitFieldsAndMethods([&](
3534 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3535 uint32_t field_idx = field.GetIndex();
3536 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3537 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3538 LoadField(field, klass, &sfields->At(num_sfields));
3539 ++num_sfields;
3540 last_static_field_idx = field_idx;
3541 }
3542 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3543 uint32_t field_idx = field.GetIndex();
3544 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3545 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3546 LoadField(field, klass, &ifields->At(num_ifields));
3547 ++num_ifields;
3548 last_instance_field_idx = field_idx;
3549 }
3550 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3551 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3552 image_pointer_size_);
3553 LoadMethod(dex_file, method, klass, art_method);
3554 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3555 uint32_t it_method_index = method.GetIndex();
3556 if (last_dex_method_index == it_method_index) {
3557 // duplicate case
3558 art_method->SetMethodIndex(last_class_def_method_index);
3559 } else {
3560 art_method->SetMethodIndex(class_def_method_index);
3561 last_dex_method_index = it_method_index;
3562 last_class_def_method_index = class_def_method_index;
3563 }
3564 ++class_def_method_index;
3565 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3566 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3567 class_def_method_index - accessor.NumDirectMethods(),
3568 image_pointer_size_);
3569 LoadMethod(dex_file, method, klass, art_method);
3570 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3571 ++class_def_method_index;
3572 });
3573
3574 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003575 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003576 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3577 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3578 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003579 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3580 if (sfields != nullptr) {
3581 sfields->SetSize(num_sfields);
3582 }
3583 if (ifields != nullptr) {
3584 ifields->SetSize(num_ifields);
3585 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003586 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003587 // Set the field arrays.
3588 klass->SetSFieldsPtr(sfields);
3589 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003590 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003591 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003592 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003593 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003594 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003595 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003596}
3597
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003598void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003599 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003600 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003601 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003602 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003603 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003604
David Brazdil85865692018-10-30 17:26:20 +00003605 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3606 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003607}
3608
Mathieu Chartier268764d2016-09-13 12:09:38 -07003609void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003610 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003611 Handle<mirror::Class> klass,
3612 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003613 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003614 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003615 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003616
Mathieu Chartier268764d2016-09-13 12:09:38 -07003617 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003618 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003619 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003620 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003621
David Brazdil85865692018-10-30 17:26:20 +00003622 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3623 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003624
Ian Rogersdfb325e2013-10-30 01:00:44 -07003625 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003626 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003627 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3628 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003629 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003630 klass->SetFinalizable();
3631 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003632 std::string temp;
3633 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003634 // The Enum class declares a "final" finalize() method to prevent subclasses from
3635 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3636 // subclasses, so we exclude it here.
3637 // We also want to avoid setting the flag on Object, where we know that finalize() is
3638 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003639 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3640 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003641 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003642 }
3643 }
3644 }
3645 } else if (method_name[0] == '<') {
3646 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003647 bool is_init = (strcmp("<init>", method_name) == 0);
3648 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003649 if (UNLIKELY(!is_init && !is_clinit)) {
3650 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3651 } else {
3652 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3653 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003654 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003655 access_flags |= kAccConstructor;
3656 }
3657 }
3658 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003659 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3660 // Check if the native method is annotated with @FastNative or @CriticalNative.
3661 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3662 dex_file, dst->GetClassDef(), dex_method_idx);
3663 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003664 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003665 // Must be done after SetAccessFlags since IsAbstract depends on it.
3666 if (klass->IsInterface() && dst->IsAbstract()) {
3667 dst->CalculateAndSetImtIndex();
3668 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003669}
3670
Ian Rogers7b078e82014-09-10 14:44:24 -07003671void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003672 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003673 self,
3674 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003675 Runtime::Current()->GetLinearAlloc());
3676 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003677 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003678}
3679
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003680void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003681 ObjPtr<mirror::DexCache> dex_cache) {
3682 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003683 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003684 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003685 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003686}
3687
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003688void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003689 ObjPtr<mirror::DexCache> dex_cache,
3690 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003691 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003692 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003693 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003694 // For app images, the dex cache location may be a suffix of the dex file location since the
3695 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003696 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3697 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003698 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3699 std::string dex_file_location = dex_file.GetLocation();
3700 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003701 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003702 // Take suffix.
3703 const std::string dex_file_suffix = dex_file_location.substr(
3704 dex_file_location.length() - dex_cache_length,
3705 dex_cache_length);
3706 // Example dex_cache location is SettingsProvider.apk and
3707 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003708 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003709 const OatFile* oat_file =
3710 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003711 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3712 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3713 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3714 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003715 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003716 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3717 DexCacheData data = *it;
3718 if (self->IsJWeakCleared(data.weak_root)) {
3719 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003720 it = dex_caches_.erase(it);
3721 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003722 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003723 it->dex_file->GetOatDexFile() != nullptr &&
3724 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003725 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003726 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003727 ++it;
3728 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003729 }
Vladimir Markob066d432018-01-03 13:14:37 +00003730 if (initialize_oat_file_data) {
3731 // Initialize the .data.bimg.rel.ro section.
3732 if (!oat_file->GetBootImageRelocations().empty()) {
3733 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3734 CheckedCall(mprotect,
3735 "un-protect boot image relocations",
3736 reloc_begin,
3737 oat_file->DataBimgRelRoSize(),
3738 PROT_READ | PROT_WRITE);
3739 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3740 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3741 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3742 const_cast<uint32_t&>(relocation) += boot_image_begin;
3743 }
3744 CheckedCall(mprotect,
3745 "protect boot image relocations",
3746 reloc_begin,
3747 oat_file->DataBimgRelRoSize(),
3748 PROT_READ);
3749 }
3750
3751 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003752 // TODO: Pre-initialize from boot/app image?
3753 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3754 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3755 entry = resolution_method;
3756 }
3757 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003758 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003759 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003760 DexCacheData data;
3761 data.weak_root = dex_cache_jweak;
3762 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003763 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003764 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003765 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003766 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3767 // path dex caches without an image.
3768 data.class_table->InsertStrongRoot(dex_cache);
3769 if (class_loader != nullptr) {
3770 // Since we added a strong root to the class table, do the write barrier as required for
3771 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003772 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003773 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003774 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003775}
3776
Vladimir Markocd556b02017-02-03 11:47:34 +00003777ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3778 return data.IsValid()
3779 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3780 : nullptr;
3781}
3782
3783ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3784 Thread* self,
3785 ObjPtr<mirror::DexCache> dex_cache,
3786 const DexCacheData& data,
3787 ObjPtr<mirror::ClassLoader> class_loader) {
3788 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3789 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3790 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3791 "Attempt to register dex file %s with multiple class loaders",
3792 data.dex_file->GetLocation().c_str());
3793 return nullptr;
3794 }
3795 return dex_cache;
3796}
3797
Alex Light07f06212017-06-01 14:01:43 -07003798void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3799 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003800 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003801 Thread* self = Thread::Current();
3802 StackHandleScope<2> hs(self);
3803 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3804 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3805 const DexFile* dex_file = dex_cache->GetDexFile();
3806 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3807 if (kIsDebugBuild) {
3808 DexCacheData old_data;
3809 {
3810 ReaderMutexLock mu(self, *Locks::dex_lock_);
3811 old_data = FindDexCacheDataLocked(*dex_file);
3812 }
3813 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3814 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3815 << "been registered on dex file " << dex_file->GetLocation();
3816 }
3817 ClassTable* table;
3818 {
3819 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3820 table = InsertClassTableForClassLoader(h_class_loader.Get());
3821 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003822 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3823 // a thread holding the dex lock and blocking on a condition variable regarding
3824 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003825 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003826 WriterMutexLock mu(self, *Locks::dex_lock_);
3827 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3828 table->InsertStrongRoot(h_dex_cache.Get());
3829 if (h_class_loader.Get() != nullptr) {
3830 // Since we added a strong root to the class table, do the write barrier as required for
3831 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003832 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003833 }
3834}
3835
Vladimir Markocd556b02017-02-03 11:47:34 +00003836ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3837 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003838 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003839 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003840 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003841 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003842 old_data = FindDexCacheDataLocked(dex_file);
3843 }
3844 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3845 if (old_dex_cache != nullptr) {
3846 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003847 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003848 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003849 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3850 DCHECK(linear_alloc != nullptr);
3851 ClassTable* table;
3852 {
3853 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3854 table = InsertClassTableForClassLoader(class_loader);
3855 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003856 // Don't alloc while holding the lock, since allocation may need to
3857 // suspend all threads and another thread may need the dex_lock_ to
3858 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003859 StackHandleScope<3> hs(self);
3860 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003861 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003862 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3863 self,
3864 dex_file)));
3865 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003866 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003867 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3868 // a thread holding the dex lock and blocking on a condition variable regarding
3869 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003870 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003871 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003872 old_data = FindDexCacheDataLocked(dex_file);
3873 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003874 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003875 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3876 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3877 // that the arrays are null.
3878 mirror::DexCache::InitializeDexCache(self,
3879 h_dex_cache.Get(),
3880 h_location.Get(),
3881 &dex_file,
3882 linear_alloc,
3883 image_pointer_size_);
3884 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003885 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003886 }
3887 if (old_dex_cache != nullptr) {
3888 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3889 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003890 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003891 self->ClearException();
3892 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3893 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3894 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003895 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003896 self->AssertPendingOOMException();
3897 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003898 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003899 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003900 if (h_class_loader.Get() != nullptr) {
3901 // Since we added a strong root to the class table, do the write barrier as required for
3902 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003903 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003904 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003905 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003906}
3907
Vladimir Markocd556b02017-02-03 11:47:34 +00003908bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003909 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003910 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003911}
3912
Vladimir Markocd556b02017-02-03 11:47:34 +00003913ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3914 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003915 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3916 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003917 if (dex_cache != nullptr) {
3918 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003919 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003920 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003921 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003922 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003923 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003924 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003925 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003926 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3927 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003928 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003929}
3930
Vladimir Markocd556b02017-02-03 11:47:34 +00003931ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3932 const DexFile* dex_file = dex_cache->GetDexFile();
3933 DCHECK(dex_file != nullptr);
3934 ReaderMutexLock mu(self, *Locks::dex_lock_);
3935 // Search assuming unique-ness of dex file.
3936 for (const DexCacheData& data : dex_caches_) {
3937 // Avoid decoding (and read barriers) other unrelated dex caches.
3938 if (data.dex_file == dex_file) {
3939 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3940 if (registered_dex_cache != nullptr) {
3941 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3942 return data.class_table;
3943 }
3944 }
3945 }
3946 return nullptr;
3947}
3948
3949ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3950 // Search assuming unique-ness of dex file.
3951 for (const DexCacheData& data : dex_caches_) {
3952 // Avoid decoding (and read barriers) other unrelated dex caches.
3953 if (data.dex_file == &dex_file) {
3954 return data;
3955 }
3956 }
3957 return DexCacheData();
3958}
3959
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003960ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003961 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003962 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003963 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003964 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003965 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003966 }
Ian Rogers1f539342012-10-03 21:09:42 -07003967 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003968 StackHandleScope<1> hs(self);
3969 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003970 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003971 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3972 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003973 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003974 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003975 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003976 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003977 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3978 h_class.Get(),
3979 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003980 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003981 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003982}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003983
Vladimir Marko02610552018-06-04 14:38:00 +01003984inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
3985 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
3986}
3987
Brian Carlstrombe977852011-07-19 14:54:54 -07003988// Create an array class (i.e. the class object for the array, not the
3989// array itself). "descriptor" looks like "[C" or "[[[[B" or
3990// "[Ljava/lang/String;".
3991//
3992// If "descriptor" refers to an array of primitives, look up the
3993// primitive type's internally-generated class object.
3994//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003995// "class_loader" is the class loader of the class that's referring to
3996// us. It's used to ensure that we're looking for the element type in
3997// the right context. It does NOT become the class loader for the
3998// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003999//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004000// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004001ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4002 const char* descriptor,
4003 size_t hash,
4004 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004005 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004006 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004007 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004008
4009 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4010 // code to be executed. We put it up here so we can avoid all the allocations associated with
4011 // creating the class. This can happen with (eg) jit threads.
4012 if (!self->CanLoadClasses()) {
4013 // Make sure we don't try to load anything, potentially causing an infinite loop.
4014 ObjPtr<mirror::Throwable> pre_allocated =
4015 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4016 self->SetException(pre_allocated);
4017 return nullptr;
4018 }
4019
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004020 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4021 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004022 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004023 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004024 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004025 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4026 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004027 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004028 DCHECK(self->IsExceptionPending());
4029 return nullptr;
4030 } else {
4031 self->ClearException();
4032 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004033 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004034 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4035 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4036 return nullptr;
4037 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004038 // See if the component type is already loaded. Array classes are
4039 // always associated with the class loader of their underlying
4040 // element type -- an array of Strings goes with the loader for
4041 // java/lang/String -- so we need to look for it there. (The
4042 // caller should have checked for the existence of the class
4043 // before calling here, but they did so with *their* class loader,
4044 // not the component type's loader.)
4045 //
4046 // If we find it, the caller adds "loader" to the class' initiating
4047 // loader list, which should prevent us from going through this again.
4048 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004049 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004050 // are the same, because our caller (FindClass) just did the
4051 // lookup. (Even if we get this wrong we still have correct behavior,
4052 // because we effectively do this lookup again when we add the new
4053 // class to the hash table --- necessary because of possible races with
4054 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004055 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004056 ObjPtr<mirror::Class> new_class =
4057 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004058 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004059 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004060 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004061 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004062
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004063 // Fill out the fields in the Class.
4064 //
4065 // It is possible to execute some methods against arrays, because
4066 // all arrays are subclasses of java_lang_Object_, so we need to set
4067 // up a vtable. We can just point at the one in java_lang_Object_.
4068 //
4069 // Array classes are simple enough that we don't need to do a full
4070 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004071 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004072 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004073 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004074 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004075 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004076 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004077 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4078 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4079 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004080 } else if (strcmp(descriptor, "[Z") == 0) {
4081 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4082 } else if (strcmp(descriptor, "[B") == 0) {
4083 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4084 } else if (strcmp(descriptor, "[C") == 0) {
4085 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4086 } else if (strcmp(descriptor, "[S") == 0) {
4087 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004088 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004089 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004090 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004091 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004092 } else if (strcmp(descriptor, "[F") == 0) {
4093 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4094 } else if (strcmp(descriptor, "[D") == 0) {
4095 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004096 }
4097 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004098 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004099 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004100 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004101 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004102 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004103 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004104 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004105 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004106 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004107 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004108 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004109 new_class->SetSuperClass(java_lang_Object);
4110 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004111 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004112 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004113 if (component_type->IsPrimitive()) {
4114 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4115 } else {
4116 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4117 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004118 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004119 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4120 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4121 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004122 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004123 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004124 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004125 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004126
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004127 // All arrays have java/lang/Cloneable and java/io/Serializable as
4128 // interfaces. We need to set that up here, so that stuff like
4129 // "instanceof" works right.
4130 //
4131 // Note: The GC could run during the call to FindSystemClass,
4132 // so we need to make sure the class object is GC-valid while we're in
4133 // there. Do this by clearing the interface list so the GC will just
4134 // think that the entries are null.
4135
4136
4137 // Use the single, global copies of "interfaces" and "iftable"
4138 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004139 {
Vladimir Marko02610552018-06-04 14:38:00 +01004140 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004141 CHECK(array_iftable != nullptr);
4142 new_class->SetIfTable(array_iftable);
4143 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004144
Elliott Hughes00626c22013-06-14 15:04:14 -07004145 // Inherit access flags from the component type.
4146 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4147 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4148 access_flags &= kAccJavaFlagsMask;
4149 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004150 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004151 access_flags |= kAccAbstract | kAccFinal;
4152 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004153 // Arrays are access-checks-clean and preverified.
4154 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004155
4156 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004157
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004158 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004159 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004160 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4161 // duplicate events in case of races. Array classes don't really follow dedicated
4162 // load and prepare, anyways.
4163 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4164 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4165
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004166 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004167 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004168 }
4169 // Another thread must have loaded the class after we
4170 // started but before we finished. Abandon what we've
4171 // done.
4172 //
4173 // (Yes, this happens.)
4174
Vladimir Markobcf17522018-06-01 13:14:32 +01004175 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004176}
4177
Vladimir Marko9186b182018-11-06 14:55:54 +00004178ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4179 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004180 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004181 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4182 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4183 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4184 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4185 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4186 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4187 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4188 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4189 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004190 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004191 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004192 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004193 return GetClassRoot(class_root, this);
4194}
4195
4196ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4197 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4198 if (UNLIKELY(result == nullptr)) {
4199 std::string printable_type(PrintableChar(type));
4200 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4201 }
4202 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004203}
4204
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004205ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4206 ObjPtr<mirror::Class> klass,
4207 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004208 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004209 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004210 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004211 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004212 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004213 source += " from ";
4214 source += dex_cache->GetLocation()->ToModifiedUtf8();
4215 }
4216 LOG(INFO) << "Loaded class " << descriptor << source;
4217 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004218 {
4219 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004220 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004221 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004222 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004223 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004224 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004225 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004226 VerifyObject(klass);
4227 class_table->InsertWithHash(klass, hash);
4228 if (class_loader != nullptr) {
4229 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004230 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004231 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004232 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004233 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004234 }
4235 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004236 if (kIsDebugBuild) {
4237 // Test that copied methods correctly can find their holder.
4238 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4239 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4240 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004241 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004242 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004243}
4244
Vladimir Marko1998cd02017-01-13 13:02:58 +00004245void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004246 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4247 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4248 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4249 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004250 }
4251}
4252
Alex Lighte64300b2015-12-15 15:02:47 -08004253// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004254void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004255 LengthPrefixedArray<ArtMethod>* new_methods) {
4256 klass->SetMethodsPtrUnchecked(new_methods,
4257 klass->NumDirectMethods(),
4258 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004259 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004260 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004261}
4262
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004263ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4264 const char* descriptor,
4265 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004266 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4267}
4268
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004269ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4270 const char* descriptor,
4271 size_t hash,
4272 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004273 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4274 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4275 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004276 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004277 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004278 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004279 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004280 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004281 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004282}
4283
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004284class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4285 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004286 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004287
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004288 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004289 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004290 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004291 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004292 if (class_table != nullptr) {
4293 class_table->FreezeSnapshot();
4294 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004295 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004296};
4297
4298void ClassLinker::MoveClassTableToPreZygote() {
4299 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004300 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004301 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004302 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004303}
4304
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004305// Look up classes by hash and descriptor and put all matching ones in the result array.
4306class LookupClassesVisitor : public ClassLoaderVisitor {
4307 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004308 LookupClassesVisitor(const char* descriptor,
4309 size_t hash,
4310 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004311 : descriptor_(descriptor),
4312 hash_(hash),
4313 result_(result) {}
4314
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004315 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004316 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004317 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004318 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004319 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4320 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004321 result_->push_back(klass);
4322 }
4323 }
4324
4325 private:
4326 const char* const descriptor_;
4327 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004328 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004329};
4330
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004331void ClassLinker::LookupClasses(const char* descriptor,
4332 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004333 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004334 Thread* const self = Thread::Current();
4335 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004336 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004337 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004338 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004339 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004340 result.push_back(klass);
4341 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004342 LookupClassesVisitor visitor(descriptor, hash, &result);
4343 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004344}
4345
Alex Lightf1f10492015-10-07 16:08:36 -07004346bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4347 Handle<mirror::Class> klass,
4348 Handle<mirror::Class> supertype) {
4349 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004350 DCHECK(klass != nullptr);
4351 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004352
Alex Lightf1f10492015-10-07 16:08:36 -07004353 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4354 VerifyClass(self, supertype);
4355 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004356
4357 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4358 // The supertype is either verified, or we soft failed at AOT time.
4359 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004360 return true;
4361 }
4362 // If we got this far then we have a hard failure.
4363 std::string error_msg =
4364 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004365 klass->PrettyDescriptor().c_str(),
4366 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004367 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004368 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004369 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004370 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004371 // Set during VerifyClass call (if at all).
4372 self->ClearException();
4373 }
4374 // Change into a verify error.
4375 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004376 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004377 self->GetException()->SetCause(cause.Get());
4378 }
4379 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4380 if (Runtime::Current()->IsAotCompiler()) {
4381 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4382 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004383 // Need to grab the lock to change status.
4384 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004385 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004386 return false;
4387}
4388
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004389verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004390 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004391 {
4392 // TODO: assert that the monitor on the Class is held
4393 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004394
Andreas Gampe884f3b82016-03-30 19:52:58 -07004395 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004396 ClassStatus old_status = klass->GetStatus();
4397 while (old_status == ClassStatus::kVerifying ||
4398 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004399 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004400 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4401 // case we may see the same status again. b/62912904. This is why the check is
4402 // greater or equal.
4403 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004404 << "Class '" << klass->PrettyClass()
4405 << "' performed an illegal verification state transition from " << old_status
4406 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004407 old_status = klass->GetStatus();
4408 }
jeffhao98eacac2011-09-14 16:11:53 -07004409
Andreas Gampe884f3b82016-03-30 19:52:58 -07004410 // The class might already be erroneous, for example at compile time if we attempted to verify
4411 // this class as a parent to another.
4412 if (klass->IsErroneous()) {
4413 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004414 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004415 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004416
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004417 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004418 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004419 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004420 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004421 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004422
4423 // For AOT, don't attempt to re-verify if we have already found we should
4424 // verify at runtime.
4425 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004426 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004427 }
jeffhao98eacac2011-09-14 16:11:53 -07004428
Vladimir Marko2c64a832018-01-04 11:31:56 +00004429 if (klass->GetStatus() == ClassStatus::kResolved) {
4430 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004431 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004432 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004433 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004434 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004435 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004436 }
4437
4438 // Skip verification if disabled.
4439 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004440 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004441 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004442 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004443 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004444 }
4445
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004446 VLOG(class_linker) << "Beginning verification for class: "
4447 << klass->PrettyDescriptor()
4448 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4449
Ian Rogers9ffb0392012-09-10 11:56:50 -07004450 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004451 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004452 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4453 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004454 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004455 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004456 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004457 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004458
Alex Lightf1f10492015-10-07 16:08:36 -07004459 // Verify all default super-interfaces.
4460 //
4461 // (1) Don't bother if the superclass has already had a soft verification failure.
4462 //
4463 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4464 // recursive initialization by themselves. This is because when an interface is initialized
4465 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4466 // but choose not to for an optimization. If the interfaces is being verified due to a class
4467 // initialization (which would need all the default interfaces to be verified) the class code
4468 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004469 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004470 && !klass->IsInterface()) { // See (2)
4471 int32_t iftable_count = klass->GetIfTableCount();
4472 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4473 // Loop through all interfaces this class has defined. It doesn't matter the order.
4474 for (int32_t i = 0; i < iftable_count; i++) {
4475 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004476 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004477 // We only care if we have default interfaces and can skip if we are already verified...
4478 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4479 continue;
4480 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4481 // We had a hard failure while verifying this interface. Just return immediately.
4482 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004483 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004484 } else if (UNLIKELY(!iface->IsVerified())) {
4485 // We softly failed to verify the iface. Stop checking and clean up.
4486 // Put the iface into the supertype handle so we know what caused us to fail.
4487 supertype.Assign(iface.Get());
4488 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004489 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004490 }
4491 }
4492
Alex Lightf1f10492015-10-07 16:08:36 -07004493 // At this point if verification failed, then supertype is the "first" supertype that failed
4494 // verification (without a specific order). If verification succeeded, then supertype is either
4495 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004496 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004497 supertype.Get() == klass->GetSuperClass() ||
4498 !supertype->IsVerified());
4499
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004500 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004501 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004502 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004503 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004504
4505 VLOG(class_linker) << "Class preverified status for class "
4506 << klass->PrettyDescriptor()
4507 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4508 << ": "
4509 << preverified;
4510
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004511 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4512 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004513 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4514 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004515
Ian Rogers62d6c772013-02-27 08:32:07 -08004516 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004517 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004518 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004519 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004520 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004521
4522 // Verification is done, grab the lock again.
4523 ObjectLock<mirror::Class> lock(self, klass);
4524
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004525 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4526 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004527 VLOG(class_linker) << "Soft verification failure in class "
4528 << klass->PrettyDescriptor()
4529 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4530 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004531 }
Ian Rogers1f539342012-10-03 21:09:42 -07004532 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004533 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004534 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004535 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004536 // Even though there were no verifier failures we need to respect whether the super-class and
4537 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004538 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004539 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004540 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004541 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4542 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004543 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004544 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004545 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004546 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004547 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004548 // Soft failures at compile time should be retried at runtime. Soft
4549 // failures at runtime will be handled by slow paths in the generated
4550 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004551 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004552 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004553 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004554 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004555 // As this is a fake verified status, make sure the methods are _not_ marked
4556 // kAccSkipAccessChecks later.
4557 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004558 }
4559 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004560 } else {
David Sehr709b0702016-10-13 09:12:37 -07004561 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004562 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4563 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004564 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004565 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004566 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004567 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004568 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004569 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004570 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004571 // method.
4572 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004573 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004574 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004575
4576 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4577 // Never skip access checks if the verification soft fail is forced.
4578 // Mark the class as having a verification attempt to avoid re-running the verifier.
4579 klass->SetVerificationAttempted();
4580 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004581 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004582 }
Andreas Gampe48498592014-09-10 19:48:05 -07004583 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004584 // Done verifying. Notify the compiler about the verification status, in case the class
4585 // was verified implicitly (eg super class of a compiled class).
4586 if (Runtime::Current()->IsAotCompiler()) {
4587 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4588 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4589 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004590 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004591}
4592
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004593verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4594 Handle<mirror::Class> klass,
4595 verifier::HardFailLogMode log_level,
4596 std::string* error_msg) {
4597 Runtime* const runtime = Runtime::Current();
4598 return verifier::MethodVerifier::VerifyClass(self,
4599 klass.Get(),
4600 runtime->GetCompilerCallbacks(),
4601 runtime->IsAotCompiler(),
4602 log_level,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07004603 Runtime::Current()->GetTargetSdkVersion(),
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004604 error_msg);
4605}
4606
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004607bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004608 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004609 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004610 // If we're compiling, we can only verify the class using the oat file if
4611 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004612 // the compilation unit (app - dependencies). We will let the compiler callback
4613 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004614 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004615 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004616 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004617 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004618 return false;
4619 }
4620 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004621 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004622 return false;
4623 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004624 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004625
Andreas Gampeb40d3612018-06-26 15:49:42 -07004626 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004627 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004628 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004629 return false;
4630 }
4631
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004632 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004633 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004634 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004635 return true;
4636 }
4637 // If we only verified a subset of the classes at compile time, we can end up with classes that
4638 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004639 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004640 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004641 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004642 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004643 // Compile time verification failed with a soft error. Compile time verification can fail
4644 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004645 // class ... {
4646 // Foo x;
4647 // .... () {
4648 // if (...) {
4649 // v1 gets assigned a type of resolved class Foo
4650 // } else {
4651 // v1 gets assigned a type of unresolved class Bar
4652 // }
4653 // iput x = v1
4654 // } }
4655 // when we merge v1 following the if-the-else it results in Conflict
4656 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4657 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4658 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4659 // at compile time).
4660 return false;
4661 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004662 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004663 // Compile time verification failed with a hard error. This is caused by invalid instructions
4664 // in the class. These errors are unrecoverable.
4665 return false;
4666 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004667 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004668 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4669 // not loading the class.
4670 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4671 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004672 return false;
4673 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004674 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004675 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004676 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004677 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004678 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004679}
4680
Alex Light5a559862016-01-29 12:24:48 -08004681void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004682 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004683 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004684 }
4685}
4686
Alex Light5a559862016-01-29 12:24:48 -08004687void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004688 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004689 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004690 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004691 return; // native or abstract method
4692 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004693 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004694 return; // nothing to process
4695 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004696 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004697 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004698 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4699 CatchHandlerIterator iterator(handlers_ptr);
4700 for (; iterator.HasNext(); iterator.Next()) {
4701 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4702 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004703 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004704 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004705 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004706 DCHECK(Thread::Current()->IsExceptionPending());
4707 Thread::Current()->ClearException();
4708 }
4709 }
4710 }
4711 handlers_ptr = iterator.EndDataPointer();
4712 }
4713}
4714
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004715ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4716 jstring name,
4717 jobjectArray interfaces,
4718 jobject loader,
4719 jobjectArray methods,
4720 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004721 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004722
4723 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4724 // code to be executed. We put it up here so we can avoid all the allocations associated with
4725 // creating the class. This can happen with (eg) jit-threads.
4726 if (!self->CanLoadClasses()) {
4727 // Make sure we don't try to load anything, potentially causing an infinite loop.
4728 ObjPtr<mirror::Throwable> pre_allocated =
4729 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4730 self->SetException(pre_allocated);
4731 return nullptr;
4732 }
4733
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004734 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004735 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004736 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004737 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004738 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004739 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004740 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004741 DCHECK(temp_klass->GetClass() != nullptr);
4742 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004743 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4744 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004745 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4746 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4747 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4748 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004749 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004750 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004751 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004752 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004753 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004754 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004755
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004756 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004757 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004758
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004759 // Insert the class before loading the fields as the field roots
4760 // (ArtField::declaring_class_) are only visited from the class
4761 // table. There can't be any suspend points between inserting the
4762 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004763 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004764 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004765
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004766 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004767 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004768 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004769 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004770
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004771 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4772 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004773 ArtField& interfaces_sfield = sfields->At(0);
4774 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004775 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004776 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004777
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004778 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004779 ArtField& throws_sfield = sfields->At(1);
4780 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004781 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004782 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004783
Ian Rogers466bb252011-10-14 03:29:56 -07004784 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004785 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004786
Alex Lighte64300b2015-12-15 15:02:47 -08004787 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004788 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004789 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004790 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004791 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004792
4793 // Create the methods array.
4794 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4795 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004796 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4797 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004798 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004799 self->AssertPendingOOMException();
4800 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004801 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004802 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004803
4804 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004805 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004806
4807 // Create virtual method using specified prototypes.
4808 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004809 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004810 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004811 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004812 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004813 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4814 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004815 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004816
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004817 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004818 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004819 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004820 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004821 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004822
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004823 // At this point the class is loaded. Publish a ClassLoad event.
4824 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4825 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4826
4827 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004828 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004829 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004830 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004831 // Link the fields and virtual methods, creating vtable and iftables.
4832 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004833 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004834 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004835 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004836 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004837 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004838 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004839 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004840 CHECK(temp_klass->IsRetired());
4841 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004842
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004843 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004844 interfaces_sfield.SetObject<false>(
4845 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004846 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004847 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4848 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004849 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004850 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004851
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004852 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4853
Vladimir Marko305c38b2018-02-14 11:50:07 +00004854 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4855 // See also ClassLinker::EnsureInitialized().
4856 if (kBitstringSubtypeCheckEnabled) {
4857 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4858 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4859 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4860 }
4861
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004862 {
4863 // Lock on klass is released. Lock new class object.
4864 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004865 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004866 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004867 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004868
4869 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004870 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004871 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004872 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4873
Ian Rogersc2b44472011-12-14 21:17:17 -08004874 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004875 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4876 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004877 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004878 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004879
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004880 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004881 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004882 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004883 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004884 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004885
4886 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004887 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004888 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004889
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004890 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004891 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004892 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004893 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004894 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004895 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004896}
4897
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004898std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004899 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004900 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004901 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004902 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4903}
4904
Mathieu Chartiere401d142015-04-22 13:56:20 -07004905void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4906 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004907 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4908 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004909
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004910 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4911 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004912 ArtMethod* proxy_constructor =
4913 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004914 DCHECK(proxy_constructor != nullptr)
4915 << "Could not find <init> method in java.lang.reflect.Proxy";
4916
Jeff Haodb8a6642014-08-14 17:18:52 -07004917 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4918 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004919 DCHECK(out != nullptr);
4920 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004921 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004922 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004923 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004924 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4925 kAccPublic |
4926 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004927 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004928
4929 // Set the original constructor method.
4930 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004931}
4932
Mathieu Chartiere401d142015-04-22 13:56:20 -07004933void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004934 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004935 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4936 CHECK_STREQ(np->GetName(), "<init>");
4937 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004938 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004939}
4940
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004941void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004942 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004943 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004944 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004945 DCHECK(out != nullptr);
4946 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004947
Alex Lighte9dd04f2016-03-16 16:09:45 -07004948 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004949 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004950 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4951 // preference to the invocation handler.
4952 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4953 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004954 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4955 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004956 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4957
4958 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4959 // method they copy might (if it's a default method).
4960 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004961
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004962 // Set the original interface method.
4963 out->SetDataPtrSize(prototype, image_pointer_size_);
4964
Ian Rogers466bb252011-10-14 03:29:56 -07004965 // At runtime the method looks like a reference and argument saving method, clone the code
4966 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004967 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004968}
Jesse Wilson95caa792011-10-12 18:14:17 -04004969
Mathieu Chartiere401d142015-04-22 13:56:20 -07004970void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004971 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004972 CHECK(!prototype->IsFinal());
4973 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004974 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004975
4976 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4977 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004978 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004979 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004980}
4981
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004982bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004983 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004984 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004985 return true;
4986 }
4987 if (!can_init_statics) {
4988 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004989 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004990 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004991 return false;
4992 }
4993 // Check if there are encoded static values needing initialization.
4994 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004995 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004996 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004997 if (dex_class_def->static_values_off_ != 0) {
4998 return false;
4999 }
5000 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005001 // If we are a class we need to initialize all interfaces with default methods when we are
5002 // initialized. Check all of them.
5003 if (!klass->IsInterface()) {
5004 size_t num_interfaces = klass->GetIfTableCount();
5005 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005006 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005007 if (iface->HasDefaultMethods() &&
5008 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5009 return false;
5010 }
5011 }
5012 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005013 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005014 if (klass->IsInterface() || !klass->HasSuperClass()) {
5015 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005016 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005017 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005018 if (!can_init_parents && !super_class->IsInitialized()) {
5019 return false;
5020 }
5021 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005022}
5023
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005024bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5025 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005026 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5027
5028 // Are we already initialized and therefore done?
5029 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5030 // an initialized class will never change its state.
5031 if (klass->IsInitialized()) {
5032 return true;
5033 }
5034
5035 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005036 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005037 return false;
5038 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005039
Ian Rogers7b078e82014-09-10 14:44:24 -07005040 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005041 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005042 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005043 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005044
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005045 // Re-check under the lock in case another thread initialized ahead of us.
5046 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005047 return true;
5048 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005049
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005050 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005051 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005052 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005053 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005054 return false;
5055 }
5056
Vladimir Marko72ab6842017-01-20 19:32:50 +00005057 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5058 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005059
5060 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005061 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005062 if (!klass->IsVerified()) {
5063 // We failed to verify, expect either the klass to be erroneous or verification failed at
5064 // compile time.
5065 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005066 // The class is erroneous. This may be a verifier error, or another thread attempted
5067 // verification and/or initialization and failed. We can distinguish those cases by
5068 // whether an exception is already pending.
5069 if (self->IsExceptionPending()) {
5070 // Check that it's a VerifyError.
5071 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005072 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005073 } else {
5074 // Check that another thread attempted initialization.
5075 DCHECK_NE(0, klass->GetClinitThreadId());
5076 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5077 // Need to rethrow the previous failure now.
5078 ThrowEarlierClassFailure(klass.Get(), true);
5079 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005080 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005081 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005082 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005083 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005084 self->AssertNoPendingException();
5085 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005086 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005087 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005088 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005089 } else {
5090 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005091 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005092
5093 // A separate thread could have moved us all the way to initialized. A "simple" example
5094 // involves a subclass of the current class being initialized at the same time (which
5095 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005096 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005097 if (klass->IsInitialized()) {
5098 return true;
5099 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005100 }
5101
Vladimir Marko2c64a832018-01-04 11:31:56 +00005102 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005103 // initializing higher up the stack or another thread has beat us
5104 // to initializing and we need to wait. Either way, this
5105 // invocation of InitializeClass will not be responsible for
5106 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005107 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005108 // Could have got an exception during verification.
5109 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005110 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005111 return false;
5112 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005113 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005114 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005115 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005116 return true;
5117 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005118 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005119 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005120 }
5121
Jeff Haoe2e40342017-07-19 10:45:18 -07005122 // Try to get the oat class's status for this class if the oat file is present. The compiler
5123 // tries to validate superclass descriptors, and writes the result into the oat file.
5124 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5125 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5126 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005127 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005128 const Runtime* runtime = Runtime::Current();
5129 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5130 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5131 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005132 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005133 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005134 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005135 return false;
5136 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005137 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005138
Vladimir Marko2c64a832018-01-04 11:31:56 +00005139 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005140 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005141
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005142 // From here out other threads may observe that we're initializing and so changes of state
5143 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005144 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005145 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005146
5147 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005148 }
5149
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005150 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005151 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005152 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005153 if (!super_class->IsInitialized()) {
5154 CHECK(!super_class->IsInterface());
5155 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005156 StackHandleScope<1> hs(self);
5157 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005158 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005159 if (!super_initialized) {
5160 // The super class was verified ahead of entering initializing, we should only be here if
5161 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005162 // For the case of aot compiler, the super class might also be initializing but we don't
5163 // want to process circular dependencies in pre-compile.
5164 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005165 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005166 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005167 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005168 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005169 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005170 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005171 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005172 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005173 return false;
5174 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005176 }
5177
Alex Lighteb7c1442015-08-31 13:17:42 -07005178 if (!klass->IsInterface()) {
5179 // Initialize interfaces with default methods for the JLS.
5180 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005181 // Only setup the (expensive) handle scope if we actually need to.
5182 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005183 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005184 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5185 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005186 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005187 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005188 CHECK(handle_scope_iface->IsInterface());
5189 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5190 // We have already done this for this interface. Skip it.
5191 continue;
5192 }
5193 // We cannot just call initialize class directly because we need to ensure that ALL
5194 // interfaces with default methods are initialized. Non-default interface initialization
5195 // will not affect other non-default super-interfaces.
5196 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5197 handle_scope_iface,
5198 can_init_statics,
5199 can_init_parents);
5200 if (!iface_initialized) {
5201 ObjectLock<mirror::Class> lock(self, klass);
5202 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005203 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005204 return false;
5205 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005206 }
5207 }
5208 }
5209
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005210 const size_t num_static_fields = klass->NumStaticFields();
5211 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005212 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005213 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005214 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005215 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005216 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005217
5218 // Eagerly fill in static fields so that the we don't have to do as many expensive
5219 // Class::FindStaticField in ResolveField.
5220 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005221 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005222 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005223 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005224 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005225 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005226 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5227 field,
5228 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5229 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005230 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005231 } else {
5232 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005233 }
5234 }
5235
Vladimir Markoe11dd502017-12-08 14:09:45 +00005236 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5237 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005238 this,
5239 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005240 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005241
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005242 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005243 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005244 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005245 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5246 if (!value_it.HasNext()) {
5247 break;
5248 }
5249 ArtField* art_field = ResolveField(field.GetIndex(),
5250 dex_cache,
5251 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005252 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005253 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005254 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005255 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005256 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005257 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005258 if (self->IsExceptionPending()) {
5259 break;
5260 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005261 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005262 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005263 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005264 }
5265 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005266
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005267
Mathieu Chartierda595be2016-08-10 13:57:39 -07005268 if (!self->IsExceptionPending()) {
5269 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5270 if (clinit != nullptr) {
5271 CHECK(can_init_statics);
5272 JValue result;
5273 clinit->Invoke(self, nullptr, 0, &result, "V");
5274 }
5275 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005276 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005277 uint64_t t1 = NanoTime();
5278
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005279 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005280 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005281 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005282
5283 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005284 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005285 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005286 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005287 } else if (Runtime::Current()->IsTransactionAborted()) {
5288 // The exception thrown when the transaction aborted has been caught and cleared
5289 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005290 VLOG(compiler) << "Return from class initializer of "
5291 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005292 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005293 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005294 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005295 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005296 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005297 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5298 RuntimeStats* thread_stats = self->GetStats();
5299 ++global_stats->class_init_count;
5300 ++thread_stats->class_init_count;
5301 global_stats->class_init_time_ns += (t1 - t0);
5302 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005303 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005304 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005305 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005306 std::string temp;
5307 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005308 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005309 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005310 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005311 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005312 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005313 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005314 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005315}
5316
Alex Lighteb7c1442015-08-31 13:17:42 -07005317// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5318// and perform the initialization only on those interfaces that contain default methods.
5319bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5320 Handle<mirror::Class> iface,
5321 bool can_init_statics,
5322 bool can_init_parents) {
5323 CHECK(iface->IsInterface());
5324 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005325 // Only create the (expensive) handle scope if we need it.
5326 if (UNLIKELY(num_direct_ifaces > 0)) {
5327 StackHandleScope<1> hs(self);
5328 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5329 // First we initialize all of iface's super-interfaces recursively.
5330 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005331 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005332 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005333 if (!super_iface->HasBeenRecursivelyInitialized()) {
5334 // Recursive step
5335 handle_super_iface.Assign(super_iface);
5336 if (!InitializeDefaultInterfaceRecursive(self,
5337 handle_super_iface,
5338 can_init_statics,
5339 can_init_parents)) {
5340 return false;
5341 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005342 }
5343 }
5344 }
5345
5346 bool result = true;
5347 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5348 // initialize if we don't have default methods.
5349 if (iface->HasDefaultMethods()) {
5350 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5351 }
5352
5353 // Mark that this interface has undergone recursive default interface initialization so we know we
5354 // can skip it on any later class initializations. We do this even if we are not a default
5355 // interface since we can still avoid the traversal. This is purely a performance optimization.
5356 if (result) {
5357 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005358 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5359 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5360 // initialization is a performance optimization (to avoid another idempotent visit
5361 // for other implementing classes/interfaces), and can be revisited later.
5362 ObjectTryLock<mirror::Class> lock(self, iface);
5363 if (lock.Acquired()) {
5364 iface->SetRecursivelyInitialized();
5365 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005366 }
5367 return result;
5368}
5369
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005370bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5371 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005372 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005373 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005374 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005375 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005376 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005377 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005378
5379 // When we wake up, repeat the test for init-in-progress. If
5380 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005381 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005382 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005383 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005384 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005385 return false;
5386 }
5387 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005388 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005389 continue;
5390 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005391 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005392 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005393 // Compile time initialization failed.
5394 return false;
5395 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005396 if (klass->IsErroneous()) {
5397 // The caller wants an exception, but it was thrown in a
5398 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005399 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005400 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005401 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005402 return false;
5403 }
5404 if (klass->IsInitialized()) {
5405 return true;
5406 }
David Sehr709b0702016-10-13 09:12:37 -07005407 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005408 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005409 }
Ian Rogers07140832014-09-30 15:43:59 -07005410 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005411}
5412
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005413static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5414 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005415 ArtMethod* method,
5416 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005417 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005418 DCHECK(Thread::Current()->IsExceptionPending());
5419 DCHECK(!m->IsProxyMethod());
5420 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005421 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5422 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005423 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005424 std::string return_type = dex_file->PrettyType(return_type_idx);
5425 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005426 ThrowWrappedLinkageError(klass.Get(),
5427 "While checking class %s method %s signature against %s %s: "
5428 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005429 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5430 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005431 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005432 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005433 return_type.c_str(), class_loader.c_str());
5434}
5435
5436static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5437 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005438 ArtMethod* method,
5439 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005440 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005441 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005442 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005443 DCHECK(Thread::Current()->IsExceptionPending());
5444 DCHECK(!m->IsProxyMethod());
5445 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005446 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5447 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005448 ThrowWrappedLinkageError(klass.Get(),
5449 "While checking class %s method %s signature against %s %s: "
5450 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005451 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5452 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005453 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005454 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005455 index, arg_type.c_str(), class_loader.c_str());
5456}
5457
5458static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5459 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005460 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005461 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005462 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005463 ThrowLinkageError(klass.Get(),
5464 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005465 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5466 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005467 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005468 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005469 error_msg.c_str());
5470}
5471
Ian Rogersb5fb2072014-12-02 17:22:02 -08005472static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005473 Handle<mirror::Class> klass,
5474 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005475 ArtMethod* method1,
5476 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005477 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005478 {
5479 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005480 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005481 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005482 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005483 return false;
5484 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005485 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005486 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005487 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005488 return false;
5489 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005490 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005491 ThrowSignatureMismatch(klass, super_klass, method1,
5492 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005493 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005494 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005495 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005496 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005497 return false;
5498 }
5499 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005500 const dex::TypeList* types1 = method1->GetParameterTypeList();
5501 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005502 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005503 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005504 ThrowSignatureMismatch(klass, super_klass, method1,
5505 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005506 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005507 return false;
5508 }
5509 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005510 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005511 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005512 ThrowSignatureMismatch(klass, super_klass, method1,
5513 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005514 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005515 return false;
5516 }
5517 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005518 }
5519 uint32_t num_types = types1->Size();
5520 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005521 ThrowSignatureMismatch(klass, super_klass, method1,
5522 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005523 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005524 return false;
5525 }
5526 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005527 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005528 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005529 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005530 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005531 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005532 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005533 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005534 return false;
5535 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005536 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005537 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005538 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005539 if (UNLIKELY(other_param_type == nullptr)) {
5540 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005541 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005542 return false;
5543 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005544 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005545 ThrowSignatureMismatch(klass, super_klass, method1,
5546 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5547 i,
David Sehr709b0702016-10-13 09:12:37 -07005548 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005549 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005550 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005551 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005552 return false;
5553 }
5554 }
5555 return true;
5556}
5557
5558
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005559bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005560 if (klass->IsInterface()) {
5561 return true;
5562 }
Ian Rogers151f2212014-05-06 11:27:27 -07005563 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005564 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005565 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005566 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005567 if (klass->HasSuperClass() &&
5568 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005569 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005570 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005571 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5572 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5573 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005574 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5575 klass,
5576 super_klass,
5577 m,
5578 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005579 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005580 return false;
5581 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005582 }
5583 }
5584 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005585 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005586 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5587 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5588 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005589 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005590 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5591 j, image_pointer_size_);
5592 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5593 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005594 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5595 klass,
5596 super_klass,
5597 m,
5598 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005599 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005600 return false;
5601 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005602 }
5603 }
5604 }
5605 }
5606 return true;
5607}
5608
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005609bool ClassLinker::EnsureInitialized(Thread* self,
5610 Handle<mirror::Class> c,
5611 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005612 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005613 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005614
Mathieu Chartier524507a2014-08-27 15:28:28 -07005615 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005616 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005617 return true;
5618 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005619 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5620 //
5621 // Ensure the bitstring is initialized before any of the class initialization
5622 // logic occurs. Once a class initializer starts running, objects can
5623 // escape into the heap and use the subtype checking code.
5624 //
5625 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5626 // can be used as a source for the IsSubClass check, and that all ancestors
5627 // of the class are Assigned (can be used as a target for IsSubClass check)
5628 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005629 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005630 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005631 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005632 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5633 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005634 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005635 if (!success) {
5636 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005637 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005638 }
5639 } else {
5640 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005641 }
5642 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005643}
5644
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005645void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5646 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005647 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005648 for (ArtField& field : new_class->GetIFields()) {
5649 if (field.GetDeclaringClass() == temp_class) {
5650 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005651 }
5652 }
5653
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005654 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005655 for (ArtField& field : new_class->GetSFields()) {
5656 if (field.GetDeclaringClass() == temp_class) {
5657 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005658 }
5659 }
5660
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005661 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005662 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005663 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005664 if (method.GetDeclaringClass() == temp_class) {
5665 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005666 }
5667 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005668
5669 // Make sure the remembered set and mod-union tables know that we updated some of the native
5670 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005671 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005672}
5673
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005674void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005675 CHECK(class_loader->GetAllocator() == nullptr);
5676 CHECK(class_loader->GetClassTable() == nullptr);
5677 Thread* const self = Thread::Current();
5678 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005679 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005680 // Create and set the class table.
5681 data.class_table = new ClassTable;
5682 class_loader->SetClassTable(data.class_table);
5683 // Create and set the linear allocator.
5684 data.allocator = Runtime::Current()->CreateLinearAlloc();
5685 class_loader->SetAllocator(data.allocator);
5686 // Add to the list so that we know to free the data later.
5687 class_loaders_.push_back(data);
5688}
5689
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005690ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005691 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005692 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005693 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005694 ClassTable* class_table = class_loader->GetClassTable();
5695 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005696 RegisterClassLoader(class_loader);
5697 class_table = class_loader->GetClassTable();
5698 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005699 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005700 return class_table;
5701}
5702
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005703ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005704 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005705}
5706
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005707static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005708 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005709 while (klass->HasSuperClass()) {
5710 klass = klass->GetSuperClass();
5711 if (klass->ShouldHaveImt()) {
5712 return klass->GetImt(pointer_size);
5713 }
5714 }
5715 return nullptr;
5716}
5717
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005718bool ClassLinker::LinkClass(Thread* self,
5719 const char* descriptor,
5720 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005721 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005722 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005723 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005724
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005725 if (!LinkSuperClass(klass)) {
5726 return false;
5727 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005728 ArtMethod* imt_data[ImTable::kSize];
5729 // If there are any new conflicts compared to super class.
5730 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005731 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005732 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005733 return false;
5734 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005735 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005736 return false;
5737 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005738 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005739 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005740 return false;
5741 }
5742 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005743 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005744
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005745 ImTable* imt = nullptr;
5746 if (klass->ShouldHaveImt()) {
5747 // If there are any new conflicts compared to the super class we can not make a copy. There
5748 // can be cases where both will have a conflict method at the same slot without having the same
5749 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5750 // will possibly create a table that is incorrect for either of the classes.
5751 // Same IMT with new_conflict does not happen very often.
5752 if (!new_conflict) {
5753 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5754 if (super_imt != nullptr) {
5755 bool imt_equals = true;
5756 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5757 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5758 }
5759 if (imt_equals) {
5760 imt = super_imt;
5761 }
5762 }
5763 }
5764 if (imt == nullptr) {
5765 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5766 imt = reinterpret_cast<ImTable*>(
5767 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5768 if (imt == nullptr) {
5769 return false;
5770 }
5771 imt->Populate(imt_data, image_pointer_size_);
5772 }
5773 }
5774
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005775 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5776 // We don't need to retire this class as it has no embedded tables or it was created the
5777 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005778 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005779
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005780 if (klass->ShouldHaveEmbeddedVTable()) {
5781 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005782 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005783 if (klass->ShouldHaveImt()) {
5784 klass->SetImt(imt, image_pointer_size_);
5785 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005786
5787 // Update CHA info based on whether we override methods.
5788 // Have to do this before setting the class as resolved which allows
5789 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005790 if (cha_ != nullptr) {
5791 cha_->UpdateAfterLoadingOf(klass);
5792 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005793
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005794 // This will notify waiters on klass that saw the not yet resolved
5795 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005796 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005797 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005798 } else {
5799 CHECK(!klass->IsResolved());
5800 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005801 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005802 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005803 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5804 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5805 // may not see any references to the target space and clean the card for a class if another
5806 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005807 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005808 klass->SetSFieldsPtrUnchecked(nullptr);
5809 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005810 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005811 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005812 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005813 return false;
5814 }
5815
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005816 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5817 ObjectLock<mirror::Class> lock(self, h_new_class);
5818 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005819
5820 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005821 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005822 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005823 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005824 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005825 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005826 if (class_loader != nullptr) {
5827 // We updated the class in the class table, perform the write barrier so that the GC knows
5828 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005829 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005830 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005831 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005832 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005833 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5834 }
5835 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005836
Mingyao Yang063fc772016-08-02 11:02:54 -07005837 // Update CHA info based on whether we override methods.
5838 // Have to do this before setting the class as resolved which allows
5839 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005840 if (cha_ != nullptr) {
5841 cha_->UpdateAfterLoadingOf(h_new_class);
5842 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005843
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005844 // This will notify waiters on temp class that saw the not yet resolved class in the
5845 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005846 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005847
Vladimir Marko2c64a832018-01-04 11:31:56 +00005848 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005849 // This will notify waiters on new_class that saw the not yet resolved
5850 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005851 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005852 // Return the new class.
5853 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005854 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005855 return true;
5856}
5857
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005858bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005859 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005860 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005861 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5862 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005863 // Check that a class does not inherit from itself directly.
5864 //
5865 // TODO: This is a cheap check to detect the straightforward case
5866 // of a class extending itself (b/28685551), but we should do a
5867 // proper cycle detection on loaded classes, to detect all cases
5868 // of class circularity errors (b/28830038).
5869 if (super_class_idx == class_def.class_idx_) {
5870 ThrowClassCircularityError(klass.Get(),
5871 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005872 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005873 return false;
5874 }
5875
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005876 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005877 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005878 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005879 return false;
5880 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005881 // Verify
5882 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005883 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005884 super_class->PrettyDescriptor().c_str(),
5885 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005886 return false;
5887 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005888 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005889 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005890 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005891 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005892 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005893 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005894 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005895 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005896 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005897 DCHECK(Thread::Current()->IsExceptionPending());
5898 return false;
5899 }
5900 // Verify
5901 if (!klass->CanAccess(interface)) {
5902 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005903 ThrowIllegalAccessError(klass.Get(),
5904 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005905 interface->PrettyDescriptor().c_str(),
5906 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005907 return false;
5908 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005909 }
5910 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005911 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005912 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005913 return true;
5914}
5915
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005916bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005917 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005918 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005919 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5920 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005921 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005922 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005923 return false;
5924 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005925 return true;
5926 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005927 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005928 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005929 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005930 return false;
5931 }
5932 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005933 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005934 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5935 return false;
5936 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005937 if (super->IsFinal()) {
5938 ThrowVerifyError(klass.Get(),
5939 "Superclass %s of %s is declared final",
5940 super->PrettyDescriptor().c_str(),
5941 klass->PrettyDescriptor().c_str());
5942 return false;
5943 }
5944 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005945 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005946 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005947 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005948 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005949 return false;
5950 }
5951 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005952 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005953 super->PrettyDescriptor().c_str(),
5954 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005955 return false;
5956 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005957
Brian Carlstromf3632832014-05-20 15:36:53 -07005958 // Inherit kAccClassIsFinalizable from the superclass in case this
5959 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005960 if (super->IsFinalizable()) {
5961 klass->SetFinalizable();
5962 }
5963
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005964 // Inherit class loader flag form super class.
5965 if (super->IsClassLoaderClass()) {
5966 klass->SetClassLoaderClass();
5967 }
5968
Elliott Hughes2da50362011-10-10 16:57:08 -07005969 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005970 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005971 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005972 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005973 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005974 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005975 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005976 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005977 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005978 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005979 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005980 return false;
5981 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005982
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005983 if (kIsDebugBuild) {
5984 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005985 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005986 CHECK(super->IsResolved());
5987 super = super->GetSuperClass();
5988 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005989 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005990 return true;
5991}
5992
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005993// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005994bool ClassLinker::LinkMethods(Thread* self,
5995 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005996 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005997 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005998 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005999 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006000 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6001 // need to have default methods be in the virtuals array of each class but we don't set that up
6002 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006003 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006004 // Link virtual methods then interface methods.
6005 // We set up the interface lookup table first because we need it to determine if we need to update
6006 // any vtable entries with new default method implementations.
6007 return SetupInterfaceLookupTable(self, klass, interfaces)
6008 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006009 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006010}
6011
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006012// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6013// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6014// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006015class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006016 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006017 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006018 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006019 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6020 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006021 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006022 }
6023
6024 const char* GetName() {
6025 if (name_ == nullptr) {
6026 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6027 }
6028 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006029 }
6030
Mathieu Chartiere401d142015-04-22 13:56:20 -07006031 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006032 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006033 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006034 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006035 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006036 if (dex_file_ == other_dex_file) {
6037 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6038 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006039 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006040 uint32_t other_name_len;
6041 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6042 &other_name_len);
6043 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6044 return false;
6045 }
6046 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6047 }
6048
6049 private:
6050 // Dex file for the method to compare against.
6051 const DexFile* const dex_file_;
6052 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006053 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006054 // Lazily computed name from the dex file's strings.
6055 const char* name_;
6056 // Lazily computed name length.
6057 uint32_t name_len_;
6058};
6059
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006060class LinkVirtualHashTable {
6061 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006062 LinkVirtualHashTable(Handle<mirror::Class> klass,
6063 size_t hash_size,
6064 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006065 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006066 : klass_(klass),
6067 hash_size_(hash_size),
6068 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006069 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006070 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6071 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006072
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006073 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006074 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6075 virtual_method_index, image_pointer_size_);
6076 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006077 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006078 uint32_t index = hash % hash_size_;
6079 // Linear probe until we have an empty slot.
6080 while (hash_table_[index] != invalid_index_) {
6081 if (++index == hash_size_) {
6082 index = 0;
6083 }
6084 }
6085 hash_table_[index] = virtual_method_index;
6086 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006087
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006088 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006089 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006090 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006091 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006092 size_t index = hash % hash_size_;
6093 while (true) {
6094 const uint32_t value = hash_table_[index];
6095 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6096 // the block and can safely assume not found.
6097 if (value == invalid_index_) {
6098 break;
6099 }
6100 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006101 ArtMethod* virtual_method =
6102 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6103 if (comparator->HasSameNameAndSignature(
6104 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006105 hash_table_[index] = removed_index_;
6106 return value;
6107 }
6108 }
6109 if (++index == hash_size_) {
6110 index = 0;
6111 }
6112 }
6113 return GetNotFoundIndex();
6114 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006115
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006116 static uint32_t GetNotFoundIndex() {
6117 return invalid_index_;
6118 }
6119
6120 private:
6121 static const uint32_t invalid_index_;
6122 static const uint32_t removed_index_;
6123
6124 Handle<mirror::Class> klass_;
6125 const size_t hash_size_;
6126 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006127 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006128};
6129
6130const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6131const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6132
Stephen Hines1ddd9132017-02-08 01:51:18 -08006133bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006134 Thread* self,
6135 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006136 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006137 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006138 if (klass->IsInterface()) {
6139 // No vtable.
6140 if (!IsUint<16>(num_virtual_methods)) {
6141 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6142 return false;
6143 }
6144 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006145 // Assign each method an IMT index and set the default flag.
6146 for (size_t i = 0; i < num_virtual_methods; ++i) {
6147 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6148 m->SetMethodIndex(i);
6149 if (!m->IsAbstract()) {
6150 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6151 has_defaults = true;
6152 }
6153 }
6154 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6155 // during initialization. This is a performance optimization. We could simply traverse the
6156 // virtual_methods_ array again during initialization.
6157 if (has_defaults) {
6158 klass->SetHasDefaultMethods();
6159 }
6160 return true;
6161 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006162 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6163 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006164 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006165 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006166 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006167 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006168 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006169 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006170 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006171 return false;
6172 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006173 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006174 vtable->SetElementPtrSize(
6175 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006176 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006177 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6178 // might give us new default methods). If no new interfaces then we can skip the rest since
6179 // the class cannot override any of the super-class's methods. This is required for
6180 // correctness since without it we might not update overridden default method vtable entries
6181 // correctly.
6182 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006183 klass->SetVTable(vtable.Get());
6184 return true;
6185 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006186 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006187 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006188 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006189 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006190 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6191 // might give us new default methods). See comment above.
6192 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006193 klass->SetVTable(super_vtable);
6194 return true;
6195 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006196 vtable = hs.NewHandle(
6197 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006198 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006199 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006200 return false;
6201 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006202 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006203 // How the algorithm works:
6204 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6205 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6206 // method which has not been matched to a vtable method, and j if the virtual method at the
6207 // index overrode the super virtual method at index j.
6208 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6209 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6210 // the need for the initial vtable which we later shrink back down).
6211 // 3. Add non overridden methods to the end of the vtable.
6212 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006213 // + 1 so that even if we only have new default methods we will still be able to use this hash
6214 // table (i.e. it will never have 0 size).
6215 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006216 uint32_t* hash_table_ptr;
6217 std::unique_ptr<uint32_t[]> hash_heap_storage;
6218 if (hash_table_size <= kMaxStackHash) {
6219 hash_table_ptr = reinterpret_cast<uint32_t*>(
6220 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6221 } else {
6222 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6223 hash_table_ptr = hash_heap_storage.get();
6224 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006225 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006226 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006227 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006228 DCHECK(klass->GetVirtualMethodDuringLinking(
6229 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006230 hash_table.Add(i);
6231 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006232 // 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 -07006233 // the hash table.
6234 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006235 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006236 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006237 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6238 super_method->GetAccessFlags())) {
6239 // Continue on to the next method since this one is package private and canot be overridden.
6240 // Before Android 4.1, the package-private method super_method might have been incorrectly
6241 // overridden.
6242 continue;
6243 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006244 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006245 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006246 // We remove the method so that subsequent lookups will be faster by making the hash-map
6247 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006248 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6249 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006250 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6251 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006252 if (super_method->IsFinal()) {
6253 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6254 virtual_method->PrettyMethod().c_str(),
6255 super_method->GetDeclaringClassDescriptor());
6256 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006257 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006258 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6259 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006260 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006261 // We didn't directly override this method but we might through default methods...
6262 // Check for default method update.
6263 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006264 switch (FindDefaultMethodImplementation(self,
6265 super_method,
6266 klass,
6267 /*out*/&default_method)) {
6268 case DefaultMethodSearchResult::kDefaultConflict: {
6269 // A conflict was found looking for default methods. Note this (assuming it wasn't
6270 // pre-existing) in the translations map.
6271 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6272 // Don't generate another conflict method to reduce memory use as an optimization.
6273 default_translations->insert(
6274 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6275 }
6276 break;
6277 }
6278 case DefaultMethodSearchResult::kAbstractFound: {
6279 // No conflict but method is abstract.
6280 // We note that this vtable entry must be made abstract.
6281 if (UNLIKELY(!super_method->IsAbstract())) {
6282 default_translations->insert(
6283 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6284 }
6285 break;
6286 }
6287 case DefaultMethodSearchResult::kDefaultFound: {
6288 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6289 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6290 // Found a default method implementation that is new.
6291 // TODO Refactor this add default methods to virtuals here and not in
6292 // LinkInterfaceMethods maybe.
6293 // The problem is default methods might override previously present
6294 // default-method or miranda-method vtable entries from the superclass.
6295 // Unfortunately we need these to be entries in this class's virtuals. We do not
6296 // give these entries there until LinkInterfaceMethods so we pass this map around
6297 // to let it know which vtable entries need to be updated.
6298 // Make a note that vtable entry j must be updated, store what it needs to be updated
6299 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6300 // then.
6301 default_translations->insert(
6302 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006303 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6304 << " overridden by default "
6305 << default_method->PrettyMethod()
6306 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006307 }
6308 break;
6309 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006310 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006311 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006312 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006313 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006314 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006315 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006316 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006317 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6318 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006319 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006320 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006321 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006322 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006323 local_method->SetMethodIndex(actual_count);
6324 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006325 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006326 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006327 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006328 return false;
6329 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006330 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006331 CHECK_LE(actual_count, max_count);
6332 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006333 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006334 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006335 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006336 return false;
6337 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006338 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006339 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006340 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006341 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006342 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006343 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6344 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006345 return false;
6346 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006347 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006348 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006349 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006350 return false;
6351 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006352 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006353 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6354 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006355 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006356 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006357 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006358 }
6359 return true;
6360}
6361
Alex Light9139e002015-10-09 15:59:48 -07006362// Determine if the given iface has any subinterface in the given list that declares the method
6363// specified by 'target'.
6364//
6365// Arguments
6366// - self: The thread we are running on
6367// - target: A comparator that will match any method that overrides the method we are checking for
6368// - iftable: The iftable we are searching for an overriding method on.
6369// - ifstart: The index of the interface we are checking to see if anything overrides
6370// - iface: The interface we are checking to see if anything overrides.
6371// - image_pointer_size:
6372// The image pointer size.
6373//
6374// Returns
6375// - True: There is some method that matches the target comparator defined in an interface that
6376// is a subtype of iface.
6377// - False: There is no method that matches the target comparator in any interface that is a subtype
6378// of iface.
6379static bool ContainsOverridingMethodOf(Thread* self,
6380 MethodNameAndSignatureComparator& target,
6381 Handle<mirror::IfTable> iftable,
6382 size_t ifstart,
6383 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006384 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006385 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006386 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006387 DCHECK(iface != nullptr);
6388 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006389 DCHECK_GE(ifstart, 0u);
6390 DCHECK_LT(ifstart, iftable->Count());
6391 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6392 DCHECK(iface->IsInterface());
6393
6394 size_t iftable_count = iftable->Count();
6395 StackHandleScope<1> hs(self);
6396 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6397 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6398 // Skip ifstart since our current interface obviously cannot override itself.
6399 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006400 // Iterate through every method on this interface. The order does not matter.
6401 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006402 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006403 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006404 // Check if the i'th interface is a subtype of this one.
6405 if (iface->IsAssignableFrom(current_iface.Get())) {
6406 return true;
6407 }
6408 break;
6409 }
6410 }
6411 }
6412 return false;
6413}
6414
Alex Lighteb7c1442015-08-31 13:17:42 -07006415// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006416// out_default_method and returns kDefaultFound on success. If no default method was found return
6417// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6418// default_method conflict) it will return kDefaultConflict.
6419ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6420 Thread* self,
6421 ArtMethod* target_method,
6422 Handle<mirror::Class> klass,
6423 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006424 DCHECK(self != nullptr);
6425 DCHECK(target_method != nullptr);
6426 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006427
6428 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006429
6430 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6431 // table. This lets us walk the table backwards when searching for default methods. The first one
6432 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6433 // track of it and then continue checking all other interfaces, since we need to throw an error if
6434 // we encounter conflicting default method implementations (one is not a subtype of the other).
6435 //
6436 // The order of unrelated interfaces does not matter and is not defined.
6437 size_t iftable_count = klass->GetIfTableCount();
6438 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006439 // No interfaces. We have already reset out to null so just return kAbstractFound.
6440 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006441 }
6442
Alex Light9139e002015-10-09 15:59:48 -07006443 StackHandleScope<3> hs(self);
6444 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006445 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006446 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006447 MethodNameAndSignatureComparator target_name_comparator(
6448 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6449 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006450 for (size_t k = iftable_count; k != 0; ) {
6451 --k;
6452
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006454
6455 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006456 // Iterate through every declared method on this interface. The order does not matter.
6457 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6458 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006459 // Skip abstract methods and methods with different names.
6460 if (current_method->IsAbstract() ||
6461 !target_name_comparator.HasSameNameAndSignature(
6462 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6463 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006464 } else if (!current_method->IsPublic()) {
6465 // The verifier should have caught the non-public method for dex version 37. Just warn and
6466 // skip it since this is from before default-methods so we don't really need to care that it
6467 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006468 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6469 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006470 << "This will be a fatal error in subsequent versions of android. "
6471 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006472 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006473 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006474 // We have multiple default impls of the same method. This is a potential default conflict.
6475 // We need to check if this possibly conflicting method is either a superclass of the chosen
6476 // default implementation or is overridden by a non-default interface method. In either case
6477 // there is no conflict.
6478 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6479 !ContainsOverridingMethodOf(self,
6480 target_name_comparator,
6481 iftable,
6482 k,
6483 iface,
6484 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006485 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006486 << current_method->PrettyMethod() << " and "
6487 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6488 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006489 *out_default_method = nullptr;
6490 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006491 } else {
6492 break; // Continue checking at the next interface.
6493 }
6494 } else {
Alex Light9139e002015-10-09 15:59:48 -07006495 // chosen_iface == null
6496 if (!ContainsOverridingMethodOf(self,
6497 target_name_comparator,
6498 iftable,
6499 k,
6500 iface,
6501 image_pointer_size_)) {
6502 // Don't set this as the chosen interface if something else is overriding it (because that
6503 // other interface would be potentially chosen instead if it was default). If the other
6504 // interface was abstract then we wouldn't select this interface as chosen anyway since
6505 // the abstract method masks it.
6506 *out_default_method = current_method;
6507 chosen_iface.Assign(iface.Get());
6508 // We should now finish traversing the graph to find if we have default methods that
6509 // conflict.
6510 } else {
David Sehr709b0702016-10-13 09:12:37 -07006511 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6512 << "' was "
6513 << "skipped because it was overridden by an abstract method in a "
6514 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006515 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006516 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006517 break;
6518 }
6519 }
Alex Light9139e002015-10-09 15:59:48 -07006520 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006521 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6522 << "' selected "
6523 << "as the implementation for '" << target_method->PrettyMethod()
6524 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006525 return DefaultMethodSearchResult::kDefaultFound;
6526 } else {
6527 return DefaultMethodSearchResult::kAbstractFound;
6528 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006529}
6530
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006531ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006532 ArtMethod* conflict_method,
6533 ArtMethod* interface_method,
6534 ArtMethod* method,
6535 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006536 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006537 Runtime* const runtime = Runtime::Current();
6538 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6539 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6540
6541 // Create a new entry if the existing one is the shared conflict method.
6542 ArtMethod* new_conflict_method = new_entry
6543 ? runtime->CreateImtConflictMethod(linear_alloc)
6544 : conflict_method;
6545
6546 // Allocate a new table. Note that we will leak this table at the next conflict,
6547 // but that's a tradeoff compared to making the table fixed size.
6548 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006549 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6550 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006551 if (data == nullptr) {
6552 LOG(ERROR) << "Failed to allocate conflict table";
6553 return conflict_method;
6554 }
6555 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6556 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006557 method,
6558 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006559
6560 // Do a fence to ensure threads see the data in the table before it is assigned
6561 // to the conflict method.
6562 // Note that there is a race in the presence of multiple threads and we may leak
6563 // memory from the LinearAlloc, but that's a tradeoff compared to using
6564 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006565 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006566 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006567 return new_conflict_method;
6568}
6569
Vladimir Marko921094a2017-01-12 18:37:06 +00006570bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6571 Handle<mirror::Class> klass,
6572 Handle<mirror::IfTable> iftable) {
6573 DCHECK(!klass->IsInterface());
6574 const bool has_superclass = klass->HasSuperClass();
6575 const bool extend_super_iftable = has_superclass;
6576 const size_t ifcount = klass->GetIfTableCount();
6577 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6578 for (size_t i = 0; i < ifcount; ++i) {
6579 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6580 if (num_methods > 0) {
6581 const bool is_super = i < super_ifcount;
6582 // This is an interface implemented by a super-class. Therefore we can just copy the method
6583 // array from the superclass.
6584 const bool super_interface = is_super && extend_super_iftable;
6585 ObjPtr<mirror::PointerArray> method_array;
6586 if (super_interface) {
6587 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6588 DCHECK(if_table != nullptr);
6589 DCHECK(if_table->GetMethodArray(i) != nullptr);
6590 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006591 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6592 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006593 } else {
6594 method_array = AllocPointerArray(self, num_methods);
6595 }
6596 if (UNLIKELY(method_array == nullptr)) {
6597 self->AssertPendingOOMException();
6598 return false;
6599 }
6600 iftable->SetMethodArray(i, method_array);
6601 }
6602 }
6603 return true;
6604}
6605
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006606void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6607 ArtMethod* imt_conflict_method,
6608 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006609 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006610 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006611 // Place method in imt if entry is empty, place conflict otherwise.
6612 if (*imt_ref == unimplemented_method) {
6613 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006614 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006615 // If we are not a conflict and we have the same signature and name as the imt
6616 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006617 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6618 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006619 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006620 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006621 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006622 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006623 *imt_ref = current_method;
6624 } else {
Alex Light9139e002015-10-09 15:59:48 -07006625 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006626 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006627 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006628 } else {
6629 // Place the default conflict method. Note that there may be an existing conflict
6630 // method in the IMT, but it could be one tailored to the super class, with a
6631 // specific ImtConflictTable.
6632 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006633 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006634 }
6635}
6636
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006637void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006638 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6639 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006640 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006641 Runtime* const runtime = Runtime::Current();
6642 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6643 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006644 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006645 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006646 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006647 FillIMTFromIfTable(klass->GetIfTable(),
6648 unimplemented_method,
6649 conflict_method,
6650 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006651 /*create_conflict_tables=*/true,
6652 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006653 &new_conflict,
6654 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006655 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006656 if (!klass->ShouldHaveImt()) {
6657 return;
6658 }
6659 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6660 // we can just use the same pointer.
6661 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006662 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006663 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6664 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6665 bool same = true;
6666 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6667 ArtMethod* method = imt_data[i];
6668 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6669 if (method != super_method) {
6670 bool is_conflict_table = method->IsRuntimeMethod() &&
6671 method != unimplemented_method &&
6672 method != conflict_method;
6673 // Verify conflict contents.
6674 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6675 super_method != unimplemented_method &&
6676 super_method != conflict_method;
6677 if (!is_conflict_table || !super_conflict_table) {
6678 same = false;
6679 } else {
6680 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6681 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6682 same = same && table1->Equals(table2, image_pointer_size_);
6683 }
6684 }
6685 }
6686 if (same) {
6687 imt = super_imt;
6688 }
6689 }
6690 if (imt == nullptr) {
6691 imt = klass->GetImt(image_pointer_size_);
6692 DCHECK(imt != nullptr);
6693 imt->Populate(imt_data, image_pointer_size_);
6694 } else {
6695 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006696 }
6697}
6698
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006699ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6700 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006701 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006702 void* data = linear_alloc->Alloc(Thread::Current(),
6703 ImtConflictTable::ComputeSize(count,
6704 image_pointer_size));
6705 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6706}
6707
6708ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6709 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6710}
6711
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006712void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006713 ArtMethod* unimplemented_method,
6714 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006715 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006716 bool create_conflict_tables,
6717 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006718 /*out*/bool* new_conflict,
6719 /*out*/ArtMethod** imt) {
6720 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006721 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006722 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006723 const size_t num_virtuals = interface->NumVirtualMethods();
6724 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6725 // Virtual methods can be larger than the if table methods if there are default methods.
6726 DCHECK_GE(num_virtuals, method_array_count);
6727 if (kIsDebugBuild) {
6728 if (klass->IsInterface()) {
6729 DCHECK_EQ(method_array_count, 0u);
6730 } else {
6731 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6732 }
6733 }
6734 if (method_array_count == 0) {
6735 continue;
6736 }
6737 auto* method_array = if_table->GetMethodArray(i);
6738 for (size_t j = 0; j < method_array_count; ++j) {
6739 ArtMethod* implementation_method =
6740 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6741 if (ignore_copied_methods && implementation_method->IsCopied()) {
6742 continue;
6743 }
6744 DCHECK(implementation_method != nullptr);
6745 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6746 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6747 // or interface methods in the IMT here they will not create extra conflicts since we compare
6748 // names and signatures in SetIMTRef.
6749 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006750 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006751
6752 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6753 // the same implementation method, keep track of this to avoid creating a conflict table in
6754 // this case.
6755
6756 // Conflict table size for each IMT slot.
6757 ++conflict_counts[imt_index];
6758
6759 SetIMTRef(unimplemented_method,
6760 imt_conflict_method,
6761 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006762 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006763 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006764 }
6765 }
6766
6767 if (create_conflict_tables) {
6768 // Create the conflict tables.
6769 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006770 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006771 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006772 if (imt[i] == imt_conflict_method) {
6773 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6774 if (new_table != nullptr) {
6775 ArtMethod* new_conflict_method =
6776 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6777 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6778 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006779 } else {
6780 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006781 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006782 }
6783 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006784 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006785 }
6786 }
6787
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006788 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006789 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006790 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6791 // Virtual methods can be larger than the if table methods if there are default methods.
6792 if (method_array_count == 0) {
6793 continue;
6794 }
6795 auto* method_array = if_table->GetMethodArray(i);
6796 for (size_t j = 0; j < method_array_count; ++j) {
6797 ArtMethod* implementation_method =
6798 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6799 if (ignore_copied_methods && implementation_method->IsCopied()) {
6800 continue;
6801 }
6802 DCHECK(implementation_method != nullptr);
6803 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006804 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006805 if (!imt[imt_index]->IsRuntimeMethod() ||
6806 imt[imt_index] == unimplemented_method ||
6807 imt[imt_index] == imt_conflict_method) {
6808 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006809 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006810 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6811 const size_t num_entries = table->NumEntries(image_pointer_size_);
6812 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6813 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006814 }
6815 }
6816 }
6817}
6818
Alex Lighteb7c1442015-08-31 13:17:42 -07006819// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6820// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006821static bool NotSubinterfaceOfAny(
6822 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6823 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006824 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006825 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006826 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006827 for (ObjPtr<mirror::Class> c : classes) {
6828 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006829 return false;
6830 }
6831 }
6832 return true;
6833}
6834
6835// Fills in and flattens the interface inheritance hierarchy.
6836//
6837// By the end of this function all interfaces in the transitive closure of to_process are added to
6838// the iftable and every interface precedes all of its sub-interfaces in this list.
6839//
6840// all I, J: Interface | I <: J implies J precedes I
6841//
6842// (note A <: B means that A is a subtype of B)
6843//
6844// This returns the total number of items in the iftable. The iftable might be resized down after
6845// this call.
6846//
6847// We order this backwards so that we do not need to reorder superclass interfaces when new
6848// interfaces are added in subclass's interface tables.
6849//
6850// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6851// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6852// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6853// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006854static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006855 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006856 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006857 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006858 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006859 // This is the set of all class's already in the iftable. Used to make checking if a class has
6860 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006861 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006862 // The first super_ifcount elements are from the superclass. We note that they are already added.
6863 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006864 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006865 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6866 classes_in_iftable.insert(iface);
6867 }
6868 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006869 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006870 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6871 // At this point in the loop current-iface-list has the invariant that:
6872 // for every pair of interfaces I,J within it:
6873 // if index_of(I) < index_of(J) then I is not a subtype of J
6874
6875 // If we have already seen this element then all of its super-interfaces must already be in the
6876 // current-iface-list so we can skip adding it.
6877 if (!ContainsElement(classes_in_iftable, interface)) {
6878 // We haven't seen this interface so add all of its super-interfaces onto the
6879 // current-iface-list, skipping those already on it.
6880 int32_t ifcount = interface->GetIfTableCount();
6881 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006882 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006883 if (!ContainsElement(classes_in_iftable, super_interface)) {
6884 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6885 classes_in_iftable.insert(super_interface);
6886 iftable->SetInterface(filled_ifcount, super_interface);
6887 filled_ifcount++;
6888 }
6889 }
6890 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6891 // Place this interface onto the current-iface-list after all of its super-interfaces.
6892 classes_in_iftable.insert(interface);
6893 iftable->SetInterface(filled_ifcount, interface);
6894 filled_ifcount++;
6895 } else if (kIsDebugBuild) {
6896 // Check all super-interfaces are already in the list.
6897 int32_t ifcount = interface->GetIfTableCount();
6898 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006899 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006900 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006901 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6902 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006903 }
6904 }
6905 }
6906 if (kIsDebugBuild) {
6907 // Check that the iftable is ordered correctly.
6908 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006909 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006910 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006911 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006912 // !(if_a <: if_b)
6913 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006914 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6915 << ") extends "
6916 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006917 << "interface list.";
6918 }
6919 }
6920 }
6921 return filled_ifcount;
6922}
6923
6924bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6925 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6926 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006927 const bool has_superclass = klass->HasSuperClass();
6928 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006929 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006930 const size_t num_interfaces =
6931 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006932 if (num_interfaces == 0) {
6933 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006934 if (LIKELY(has_superclass)) {
6935 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6936 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006937 // Class implements no interfaces.
6938 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006939 return true;
6940 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006941 // Class implements same interfaces as parent, are any of these not marker interfaces?
6942 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006943 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006944 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006945 if (super_iftable->GetMethodArrayCount(i) > 0) {
6946 has_non_marker_interface = true;
6947 break;
6948 }
6949 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006950 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006951 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006952 klass->SetIfTable(super_iftable);
6953 return true;
6954 }
6955 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006956 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006957 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006958 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006959 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006960 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006961 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006962 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006963 if (UNLIKELY(!interface->IsInterface())) {
6964 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006965 ThrowIncompatibleClassChangeError(klass.Get(),
6966 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006967 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006968 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6969 return false;
6970 }
6971 ifcount += interface->GetIfTableCount();
6972 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006973 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006974 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006975 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006976 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006977 return false;
6978 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006979 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006980 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006981 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006982 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006983 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006984 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006985 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006986 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006987
6988 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6989 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6990 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006991 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006992
6993 size_t new_ifcount;
6994 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006995 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01006996 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07006997 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006998 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006999 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007000 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007001 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007002
7003 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007004 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007005
Ian Rogers7b078e82014-09-10 14:44:24 -07007006 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007007
Ian Rogersb52b01a2012-01-12 17:01:38 -08007008 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007009 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007010 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007011 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007012 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007013 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007014 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007015 return false;
7016 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007017 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007018 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007019 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007020 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007021 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007022 return true;
7023}
7024
Alex Light1f3925d2016-09-07 12:04:20 -07007025// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7026// of methods must be unique.
7027static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7028 return nullptr;
7029}
7030
7031template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007032static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007033 const ScopedArenaVector<ArtMethod*>& list,
7034 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007035 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007036 for (ArtMethod* method : list) {
7037 if (cmp.HasSameNameAndSignature(method)) {
7038 return method;
7039 }
7040 }
Alex Light1f3925d2016-09-07 12:04:20 -07007041 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007042}
7043
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007044namespace {
7045
Alex Light1f3925d2016-09-07 12:04:20 -07007046// Check that all vtable entries are present in this class's virtuals or are the same as a
7047// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007048void CheckClassOwnsVTableEntries(Thread* self,
7049 Handle<mirror::Class> klass,
7050 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007051 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007052 StackHandleScope<2> hs(self);
7053 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007054 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007055 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007056 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007057 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7058 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7059 CHECK(m != nullptr);
7060
Alex Lighta41a30782017-03-29 11:33:19 -07007061 if (m->GetMethodIndexDuringLinking() != i) {
7062 LOG(WARNING) << m->PrettyMethod()
7063 << " has an unexpected method index for its spot in the vtable for class"
7064 << klass->PrettyClass();
7065 }
Alex Lighte64300b2015-12-15 15:02:47 -08007066 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7067 auto is_same_method = [m] (const ArtMethod& meth) {
7068 return &meth == m;
7069 };
Alex Light3f980532017-03-17 15:10:32 -07007070 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7071 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7072 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7073 << klass->PrettyClass() << " or any of its superclasses!";
7074 }
Alex Lighte64300b2015-12-15 15:02:47 -08007075 }
7076}
7077
Alex Light1f3925d2016-09-07 12:04:20 -07007078// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7079// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007080template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007081void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007082 REQUIRES_SHARED(Locks::mutator_lock_) {
7083 StackHandleScope<1> hs(self);
7084 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7085 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007086
7087 // Observations:
7088 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7089 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7090 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7091 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7092 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7093 // * The single-pass algorithm will trade memory for speed, but that is OK.
7094
7095 CHECK_GT(num_entries, 0);
7096
7097 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7098 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7099 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7100 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7101 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7102 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7103 << m2->PrettyMethod() << " (0x" << std::hex
7104 << reinterpret_cast<uintptr_t>(m2) << ")";
7105 };
7106 struct BaseHashType {
7107 static size_t HashCombine(size_t seed, size_t val) {
7108 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7109 }
7110 };
7111
7112 // Check assuming all entries come from the same dex file.
7113 {
7114 // Find the first interesting method and its dex file.
7115 int32_t start = 0;
7116 for (; start < num_entries; ++start) {
7117 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7118 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7119 // maybe).
7120 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7121 vtable_entry->GetAccessFlags())) {
7122 continue;
7123 }
7124 break;
7125 }
7126 if (start == num_entries) {
7127 return;
7128 }
7129 const DexFile* dex_file =
7130 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7131 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7132
7133 // Helper function to avoid logging if we have to run the cross-file checks.
7134 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7135 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7136 using PairType = std::pair<uint32_t, uint16_t>;
7137 struct PairHash : BaseHashType {
7138 size_t operator()(const PairType& key) const {
7139 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7140 }
7141 };
7142 std::unordered_map<PairType, int32_t, PairHash> seen;
7143 seen.reserve(2 * num_entries);
7144 bool need_slow_path = false;
7145 bool found_dup = false;
7146 for (int i = start; i < num_entries; ++i) {
7147 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7148 // wrt/ kPointerSize.
7149 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7150 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7151 vtable_entry->GetAccessFlags())) {
7152 continue;
7153 }
7154 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7155 if (dex_file != m->GetDexFile()) {
7156 need_slow_path = true;
7157 break;
7158 }
7159 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7160 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7161 auto it = seen.find(pair);
7162 if (it != seen.end()) {
7163 found_dup = true;
7164 if (log_warn) {
7165 log_fn(it->second, i);
7166 }
7167 } else {
7168 seen.emplace(pair, i);
7169 }
7170 }
7171 return std::make_pair(need_slow_path, found_dup);
7172 };
7173 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7174 if (!result.first) {
7175 if (result.second) {
7176 check_fn(/* log_warn= */ true);
7177 }
7178 return;
7179 }
7180 }
7181
7182 // Need to check across dex files.
7183 struct Entry {
7184 size_t cached_hash = 0;
7185 const char* name = nullptr;
7186 Signature signature = Signature::NoSignature();
7187 uint32_t name_len = 0;
7188
7189 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7190 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7191 signature(dex_file->GetMethodSignature(mid)) {
7192 }
7193
7194 bool operator==(const Entry& other) const {
7195 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7196 return false;
7197 }
7198 return signature == other.signature;
7199 }
7200 };
7201 struct EntryHash {
7202 size_t operator()(const Entry& key) const {
7203 return key.cached_hash;
7204 }
7205 };
7206 std::unordered_map<Entry, int32_t, EntryHash> map;
7207 for (int32_t i = 0; i < num_entries; ++i) {
7208 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7209 // wrt/ kPointerSize.
7210 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7211 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7212 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007213 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7214 vtable_entry->GetAccessFlags())) {
7215 continue;
7216 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007217 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7218 const DexFile* dex_file = m->GetDexFile();
7219 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7220
7221 Entry e(dex_file, mid);
7222
7223 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7224 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7225 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7226 sig_hash);
7227
7228 auto it = map.find(e);
7229 if (it != map.end()) {
7230 log_fn(it->second, i);
7231 } else {
7232 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007233 }
7234 }
7235}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007236
7237void CheckVTableHasNoDuplicates(Thread* self,
7238 Handle<mirror::Class> klass,
7239 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007240 REQUIRES_SHARED(Locks::mutator_lock_) {
7241 switch (pointer_size) {
7242 case PointerSize::k64:
7243 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7244 break;
7245 case PointerSize::k32:
7246 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7247 break;
7248 }
7249}
Alex Light1f3925d2016-09-07 12:04:20 -07007250
7251static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7252 REQUIRES_SHARED(Locks::mutator_lock_) {
7253 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7254 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7255}
7256
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007257} // namespace
7258
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007259void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7260 ArtMethod* unimplemented_method,
7261 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007262 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007263 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007264 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007265 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007266 if (super_class->ShouldHaveImt()) {
7267 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7268 for (size_t i = 0; i < ImTable::kSize; ++i) {
7269 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007270 }
7271 } else {
7272 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007273 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007274 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007275 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007276 FillIMTFromIfTable(if_table,
7277 unimplemented_method,
7278 imt_conflict_method,
7279 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007280 /*create_conflict_tables=*/false,
7281 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007282 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007283 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007284 }
7285 }
7286}
7287
Vladimir Marko921094a2017-01-12 18:37:06 +00007288class ClassLinker::LinkInterfaceMethodsHelper {
7289 public:
7290 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7291 Handle<mirror::Class> klass,
7292 Thread* self,
7293 Runtime* runtime)
7294 : class_linker_(class_linker),
7295 klass_(klass),
7296 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7297 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7298 self_(self),
7299 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7300 allocator_(&stack_),
7301 default_conflict_methods_(allocator_.Adapter()),
7302 overriding_default_conflict_methods_(allocator_.Adapter()),
7303 miranda_methods_(allocator_.Adapter()),
7304 default_methods_(allocator_.Adapter()),
7305 overriding_default_methods_(allocator_.Adapter()),
7306 move_table_(allocator_.Adapter()) {
7307 }
7308
7309 ArtMethod* FindMethod(ArtMethod* interface_method,
7310 MethodNameAndSignatureComparator& interface_name_comparator,
7311 ArtMethod* vtable_impl)
7312 REQUIRES_SHARED(Locks::mutator_lock_);
7313
7314 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7315 MethodNameAndSignatureComparator& interface_name_comparator)
7316 REQUIRES_SHARED(Locks::mutator_lock_);
7317
7318 bool HasNewVirtuals() const {
7319 return !(miranda_methods_.empty() &&
7320 default_methods_.empty() &&
7321 overriding_default_methods_.empty() &&
7322 overriding_default_conflict_methods_.empty() &&
7323 default_conflict_methods_.empty());
7324 }
7325
7326 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7327
7328 ObjPtr<mirror::PointerArray> UpdateVtable(
7329 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7330 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7331
7332 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7333
7334 void UpdateIMT(ArtMethod** out_imt);
7335
7336 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7337 if (kIsDebugBuild) {
7338 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7339 // Check that there are no stale methods are in the dex cache array.
7340 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7341 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007342 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7343 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007344 CHECK(move_table_.find(m) == move_table_.end() ||
7345 // The original versions of copied methods will still be present so allow those too.
7346 // Note that if the first check passes this might fail to GetDeclaringClass().
7347 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7348 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7349 [m] (ArtMethod& meth) {
7350 return &meth == m;
7351 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7352 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7353 }
7354 }
7355 }
7356
7357 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7358 LengthPrefixedArray<ArtMethod>* methods) {
7359 if (kIsDebugBuild) {
7360 CHECK(methods != nullptr);
7361 // Put some random garbage in old methods to help find stale pointers.
7362 if (methods != old_methods && old_methods != nullptr) {
7363 // Need to make sure the GC is not running since it could be scanning the methods we are
7364 // about to overwrite.
7365 ScopedThreadStateChange tsc(self_, kSuspended);
7366 gc::ScopedGCCriticalSection gcs(self_,
7367 gc::kGcCauseClassLinker,
7368 gc::kCollectorTypeClassLinker);
7369 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7370 method_size_,
7371 method_alignment_);
7372 memset(old_methods, 0xFEu, old_size);
7373 }
7374 }
7375 }
7376
7377 private:
7378 size_t NumberOfNewVirtuals() const {
7379 return miranda_methods_.size() +
7380 default_methods_.size() +
7381 overriding_default_conflict_methods_.size() +
7382 overriding_default_methods_.size() +
7383 default_conflict_methods_.size();
7384 }
7385
7386 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7387 return !klass_->IsInterface();
7388 }
7389
7390 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7391 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7392 << "Interfaces should only have default-conflict methods appended to them.";
7393 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7394 << miranda_methods_.size()
7395 << " default_methods=" << default_methods_.size()
7396 << " overriding_default_methods=" << overriding_default_methods_.size()
7397 << " default_conflict_methods=" << default_conflict_methods_.size()
7398 << " overriding_default_conflict_methods="
7399 << overriding_default_conflict_methods_.size();
7400 }
7401
7402 ClassLinker* class_linker_;
7403 Handle<mirror::Class> klass_;
7404 size_t method_alignment_;
7405 size_t method_size_;
7406 Thread* const self_;
7407
7408 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7409 // the virtual methods array.
7410 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7411 // during cross compilation.
7412 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7413 ArenaStack stack_;
7414 ScopedArenaAllocator allocator_;
7415
7416 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7417 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7418 ScopedArenaVector<ArtMethod*> miranda_methods_;
7419 ScopedArenaVector<ArtMethod*> default_methods_;
7420 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7421
7422 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7423};
7424
7425ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7426 ArtMethod* interface_method,
7427 MethodNameAndSignatureComparator& interface_name_comparator,
7428 ArtMethod* vtable_impl) {
7429 ArtMethod* current_method = nullptr;
7430 switch (class_linker_->FindDefaultMethodImplementation(self_,
7431 interface_method,
7432 klass_,
7433 /*out*/&current_method)) {
7434 case DefaultMethodSearchResult::kDefaultConflict: {
7435 // Default method conflict.
7436 DCHECK(current_method == nullptr);
7437 ArtMethod* default_conflict_method = nullptr;
7438 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7439 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7440 default_conflict_method = vtable_impl;
7441 } else {
7442 // See if we already have a conflict method for this method.
7443 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7444 interface_name_comparator,
7445 default_conflict_methods_,
7446 overriding_default_conflict_methods_);
7447 if (LIKELY(preexisting_conflict != nullptr)) {
7448 // We already have another conflict we can reuse.
7449 default_conflict_method = preexisting_conflict;
7450 } else {
7451 // Note that we do this even if we are an interface since we need to create this and
7452 // cannot reuse another classes.
7453 // Create a new conflict method for this to use.
7454 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7455 new(default_conflict_method) ArtMethod(interface_method,
7456 class_linker_->GetImagePointerSize());
7457 if (vtable_impl == nullptr) {
7458 // Save the conflict method. We need to add it to the vtable.
7459 default_conflict_methods_.push_back(default_conflict_method);
7460 } else {
7461 // Save the conflict method but it is already in the vtable.
7462 overriding_default_conflict_methods_.push_back(default_conflict_method);
7463 }
7464 }
7465 }
7466 current_method = default_conflict_method;
7467 break;
7468 } // case kDefaultConflict
7469 case DefaultMethodSearchResult::kDefaultFound: {
7470 DCHECK(current_method != nullptr);
7471 // Found a default method.
7472 if (vtable_impl != nullptr &&
7473 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7474 // We found a default method but it was the same one we already have from our
7475 // superclass. Don't bother adding it to our vtable again.
7476 current_method = vtable_impl;
7477 } else if (LIKELY(FillTables())) {
7478 // Interfaces don't need to copy default methods since they don't have vtables.
7479 // Only record this default method if it is new to save space.
7480 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7481 // would make lookup for interface super much faster. (We would only need to scan
7482 // the iftable to find if there is a NSME or AME.)
7483 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7484 default_methods_,
7485 overriding_default_methods_);
7486 if (old == nullptr) {
7487 // We found a default method implementation and there were no conflicts.
7488 if (vtable_impl == nullptr) {
7489 // Save the default method. We need to add it to the vtable.
7490 default_methods_.push_back(current_method);
7491 } else {
7492 // Save the default method but it is already in the vtable.
7493 overriding_default_methods_.push_back(current_method);
7494 }
7495 } else {
7496 CHECK(old == current_method) << "Multiple default implementations selected!";
7497 }
7498 }
7499 break;
7500 } // case kDefaultFound
7501 case DefaultMethodSearchResult::kAbstractFound: {
7502 DCHECK(current_method == nullptr);
7503 // Abstract method masks all defaults.
7504 if (vtable_impl != nullptr &&
7505 vtable_impl->IsAbstract() &&
7506 !vtable_impl->IsDefaultConflicting()) {
7507 // We need to make this an abstract method but the version in the vtable already is so
7508 // don't do anything.
7509 current_method = vtable_impl;
7510 }
7511 break;
7512 } // case kAbstractFound
7513 }
7514 return current_method;
7515}
7516
7517ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7518 ArtMethod* interface_method,
7519 MethodNameAndSignatureComparator& interface_name_comparator) {
7520 // Find out if there is already a miranda method we can use.
7521 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7522 miranda_methods_);
7523 if (miranda_method == nullptr) {
7524 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7525 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7526 CHECK(miranda_method != nullptr);
7527 // Point the interface table at a phantom slot.
7528 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7529 miranda_methods_.push_back(miranda_method);
7530 }
7531 return miranda_method;
7532}
7533
7534void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7535 LogNewVirtuals();
7536
7537 const size_t old_method_count = klass_->NumMethods();
7538 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7539 DCHECK_NE(old_method_count, new_method_count);
7540
7541 // Attempt to realloc to save RAM if possible.
7542 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7543 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7544 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7545 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7546 // CopyFrom has internal read barriers.
7547 //
7548 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7549 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7550 method_size_,
7551 method_alignment_);
7552 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7553 method_size_,
7554 method_alignment_);
7555 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7556 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007557 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007558 self_, old_methods, old_methods_ptr_size, new_size));
7559 CHECK(methods != nullptr); // Native allocation failure aborts.
7560
7561 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7562 if (methods != old_methods) {
7563 // Maps from heap allocated miranda method to linear alloc miranda method.
7564 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7565 // Copy over the old methods.
7566 for (auto& m : klass_->GetMethods(pointer_size)) {
7567 move_table_.emplace(&m, &*out);
7568 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7569 // barriers when it copies.
7570 out->CopyFrom(&m, pointer_size);
7571 ++out;
7572 }
7573 }
7574 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7575 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7576 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007577 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7578 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007579 ArtMethod& new_method = *out;
7580 new_method.CopyFrom(mir_method, pointer_size);
7581 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7582 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7583 << "Miranda method should be abstract!";
7584 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007585 // Update the entry in the method array, as the array will be used for future lookups,
7586 // where thread suspension is allowed.
7587 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7588 // would not see them.
7589 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007590 ++out;
7591 }
7592 // We need to copy the default methods into our own method table since the runtime requires that
7593 // every method on a class's vtable be in that respective class's virtual method table.
7594 // NOTE This means that two classes might have the same implementation of a method from the same
7595 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7596 // default method found on a class with one found on the declaring interface directly and must
7597 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007598 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7599 &overriding_default_methods_}) {
7600 for (size_t i = 0; i < methods_vec->size(); ++i) {
7601 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007602 ArtMethod& new_method = *out;
7603 new_method.CopyFrom(def_method, pointer_size);
7604 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7605 // verified yet it shouldn't have methods that are skipping access checks.
7606 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7607 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007608 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007609 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7610 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7611 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7612 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007613 // Update the entry in the method array, as the array will be used for future lookups,
7614 // where thread suspension is allowed.
7615 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7616 // would not see them.
7617 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007618 ++out;
7619 }
7620 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007621 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7622 &overriding_default_conflict_methods_}) {
7623 for (size_t i = 0; i < methods_vec->size(); ++i) {
7624 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007625 ArtMethod& new_method = *out;
7626 new_method.CopyFrom(conf_method, pointer_size);
7627 // This is a type of default method (there are default method impls, just a conflict) so
7628 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7629 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7630 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007631 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7632 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007633 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007634 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007635 constexpr uint32_t kMaskFlags =
7636 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007637 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7638 DCHECK(new_method.IsDefaultConflicting());
7639 // The actual method might or might not be marked abstract since we just copied it from a
7640 // (possibly default) interface method. We need to set it entry point to be the bridge so
7641 // that the compiler will not invoke the implementation of whatever method we copied from.
7642 EnsureThrowsInvocationError(class_linker_, &new_method);
7643 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007644 // Update the entry in the method array, as the array will be used for future lookups,
7645 // where thread suspension is allowed.
7646 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7647 // would not see them.
7648 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007649 ++out;
7650 }
7651 }
7652 methods->SetSize(new_method_count);
7653 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7654}
7655
7656ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7657 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7658 ObjPtr<mirror::PointerArray> old_vtable) {
7659 // Update the vtable to the new method structures. We can skip this for interfaces since they
7660 // do not have vtables.
7661 const size_t old_vtable_count = old_vtable->GetLength();
7662 const size_t new_vtable_count = old_vtable_count +
7663 miranda_methods_.size() +
7664 default_methods_.size() +
7665 default_conflict_methods_.size();
7666
7667 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007668 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007669 if (UNLIKELY(vtable == nullptr)) {
7670 self_->AssertPendingOOMException();
7671 return nullptr;
7672 }
7673
7674 size_t vtable_pos = old_vtable_count;
7675 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7676 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7677 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7678 default_conflict_methods_,
7679 miranda_methods_}) {
7680 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007681 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007682 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7683 // fields are references into the dex file the method was defined in. Since the ArtMethod
7684 // does not store that information it uses declaring_class_->dex_cache_.
7685 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7686 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7687 ++vtable_pos;
7688 }
7689 }
7690 DCHECK_EQ(vtable_pos, new_vtable_count);
7691
7692 // Update old vtable methods. We use the default_translations map to figure out what each
7693 // vtable entry should be updated to, if they need to be at all.
7694 for (size_t i = 0; i < old_vtable_count; ++i) {
7695 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7696 // Try and find what we need to change this method to.
7697 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007698 if (translation_it != default_translations.end()) {
7699 if (translation_it->second.IsInConflict()) {
7700 // Find which conflict method we are to use for this method.
7701 MethodNameAndSignatureComparator old_method_comparator(
7702 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7703 // We only need to look through overriding_default_conflict_methods since this is an
7704 // overridden method we are fixing up here.
7705 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7706 old_method_comparator, overriding_default_conflict_methods_);
7707 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7708 translated_method = new_conflict_method;
7709 } else if (translation_it->second.IsAbstract()) {
7710 // Find which miranda method we are to use for this method.
7711 MethodNameAndSignatureComparator old_method_comparator(
7712 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7713 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7714 miranda_methods_);
7715 DCHECK(miranda_method != nullptr);
7716 translated_method = miranda_method;
7717 } else {
7718 // Normal default method (changed from an older default or abstract interface method).
7719 DCHECK(translation_it->second.IsTranslation());
7720 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007721 auto it = move_table_.find(translated_method);
7722 DCHECK(it != move_table_.end());
7723 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007724 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007725 } else {
7726 auto it = move_table_.find(translated_method);
7727 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007728 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007729
7730 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007731 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007732 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007733 if (kIsDebugBuild) {
7734 auto* methods = klass_->GetMethodsPtr();
7735 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007736 reinterpret_cast<uintptr_t>(translated_method));
7737 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007738 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7739 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007740 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007741 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007742 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007743 }
7744 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007745 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007746 return vtable;
7747}
7748
7749void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7750 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7751 const size_t ifcount = klass_->GetIfTableCount();
7752 // Go fix up all the stale iftable pointers.
7753 for (size_t i = 0; i < ifcount; ++i) {
7754 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7755 auto* method_array = iftable->GetMethodArray(i);
7756 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7757 DCHECK(m != nullptr) << klass_->PrettyClass();
7758 auto it = move_table_.find(m);
7759 if (it != move_table_.end()) {
7760 auto* new_m = it->second;
7761 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7762 method_array->SetElementPtrSize(j, new_m, pointer_size);
7763 }
7764 }
7765 }
7766}
7767
7768void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7769 // Fix up IMT next.
7770 for (size_t i = 0; i < ImTable::kSize; ++i) {
7771 auto it = move_table_.find(out_imt[i]);
7772 if (it != move_table_.end()) {
7773 out_imt[i] = it->second;
7774 }
7775 }
7776}
7777
Alex Light705ad492015-09-21 11:36:30 -07007778// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007779bool ClassLinker::LinkInterfaceMethods(
7780 Thread* self,
7781 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007782 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007783 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007784 ArtMethod** out_imt) {
7785 StackHandleScope<3> hs(self);
7786 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007787
7788 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007789 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007790 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007791 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007792 const size_t ifcount = klass->GetIfTableCount();
7793
Vladimir Marko921094a2017-01-12 18:37:06 +00007794 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007795
7796 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7797 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007798 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007799 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007800 const bool extend_super_iftable = has_superclass;
7801 if (has_superclass && fill_tables) {
7802 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007803 unimplemented_method,
7804 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007805 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007806 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007807 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007808 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7809 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007810 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007811 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7812 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007813 }
7814 }
7815
Vladimir Marko921094a2017-01-12 18:37:06 +00007816 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7817
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007818 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007819 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007820 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7821 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7822 // they will already be null. This has the additional benefit that the declarer of a miranda
7823 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007824 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007825 --i;
Alex Light9139e002015-10-09 15:59:48 -07007826 DCHECK_LT(i, ifcount);
7827
Alex Light705ad492015-09-21 11:36:30 -07007828 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007829 if (num_methods > 0) {
7830 StackHandleScope<2> hs2(self);
7831 const bool is_super = i < super_ifcount;
7832 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007833 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7834 // conflict methods. Just set this as nullptr in those cases.
7835 Handle<mirror::PointerArray> method_array(fill_tables
7836 ? hs2.NewHandle(iftable->GetMethodArray(i))
7837 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007838
Alex Lighte64300b2015-12-15 15:02:47 -08007839 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007840 ScopedNullHandle<mirror::PointerArray> null_handle;
7841 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007842 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007843
Alex Light9139e002015-10-09 15:59:48 -07007844 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7845 // and confusing. Default methods should always look through all the superclasses
7846 // because they are the last choice of an implementation. We get around this by looking
7847 // at the super-classes iftable methods (copied into method_array previously) when we are
7848 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007849 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007850 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007851 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007852 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007853 using_virtuals = true;
7854 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7855 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007856 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007857 // For a new interface, however, we need the whole vtable in case a new
7858 // interface method is implemented in the whole superclass.
7859 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007860 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007861 input_vtable_array = vtable;
7862 input_array_length = input_vtable_array->GetLength();
7863 }
Alex Lighte64300b2015-12-15 15:02:47 -08007864
Alex Lighteb7c1442015-08-31 13:17:42 -07007865 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007866 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007867 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007868 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007869 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007870 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007871 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007872 // For each method listed in the interface's method list, find the
7873 // matching method in our class's method list. We want to favor the
7874 // subclass over the superclass, which just requires walking
7875 // back from the end of the vtable. (This only matters if the
7876 // superclass defines a private method and this class redefines
7877 // it -- otherwise it would use the same vtable slot. In .dex files
7878 // those don't end up in the virtual method table, so it shouldn't
7879 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007880 //
7881 // To find defaults we need to do the same but also go over interfaces.
7882 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007883 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007884 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007885 ArtMethod* vtable_method = using_virtuals ?
7886 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007887 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7888 ArtMethod* vtable_method_for_name_comparison =
7889 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007890 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007891 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007892 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007893 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7894 // allocations.
7895 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007896 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007897 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007898 vtable_method->PrettyMethod().c_str(),
7899 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007900 return false;
Alex Light9139e002015-10-09 15:59:48 -07007901 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007902 // We might have a newer, better, default method for this, so we just skip it. If we
7903 // are still using this we will select it again when scanning for default methods. To
7904 // obviate the need to copy the method again we will make a note that we already found
7905 // a default here.
7906 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007907 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007908 break;
7909 } else {
7910 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007911 if (LIKELY(fill_tables)) {
7912 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7913 // Place method in imt if entry is empty, place conflict otherwise.
7914 SetIMTRef(unimplemented_method,
7915 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007916 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007917 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007918 /*out*/imt_ptr);
7919 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007920 break;
7921 }
7922 }
Alex Light9139e002015-10-09 15:59:48 -07007923 }
7924 // Continue on to the next method if we are done.
7925 if (LIKELY(found_impl)) {
7926 continue;
7927 } else if (LIKELY(super_interface)) {
7928 // Don't look for a default implementation when the super-method is implemented directly
7929 // by the class.
7930 //
7931 // See if we can use the superclasses method and skip searching everything else.
7932 // Note: !found_impl && super_interface
7933 CHECK(extend_super_iftable);
7934 // If this is a super_interface method it is possible we shouldn't override it because a
7935 // superclass could have implemented it directly. We get the method the superclass used
7936 // to implement this to know if we can override it with a default method. Doing this is
7937 // safe since we know that the super_iftable is filled in so we can simply pull it from
7938 // there. We don't bother if this is not a super-classes interface since in that case we
7939 // have scanned the entire vtable anyway and would have found it.
7940 // TODO This is rather dirty but it is faster than searching through the entire vtable
7941 // every time.
7942 ArtMethod* supers_method =
7943 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7944 DCHECK(supers_method != nullptr);
7945 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007946 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007947 // The method is not overridable by a default method (i.e. it is directly implemented
7948 // in some class). Therefore move onto the next interface method.
7949 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007950 } else {
7951 // If the super-classes method is override-able by a default method we need to keep
7952 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7953 // 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 -07007954 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7955 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7956 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007957 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007958 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7959 << " and not 'nullptr' or "
7960 << supers_method->PrettyMethod()
7961 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007962 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007963 }
7964 }
7965 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007966 ArtMethod* current_method = helper.FindMethod(interface_method,
7967 interface_name_comparator,
7968 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007969 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007970 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007971 // We could not find an implementation for this method and since it is a brand new
7972 // interface we searched the entire vtable (and all default methods) for an
7973 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007974 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7975 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007976 }
7977
7978 if (current_method != nullptr) {
7979 // We found a default method implementation. Record it in the iftable and IMT.
7980 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7981 SetIMTRef(unimplemented_method,
7982 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007983 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007984 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007985 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007986 }
7987 }
Alex Light705ad492015-09-21 11:36:30 -07007988 } // For each method in interface end.
7989 } // if (num_methods > 0)
7990 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007991 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007992 if (helper.HasNewVirtuals()) {
7993 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7994 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7995 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7996
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007997 // 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 -07007998 // suspension assert.
7999 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008000
Alex Light705ad492015-09-21 11:36:30 -07008001 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008002 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008003 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008004 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008005 return false;
8006 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008007 helper.UpdateIfTable(iftable);
8008 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008009 }
Alex Light705ad492015-09-21 11:36:30 -07008010
Vladimir Marko921094a2017-01-12 18:37:06 +00008011 helper.CheckNoStaleMethodsInDexCache();
8012 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008013 } else {
8014 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008015 }
Alex Light705ad492015-09-21 11:36:30 -07008016 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008017 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008018 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008019 return true;
8020}
8021
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008022bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008023 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008024 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008025}
8026
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008027bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008028 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008029 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008030}
8031
Brian Carlstromdbc05252011-09-09 01:59:59 -07008032struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008033 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008034 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008035 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008036 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008037 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008038 // 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 -07008039 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8040 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008041 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008042 if (type1 == Primitive::kPrimNot) {
8043 // Reference always goes first.
8044 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008045 }
Vladimir Markod5777482014-11-12 17:02:02 +00008046 if (type2 == Primitive::kPrimNot) {
8047 // Reference always goes first.
8048 return false;
8049 }
8050 size_t size1 = Primitive::ComponentSize(type1);
8051 size_t size2 = Primitive::ComponentSize(type2);
8052 if (size1 != size2) {
8053 // Larger primitive types go first.
8054 return size1 > size2;
8055 }
8056 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8057 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008058 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008059 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8060 // by name and for equal names by type id index.
8061 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8062 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008063 }
8064};
8065
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008066bool ClassLinker::LinkFields(Thread* self,
8067 Handle<mirror::Class> klass,
8068 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008069 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008070 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008071 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008072 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8073 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008074
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008075 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008076 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008077 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008078 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008079 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008080 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008081 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008082 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008083 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008084 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008085 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008086 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008087
David Sehr709b0702016-10-13 09:12:37 -07008088 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008089
Brian Carlstromdbc05252011-09-09 01:59:59 -07008090 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008091 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008092 //
8093 // The overall sort order order is:
8094 // 1) All object reference fields, sorted alphabetically.
8095 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8096 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8097 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8098 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8099 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8100 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8101 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8102 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8103 //
8104 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8105 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008106 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008107 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008108 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008109 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008110 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008111 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008112 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8113 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008114
Fred Shih381e4ca2014-08-25 17:24:27 -07008115 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008116 size_t current_field = 0;
8117 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008118 FieldGaps gaps;
8119
Brian Carlstromdbc05252011-09-09 01:59:59 -07008120 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008121 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008122 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008123 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008124 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008125 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008126 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008127 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8128 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008129 MemberOffset old_offset = field_offset;
8130 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8131 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8132 }
Roland Levillain14d90572015-07-16 10:52:26 +01008133 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008134 grouped_and_sorted_fields.pop_front();
8135 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008136 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008137 field_offset = MemberOffset(field_offset.Uint32Value() +
8138 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008139 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008140 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8141 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008142 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8143 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8144 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8145 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008146 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8147 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008148 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008149
Elliott Hughesadb460d2011-10-05 17:02:34 -07008150 // 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 -07008151 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008152 // We know there are no non-reference fields in the Reference classes, and we know
8153 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008154 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008155 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008156 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008157 --num_reference_fields;
8158 }
8159
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008160 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008161 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008162 if (is_static) {
8163 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008164 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008165 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008166 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008167 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008168 if (num_reference_fields == 0 || super_class == nullptr) {
8169 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008170 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008171 if (super_class == nullptr ||
8172 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8173 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008174 }
8175 }
8176 if (kIsDebugBuild) {
8177 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8178 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008179 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008180 while (cur_super != nullptr) {
8181 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8182 cur_super = cur_super->GetSuperClass();
8183 }
8184 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008185 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008186 } else {
8187 // Check that there is at least num_reference_fields other than Object.class.
8188 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008189 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008190 }
8191 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008192 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008193 std::string temp;
8194 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8195 size_t previous_size = klass->GetObjectSize();
8196 if (previous_size != 0) {
8197 // Make sure that we didn't originally have an incorrect size.
8198 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008199 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008200 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008201 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008202 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008203
8204 if (kIsDebugBuild) {
8205 // Make sure that the fields array is ordered by name but all reference
8206 // offsets are at the beginning as far as alignment allows.
8207 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008208 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008209 : klass->GetFirstReferenceInstanceFieldOffset();
8210 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8211 num_reference_fields *
8212 sizeof(mirror::HeapReference<mirror::Object>));
8213 MemberOffset current_ref_offset = start_ref_offset;
8214 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008215 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008216 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008217 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8218 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008219 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008220 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008221 // NOTE: The field names can be the same. This is not possible in the Java language
8222 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008223 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008224 }
8225 Primitive::Type type = field->GetTypeAsPrimitiveType();
8226 bool is_primitive = type != Primitive::kPrimNot;
8227 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8228 strcmp("referent", field->GetName()) == 0) {
8229 is_primitive = true; // We lied above, so we have to expect a lie here.
8230 }
8231 MemberOffset offset = field->GetOffsetDuringLinking();
8232 if (is_primitive) {
8233 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8234 // Shuffled before references.
8235 size_t type_size = Primitive::ComponentSize(type);
8236 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8237 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8238 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8239 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8240 }
8241 } else {
8242 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8243 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8244 sizeof(mirror::HeapReference<mirror::Object>));
8245 }
8246 }
8247 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8248 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008249 return true;
8250}
8251
Vladimir Marko76649e82014-11-10 18:32:59 +00008252// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008253void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008254 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008255 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008256 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008257 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008258 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008259 // Compute reference offsets unless our superclass overflowed.
8260 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8261 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008262 if (num_reference_fields != 0u) {
8263 // All of the fields that contain object references are guaranteed be grouped in memory
8264 // starting at an appropriately aligned address after super class object data.
8265 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8266 sizeof(mirror::HeapReference<mirror::Object>));
8267 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008268 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008269 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008270 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008271 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008272 reference_offsets |= (0xffffffffu << start_bit) &
8273 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008274 }
8275 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008276 }
8277 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008278 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008279}
8280
Vladimir Marko18090d12018-06-01 16:53:12 +01008281ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8282 ObjPtr<mirror::DexCache> dex_cache) {
8283 StackHandleScope<1> hs(Thread::Current());
8284 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8285 return DoResolveString(string_idx, h_dex_cache);
8286}
8287
8288ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8289 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008290 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008291 uint32_t utf16_length;
8292 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008293 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008294 if (string != nullptr) {
8295 dex_cache->SetResolvedString(string_idx, string);
8296 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008297 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008298}
8299
Vladimir Marko18090d12018-06-01 16:53:12 +01008300ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8301 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008302 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008303 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008304 uint32_t utf16_length;
8305 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008306 ObjPtr<mirror::String> string =
8307 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008308 if (string != nullptr) {
8309 dex_cache->SetResolvedString(string_idx, string);
8310 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008311 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008312}
8313
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008314ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008315 ObjPtr<mirror::Class> referrer) {
8316 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8317}
8318
8319ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008320 ObjPtr<mirror::DexCache> dex_cache,
8321 ObjPtr<mirror::ClassLoader> class_loader) {
8322 const DexFile& dex_file = *dex_cache->GetDexFile();
8323 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8324 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8325 ObjPtr<mirror::Class> type = nullptr;
8326 if (descriptor[1] == '\0') {
8327 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8328 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008329 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008330 } else {
8331 Thread* const self = Thread::Current();
8332 DCHECK(self != nullptr);
8333 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8334 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008335 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008336 }
8337 if (type != nullptr) {
8338 if (type->IsResolved()) {
8339 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008340 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008341 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008342 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008343 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008344 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008345}
8346
Andreas Gampe4835d212018-11-21 14:55:10 -08008347template <typename T>
8348ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008349 StackHandleScope<2> hs(Thread::Current());
8350 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8351 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8352 return DoResolveType(type_idx, dex_cache, class_loader);
8353}
8354
Andreas Gampe4835d212018-11-21 14:55:10 -08008355// Instantiate the above.
8356template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8357 ArtField* referrer);
8358template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8359 ArtMethod* referrer);
8360template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8361 ObjPtr<mirror::Class> referrer);
8362
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008363ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008364 Handle<mirror::DexCache> dex_cache,
8365 Handle<mirror::ClassLoader> class_loader) {
8366 Thread* self = Thread::Current();
8367 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8368 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8369 if (resolved != nullptr) {
8370 // TODO: we used to throw here if resolved's class loader was not the
8371 // boot class loader. This was to permit different classes with the
8372 // same name to be loaded simultaneously by different loaders
8373 dex_cache->SetResolvedType(type_idx, resolved);
8374 } else {
8375 CHECK(self->IsExceptionPending())
8376 << "Expected pending exception for failed resolution of: " << descriptor;
8377 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8378 StackHandleScope<1> hs(self);
8379 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008380 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008381 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8382 self->ClearException();
8383 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8384 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008385 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008386 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008387 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008388 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008389 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008390}
8391
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008392ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8393 ObjPtr<mirror::DexCache> dex_cache,
8394 ObjPtr<mirror::ClassLoader> class_loader,
8395 uint32_t method_idx) {
8396 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8397 // functions can optimize the search if the dex_cache is the same as the DexCache
8398 // of the class, with fall-back to name and signature search otherwise.
8399 ArtMethod* resolved = nullptr;
8400 if (klass->IsInterface()) {
8401 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8402 } else {
8403 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8404 }
8405 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008406 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008407 hiddenapi::ShouldDenyAccessToMember(resolved,
8408 hiddenapi::AccessContext(class_loader, dex_cache),
8409 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008410 resolved = nullptr;
8411 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008412 if (resolved != nullptr) {
8413 // In case of jmvti, the dex file gets verified before being registered, so first
8414 // check if it's registered before checking class tables.
8415 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008416 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8417 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008418 << "DexFile referrer: " << dex_file.GetLocation()
8419 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8420 // Be a good citizen and update the dex cache to speed subsequent calls.
8421 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008422 // Disable the following invariant check as the verifier breaks it. b/73760543
8423 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8424 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8425 // << "Method: " << resolved->PrettyMethod() << ", "
8426 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8427 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008428 }
8429 return resolved;
8430}
8431
David Brazdil4525e0b2018-04-05 16:57:32 +01008432// Returns true if `method` is either null or hidden.
8433// Does not print any warnings if it is hidden.
8434static bool CheckNoSuchMethod(ArtMethod* method,
8435 ObjPtr<mirror::DexCache> dex_cache,
8436 ObjPtr<mirror::ClassLoader> class_loader)
8437 REQUIRES_SHARED(Locks::mutator_lock_) {
8438 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008439 hiddenapi::ShouldDenyAccessToMember(method,
8440 hiddenapi::AccessContext(class_loader, dex_cache),
8441 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008442}
8443
8444ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8445 ObjPtr<mirror::DexCache> dex_cache,
8446 ObjPtr<mirror::ClassLoader> class_loader,
8447 uint32_t method_idx) {
8448 if (klass->IsInterface()) {
8449 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8450 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8451 } else {
8452 // If there was an interface method with the same signature, we would have
8453 // found it in the "copied" methods. Only DCHECK that the interface method
8454 // really does not exist.
8455 if (kIsDebugBuild) {
8456 ArtMethod* method =
8457 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8458 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8459 }
8460 return nullptr;
8461 }
8462}
8463
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008464template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008465ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008466 Handle<mirror::DexCache> dex_cache,
8467 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008468 ArtMethod* referrer,
8469 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008470 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008471 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008472 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008473 PointerSize pointer_size = image_pointer_size_;
8474 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008475 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008476 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8477 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008478 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8479 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008480 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008481 return resolved;
8482 }
Vladimir Marko89011192017-12-11 13:45:05 +00008483 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008484 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008485 ObjPtr<mirror::Class> klass = nullptr;
8486 if (valid_dex_cache_method) {
8487 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8488 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008489 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008490 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008491 // We normaly should not end up here. However the verifier currently doesn't guarantee
8492 // the invariant of having the klass in the class table. b/73760543
8493 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008494 }
Vladimir Markoba118822017-06-12 15:41:56 +01008495 } else {
8496 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008497 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008498 if (klass == nullptr) {
8499 DCHECK(Thread::Current()->IsExceptionPending());
8500 return nullptr;
8501 }
8502 }
8503
8504 // Check if the invoke type matches the class type.
8505 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008506 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008507 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008508 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008509 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008510 }
Vladimir Markoba118822017-06-12 15:41:56 +01008511
8512 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008513 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008514 }
Vladimir Markoba118822017-06-12 15:41:56 +01008515
8516 // Note: We can check for IllegalAccessError only if we have a referrer.
8517 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8518 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8519 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8520 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8521 resolved,
8522 dex_cache.Get(),
8523 method_idx,
8524 type)) {
8525 DCHECK(Thread::Current()->IsExceptionPending());
8526 return nullptr;
8527 }
8528 }
8529
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008530 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008531 if (LIKELY(resolved != nullptr) &&
8532 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8533 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008534 return resolved;
8535 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008536 // If we had a method, or if we can find one with another lookup type,
8537 // it's an incompatible-class-change error.
8538 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008539 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008540 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008541 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008542 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008543 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008544 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008545 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8546 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008547 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008548 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008549 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008550 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008551 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008552}
8553
Vladimir Marko89011192017-12-11 13:45:05 +00008554ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008555 Handle<mirror::DexCache> dex_cache,
8556 Handle<mirror::ClassLoader> class_loader) {
8557 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008558 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008559 if (resolved != nullptr) {
8560 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008561 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8562 return resolved;
8563 }
8564 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008565 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008566 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008567 if (klass == nullptr) {
8568 Thread::Current()->AssertPendingException();
8569 return nullptr;
8570 }
8571 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008572 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8573 } else {
8574 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008575 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008576 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008577 hiddenapi::ShouldDenyAccessToMember(
8578 resolved,
8579 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8580 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008581 resolved = nullptr;
8582 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008583 return resolved;
8584}
8585
Vladimir Markof44d36c2017-03-14 14:18:46 +00008586ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8587 ObjPtr<mirror::DexCache> dex_cache,
8588 ObjPtr<mirror::ClassLoader> class_loader,
8589 bool is_static) {
8590 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008591 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008592 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8593 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008594 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008595 }
8596 if (klass == nullptr) {
8597 // The class has not been resolved yet, so the field is also unresolved.
8598 return nullptr;
8599 }
8600 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008601
David Brazdil1ab0fa82018-05-04 11:28:03 +01008602 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008603}
8604
Vladimir Markoe11dd502017-12-08 14:09:45 +00008605ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008606 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008607 Handle<mirror::ClassLoader> class_loader,
8608 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008609 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008610 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008611 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008612 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008613 return resolved;
8614 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008615 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008616 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008617 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008618 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008619 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008620 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008621 }
8622
David Brazdil1ab0fa82018-05-04 11:28:03 +01008623 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008624 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008625 const char* name = dex_file.GetFieldName(field_id);
8626 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008627 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008628 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008629 return resolved;
8630}
8631
Vladimir Markoe11dd502017-12-08 14:09:45 +00008632ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008633 Handle<mirror::DexCache> dex_cache,
8634 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008635 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008636 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008637 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008638 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008639 return resolved;
8640 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008641 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008642 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008643 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008644 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008645 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008646 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008647 }
8648
David Brazdil1ab0fa82018-05-04 11:28:03 +01008649 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8650 if (resolved == nullptr) {
8651 const char* name = dex_file.GetFieldName(field_id);
8652 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008653 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008654 }
8655 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008656}
8657
David Brazdil1ab0fa82018-05-04 11:28:03 +01008658ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8659 ObjPtr<mirror::DexCache> dex_cache,
8660 ObjPtr<mirror::ClassLoader> class_loader,
8661 uint32_t field_idx,
8662 bool is_static) {
8663 ArtField* resolved = nullptr;
8664 Thread* self = is_static ? Thread::Current() : nullptr;
8665 const DexFile& dex_file = *dex_cache->GetDexFile();
8666
8667 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8668 : klass->FindInstanceField(dex_cache, field_idx);
8669
8670 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008671 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008672 const char* name = dex_file.GetFieldName(field_id);
8673 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8674 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8675 : klass->FindInstanceField(name, type);
8676 }
8677
8678 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008679 hiddenapi::ShouldDenyAccessToMember(resolved,
8680 hiddenapi::AccessContext(class_loader, dex_cache),
8681 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008682 resolved = nullptr;
8683 }
8684
8685 if (resolved != nullptr) {
8686 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8687 }
8688
8689 return resolved;
8690}
8691
8692ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8693 ObjPtr<mirror::DexCache> dex_cache,
8694 ObjPtr<mirror::ClassLoader> class_loader,
8695 uint32_t field_idx) {
8696 ArtField* resolved = nullptr;
8697 Thread* self = Thread::Current();
8698 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008699 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008700
8701 const char* name = dex_file.GetFieldName(field_id);
8702 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8703 resolved = mirror::Class::FindField(self, klass, name, type);
8704
8705 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008706 hiddenapi::ShouldDenyAccessToMember(resolved,
8707 hiddenapi::AccessContext(class_loader, dex_cache),
8708 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008709 resolved = nullptr;
8710 }
8711
8712 if (resolved != nullptr) {
8713 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8714 }
8715
8716 return resolved;
8717}
8718
Vladimir Markoaf940202017-12-08 15:01:18 +00008719ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8720 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008721 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008722 Handle<mirror::DexCache> dex_cache,
8723 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008724 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008725 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008726
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008727 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008728 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008729 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008730 }
8731
Narayan Kamath25352fc2016-08-03 12:46:58 +01008732 StackHandleScope<4> hs(self);
8733
8734 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008735 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008736 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008737 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008738 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008739 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008740 DCHECK(self->IsExceptionPending());
8741 return nullptr;
8742 }
8743
8744 // Then resolve the argument types.
8745 //
8746 // TODO: Is there a better way to figure out the number of method arguments
8747 // other than by looking at the shorty ?
8748 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8749
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008750 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008751 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8752 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008753 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008754 DCHECK(self->IsExceptionPending());
8755 return nullptr;
8756 }
8757
8758 DexFileParameterIterator it(dex_file, proto_id);
8759 int32_t i = 0;
8760 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8761 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008762 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008763 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008764 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008765 DCHECK(self->IsExceptionPending());
8766 return nullptr;
8767 }
8768
8769 method_params->Set(i++, param_class.Get());
8770 }
8771
8772 DCHECK(!it.HasNext());
8773
8774 Handle<mirror::MethodType> type = hs.NewHandle(
8775 mirror::MethodType::Create(self, return_type, method_params));
8776 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8777
8778 return type.Get();
8779}
8780
Vladimir Markoaf940202017-12-08 15:01:18 +00008781ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008782 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008783 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008784 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008785 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8786 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008787 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008788}
8789
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008790mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8791 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008792 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008793 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008794 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008795 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8796 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008797 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008798 bool is_static;
8799 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008800 switch (handle_type) {
8801 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008802 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008803 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008804 is_static = true;
8805 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008806 break;
8807 }
8808 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008809 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008810 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008811 is_static = true;
8812 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008813 break;
8814 }
8815 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008816 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008817 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008818 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008819 num_params = 2;
8820 break;
8821 }
8822 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008823 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008824 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008825 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008826 num_params = 1;
8827 break;
8828 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008829 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008830 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008831 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008832 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008833 case DexFile::MethodHandleType::kInvokeInterface:
8834 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008835 }
8836
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008837 ArtField* target_field =
8838 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8839 if (LIKELY(target_field != nullptr)) {
8840 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8841 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8842 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8843 ThrowIllegalAccessErrorField(referring_class, target_field);
8844 return nullptr;
8845 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008846 if (UNLIKELY(is_put && target_field->IsFinal())) {
8847 ThrowIllegalAccessErrorField(referring_class, target_field);
8848 return nullptr;
8849 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008850 } else {
8851 DCHECK(Thread::Current()->IsExceptionPending());
8852 return nullptr;
8853 }
8854
8855 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008856 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008857 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8858 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008859 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008860 DCHECK(self->IsExceptionPending());
8861 return nullptr;
8862 }
8863
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008864 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008865 Handle<mirror::Class> return_type;
8866 switch (handle_type) {
8867 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008868 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008869 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008870 break;
8871 }
8872 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008873 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008874 break;
8875 }
8876 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008877 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008878 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008879 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008880 break;
8881 }
8882 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008883 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008884 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008885 break;
8886 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008887 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008888 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008889 case DexFile::MethodHandleType::kInvokeConstructor:
8890 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008891 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008892 UNREACHABLE();
8893 }
8894
8895 for (int32_t i = 0; i < num_params; ++i) {
8896 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8897 DCHECK(self->IsExceptionPending());
8898 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008899 }
8900 }
8901
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008902 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008903 DCHECK(self->IsExceptionPending());
8904 return nullptr;
8905 }
8906
8907 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008908 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8909 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008910 DCHECK(self->IsExceptionPending());
8911 return nullptr;
8912 }
Orion Hodson631827d2017-04-10 14:53:47 +01008913
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008914 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8915 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8916}
8917
8918mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8919 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008920 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008921 ArtMethod* referrer) {
8922 DexFile::MethodHandleType handle_type =
8923 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8924 mirror::MethodHandle::Kind kind;
8925 uint32_t receiver_count = 0;
8926 ArtMethod* target_method = nullptr;
8927 switch (handle_type) {
8928 case DexFile::MethodHandleType::kStaticPut:
8929 case DexFile::MethodHandleType::kStaticGet:
8930 case DexFile::MethodHandleType::kInstancePut:
8931 case DexFile::MethodHandleType::kInstanceGet:
8932 UNREACHABLE();
8933 case DexFile::MethodHandleType::kInvokeStatic: {
8934 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8935 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008936 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8937 method_handle.field_or_method_idx_,
8938 referrer,
8939 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008940 break;
8941 }
8942 case DexFile::MethodHandleType::kInvokeInstance: {
8943 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8944 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008945 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8946 method_handle.field_or_method_idx_,
8947 referrer,
8948 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008949 break;
8950 }
8951 case DexFile::MethodHandleType::kInvokeConstructor: {
8952 // Constructors are currently implemented as a transform. They
8953 // are special cased later in this method.
8954 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8955 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008956 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8957 method_handle.field_or_method_idx_,
8958 referrer,
8959 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008960 break;
8961 }
8962 case DexFile::MethodHandleType::kInvokeDirect: {
8963 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8964 receiver_count = 1;
8965 StackHandleScope<2> hs(self);
8966 // A constant method handle with type kInvokeDirect can refer to
8967 // a method that is private or to a method in a super class. To
8968 // disambiguate the two options, we resolve the method ignoring
8969 // the invocation type to determine if the method is private. We
8970 // then resolve again specifying the intended invocation type to
8971 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008972 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008973 hs.NewHandle(referrer->GetDexCache()),
8974 hs.NewHandle(referrer->GetClassLoader()));
8975 if (UNLIKELY(target_method == nullptr)) {
8976 break;
8977 }
8978
8979 if (target_method->IsPrivate()) {
8980 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008981 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8982 method_handle.field_or_method_idx_,
8983 referrer,
8984 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008985 } else {
8986 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008987 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8988 method_handle.field_or_method_idx_,
8989 referrer,
8990 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008991 if (UNLIKELY(target_method == nullptr)) {
8992 break;
8993 }
8994 // Find the method specified in the parent in referring class
8995 // so invoke-super invokes the method in the parent of the
8996 // referrer.
8997 target_method =
8998 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8999 kRuntimePointerSize);
9000 }
9001 break;
9002 }
9003 case DexFile::MethodHandleType::kInvokeInterface: {
9004 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9005 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009006 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9007 method_handle.field_or_method_idx_,
9008 referrer,
9009 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009010 break;
9011 }
Orion Hodson631827d2017-04-10 14:53:47 +01009012 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009013
9014 if (UNLIKELY(target_method == nullptr)) {
9015 DCHECK(Thread::Current()->IsExceptionPending());
9016 return nullptr;
9017 }
9018
9019 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9020 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9021 uint32_t access_flags = target_method->GetAccessFlags();
9022 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9023 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9024 return nullptr;
9025 }
9026
9027 // Calculate the number of parameters from the method shorty. We add the
9028 // receiver count (0 or 1) and deduct one for the return value.
9029 uint32_t shorty_length;
9030 target_method->GetShorty(&shorty_length);
9031 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9032
Orion Hodsonecd58562018-09-24 11:27:33 +01009033 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009034 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009035 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9036 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9037 if (method_params.Get() == nullptr) {
9038 DCHECK(self->IsExceptionPending());
9039 return nullptr;
9040 }
9041
Orion Hodsonecd58562018-09-24 11:27:33 +01009042 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009043 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009044 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009045 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009046 // Insert receiver. Use the class identified in the method handle rather than the declaring
9047 // class of the resolved method which may be super class or default interface method
9048 // (b/115964401).
9049 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9050 // receiver_class should have been resolved when resolving the target method.
9051 DCHECK(receiver_class != nullptr);
9052 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009053 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009054
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009055 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009056 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009057 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009058 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009059 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009060 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009061 if (nullptr == klass) {
9062 DCHECK(self->IsExceptionPending());
9063 return nullptr;
9064 }
9065 method_params->Set(index++, klass);
9066 it.Next();
9067 }
9068
Orion Hodsonecd58562018-09-24 11:27:33 +01009069 Handle<mirror::Class> return_type =
9070 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009071 if (UNLIKELY(return_type.IsNull())) {
9072 DCHECK(self->IsExceptionPending());
9073 return nullptr;
9074 }
9075
9076 Handle<mirror::MethodType>
9077 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9078 if (UNLIKELY(method_type.IsNull())) {
9079 DCHECK(self->IsExceptionPending());
9080 return nullptr;
9081 }
9082
9083 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9084 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9085 Handle<mirror::MethodHandlesLookup> lookup =
9086 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9087 return lookup->FindConstructor(self, constructor_class, method_type);
9088 }
9089
9090 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9091 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9092}
9093
Vladimir Markoaf940202017-12-08 15:01:18 +00009094ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9095 uint32_t method_handle_idx,
9096 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009097 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009098 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009099 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009100 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9101 case DexFile::MethodHandleType::kStaticPut:
9102 case DexFile::MethodHandleType::kStaticGet:
9103 case DexFile::MethodHandleType::kInstancePut:
9104 case DexFile::MethodHandleType::kInstanceGet:
9105 return ResolveMethodHandleForField(self, method_handle, referrer);
9106 case DexFile::MethodHandleType::kInvokeStatic:
9107 case DexFile::MethodHandleType::kInvokeInstance:
9108 case DexFile::MethodHandleType::kInvokeConstructor:
9109 case DexFile::MethodHandleType::kInvokeDirect:
9110 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009111 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009112 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009113}
9114
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009115bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9116 return (entry_point == GetQuickResolutionStub()) ||
9117 (quick_resolution_trampoline_ == entry_point);
9118}
9119
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009120bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9121 return (entry_point == GetQuickToInterpreterBridge()) ||
9122 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9123}
9124
9125bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9126 return (entry_point == GetQuickGenericJniStub()) ||
9127 (quick_generic_jni_trampoline_ == entry_point);
9128}
9129
David Sehra49e0532017-08-25 08:05:29 -07009130bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9131 return entry_point == GetJniDlsymLookupStub();
9132}
9133
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009134const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9135 return GetQuickGenericJniStub();
9136}
9137
Mathieu Chartiere401d142015-04-22 13:56:20 -07009138void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009139 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009140 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9141 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009142 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009143 }
9144}
9145
Alex Lightdb01a092017-04-03 15:39:55 -07009146void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9147 DCHECK(method->IsObsolete());
9148 // We cannot mess with the entrypoints of native methods because they are used to determine how
9149 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9150 if (!method->IsNative()) {
9151 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9152 }
9153}
9154
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009155void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009156 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009157 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009158 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9159 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009160 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9161 os << "Dumping registered class loaders\n";
9162 size_t class_loader_index = 0;
9163 for (const ClassLoaderData& class_loader : class_loaders_) {
9164 ObjPtr<mirror::ClassLoader> loader =
9165 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9166 if (loader != nullptr) {
9167 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9168 bool saw_one_dex_file = false;
9169 for (const DexCacheData& dex_cache : dex_caches_) {
9170 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9171 if (saw_one_dex_file) {
9172 os << ":";
9173 }
9174 saw_one_dex_file = true;
9175 os << dex_cache.dex_file->GetLocation();
9176 }
9177 }
9178 os << "]";
9179 bool found_parent = false;
9180 if (loader->GetParent() != nullptr) {
9181 size_t parent_index = 0;
9182 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9183 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9184 soa.Self()->DecodeJObject(class_loader2.weak_root));
9185 if (loader2 == loader->GetParent()) {
9186 os << ", parent #" << parent_index;
9187 found_parent = true;
9188 break;
9189 }
9190 parent_index++;
9191 }
9192 if (!found_parent) {
9193 os << ", unregistered parent of type "
9194 << loader->GetParent()->GetClass()->PrettyDescriptor();
9195 }
9196 } else {
9197 os << ", no parent";
9198 }
9199 os << "\n";
9200 }
9201 }
9202 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009203}
9204
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009205class CountClassesVisitor : public ClassLoaderVisitor {
9206 public:
9207 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9208
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009209 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009210 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009211 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009212 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009213 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9214 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009215 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009216 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009217
9218 size_t num_zygote_classes;
9219 size_t num_non_zygote_classes;
9220};
9221
9222size_t ClassLinker::NumZygoteClasses() const {
9223 CountClassesVisitor visitor;
9224 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009225 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009226}
9227
9228size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009229 CountClassesVisitor visitor;
9230 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009231 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009232}
9233
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009234size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009235 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009236 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009237 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009238}
9239
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009240pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009241 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009242}
9243
9244pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009245 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009246}
9247
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009248void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009249 DCHECK(!init_done_);
9250
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009251 DCHECK(klass != nullptr);
9252 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009253
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009254 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009255 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009256 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9257 int32_t index = static_cast<int32_t>(class_root);
9258 DCHECK(class_roots->Get(index) == nullptr);
9259 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009260}
9261
Roland Levillain0e840272018-08-23 19:55:30 +01009262void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9263 ObjPtr<mirror::Class> java_lang_Class,
9264 ClassRoot primitive_array_class_root,
9265 ClassRoot primitive_class_root,
9266 const char* descriptor) {
9267 StackHandleScope<1> hs(self);
9268 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9269 AllocPrimitiveArrayClass(self, java_lang_Class)));
9270 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9271 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9272 CheckSystemClass(self, primitive_array_class, descriptor);
9273}
9274
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009275ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9276 Thread* self,
9277 const std::vector<const DexFile*>& dex_files,
9278 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009279 Handle<mirror::ClassLoader> parent_loader,
9280 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009281
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009282 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009283
Mathieu Chartierc7853442015-03-27 14:35:38 -07009284 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009285 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009286
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009287 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009288 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009289 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009290 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009291 mirror::ObjectArray<mirror::Object>::Alloc(self,
9292 dex_elements_class.Get(),
9293 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009294 Handle<mirror::Class> h_dex_element_class =
9295 hs.NewHandle(dex_elements_class->GetComponentType());
9296
Mathieu Chartierc7853442015-03-27 14:35:38 -07009297 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009298 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009299 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009300
Andreas Gampe08883de2016-11-08 13:20:52 -08009301 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009302 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009303
Andreas Gampe08883de2016-11-08 13:20:52 -08009304 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009305 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009306
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009307 // Fill the elements array.
9308 int32_t index = 0;
9309 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009310 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009311
Calin Juravle7865ac72017-06-28 11:03:12 -07009312 // CreateWellKnownClassLoader is only used by gtests and compiler.
9313 // 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 -07009314 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9315 self,
9316 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009317 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009318 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009319
Mathieu Chartier3738e982017-05-12 16:07:28 -07009320 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9321 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009322 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009323 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009324 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009325 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009326
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009327 Handle<mirror::String> h_file_name = hs2.NewHandle(
9328 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009329 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009330 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9331
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009332 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009333 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009334 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009335
9336 h_dex_elements->Set(index, h_element.Get());
9337 index++;
9338 }
9339 DCHECK_EQ(index, h_dex_elements->GetLength());
9340
9341 // Create DexPathList.
9342 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009343 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009344 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009345 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009346 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009347 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9348 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9349 // elements.
9350 {
9351 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9352 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9353 DCHECK(native_lib_dirs != nullptr);
9354 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9355 DCHECK(list_class != nullptr);
9356 {
9357 StackHandleScope<1> h_list_scope(self);
9358 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9359 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9360 DCHECK(list_init);
9361 list_class = h_list_class.Get();
9362 }
9363 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9364 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9365 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9366 // normally never null), as long as one does not try to add elements, this will still
9367 // work.
9368 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9369 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009370
Calin Juravle7865ac72017-06-28 11:03:12 -07009371 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009372 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9373 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009374 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009375 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009376 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009377 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009378 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009379 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009380
9381 // Make a pretend boot-classpath.
9382 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009383 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009384 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009385 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009386 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009387 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009388 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009389 if (parent_loader.Get() == nullptr) {
9390 ScopedObjectAccessUnchecked soa(self);
9391 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9392 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9393 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9394 } else {
9395 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9396 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009397
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009398 ArtField* shared_libraries_field =
9399 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9400 DCHECK(shared_libraries_field != nullptr);
9401 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9402
9403 return h_class_loader.Get();
9404}
9405
9406jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9407 const std::vector<const DexFile*>& dex_files,
9408 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009409 jobject parent_loader,
9410 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009411 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9412 WellKnownClasses::dalvik_system_PathClassLoader) ||
9413 self->GetJniEnv()->IsSameObject(loader_class,
9414 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
9415
9416 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9417 // We could move the jobject to the callers, but all call-sites do this...
9418 ScopedObjectAccessUnchecked soa(self);
9419
9420 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009421 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009422
9423 Handle<mirror::Class> h_loader_class =
9424 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009425 Handle<mirror::ClassLoader> h_parent =
9426 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9427 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9428 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009429
9430 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9431 self,
9432 dex_files,
9433 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009434 h_parent,
9435 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009436
9437 // Make it a global ref and return.
9438 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009439 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009440 return soa.Env()->NewGlobalRef(local_ref.get());
9441}
9442
Calin Juravle7865ac72017-06-28 11:03:12 -07009443jobject ClassLinker::CreatePathClassLoader(Thread* self,
9444 const std::vector<const DexFile*>& dex_files) {
9445 return CreateWellKnownClassLoader(self,
9446 dex_files,
9447 WellKnownClasses::dalvik_system_PathClassLoader,
9448 nullptr);
9449}
9450
Andreas Gampe8ac75952015-06-02 21:01:45 -07009451void ClassLinker::DropFindArrayClassCache() {
9452 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9453 find_array_class_cache_next_victim_ = 0;
9454}
9455
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009456void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009457 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009458 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009459 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009460 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9461 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009462 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009463 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009464 }
9465 }
9466}
9467
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009468void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9469 for (const ClassLoaderData& data : class_loaders_) {
9470 LinearAlloc* alloc = data.allocator;
9471 if (alloc != nullptr && !visitor->Visit(alloc)) {
9472 break;
9473 }
9474 }
9475}
9476
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009477void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9478 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009479 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009480 Thread* const self = Thread::Current();
9481 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009482 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009483 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009484 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009485 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9486 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009487 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009488 }
9489}
9490
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009491void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009492 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009493 std::vector<ClassLoaderData> to_delete;
9494 // Do the delete outside the lock to avoid lock violation in jit code cache.
9495 {
9496 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9497 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9498 const ClassLoaderData& data = *it;
9499 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009500 ObjPtr<mirror::ClassLoader> class_loader =
9501 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009502 if (class_loader != nullptr) {
9503 ++it;
9504 } else {
9505 VLOG(class_linker) << "Freeing class loader";
9506 to_delete.push_back(data);
9507 it = class_loaders_.erase(it);
9508 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009509 }
9510 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009511 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009512 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009513 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009514 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009515}
9516
Vladimir Marko21300532017-01-24 18:06:55 +00009517class GetResolvedClassesVisitor : public ClassVisitor {
9518 public:
9519 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9520 : result_(result),
9521 ignore_boot_classes_(ignore_boot_classes),
9522 last_resolved_classes_(result->end()),
9523 last_dex_file_(nullptr),
9524 vlog_is_on_(VLOG_IS_ON(class_linker)),
9525 extra_stats_(),
9526 last_extra_stats_(extra_stats_.end()) { }
9527
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009528 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009529 if (!klass->IsProxyClass() &&
9530 !klass->IsArrayClass() &&
9531 klass->IsResolved() &&
9532 !klass->IsErroneousResolved() &&
9533 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9534 const DexFile& dex_file = klass->GetDexFile();
9535 if (&dex_file != last_dex_file_) {
9536 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009537 DexCacheResolvedClasses resolved_classes(
9538 dex_file.GetLocation(),
9539 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9540 dex_file.GetLocationChecksum(),
9541 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009542 last_resolved_classes_ = result_->find(resolved_classes);
9543 if (last_resolved_classes_ == result_->end()) {
9544 last_resolved_classes_ = result_->insert(resolved_classes).first;
9545 }
9546 }
9547 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9548 if (UNLIKELY(vlog_is_on_) && added) {
9549 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9550 if (last_extra_stats_ == extra_stats_.end() ||
9551 last_extra_stats_->first != resolved_classes) {
9552 last_extra_stats_ = extra_stats_.find(resolved_classes);
9553 if (last_extra_stats_ == extra_stats_.end()) {
9554 last_extra_stats_ =
9555 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9556 }
9557 }
9558 }
9559 }
9560 return true;
9561 }
9562
9563 void PrintStatistics() const {
9564 if (vlog_is_on_) {
9565 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9566 auto it = extra_stats_.find(std::addressof(resolved_classes));
9567 DCHECK(it != extra_stats_.end());
9568 const ExtraStats& extra_stats = it->second;
9569 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9570 << " has " << resolved_classes.GetClasses().size() << " / "
9571 << extra_stats.number_of_class_defs_ << " resolved classes";
9572 }
9573 }
9574 }
9575
9576 private:
9577 struct ExtraStats {
9578 explicit ExtraStats(uint32_t number_of_class_defs)
9579 : number_of_class_defs_(number_of_class_defs) {}
9580 uint32_t number_of_class_defs_;
9581 };
9582
9583 std::set<DexCacheResolvedClasses>* result_;
9584 bool ignore_boot_classes_;
9585 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9586 const DexFile* last_dex_file_;
9587
9588 // Statistics.
9589 bool vlog_is_on_;
9590 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9591 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9592};
9593
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009594std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009595 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009596 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009597 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009598 std::set<DexCacheResolvedClasses> ret;
9599 VLOG(class_linker) << "Collecting resolved classes";
9600 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009601 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9602 VisitClasses(&visitor);
9603 if (VLOG_IS_ON(class_linker)) {
9604 visitor.PrintStatistics();
9605 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009606 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009607 return ret;
9608}
9609
Mathieu Chartier65975772016-08-05 10:46:36 -07009610class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9611 public:
9612 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9613 : method_(method),
9614 pointer_size_(pointer_size) {}
9615
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009616 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009617 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9618 holder_ = klass;
9619 }
9620 // Return false to stop searching if holder_ is not null.
9621 return holder_ == nullptr;
9622 }
9623
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009624 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009625 const ArtMethod* const method_;
9626 const PointerSize pointer_size_;
9627};
9628
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009629ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009630 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9631 CHECK(method->IsCopied());
9632 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9633 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009634 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009635}
9636
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009637ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9638 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009639 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009640 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009641 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009642}
9643
Roland Levillain0e840272018-08-23 19:55:30 +01009644// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009645template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009646 uint32_t method_idx,
9647 Handle<mirror::DexCache> dex_cache,
9648 Handle<mirror::ClassLoader> class_loader,
9649 ArtMethod* referrer,
9650 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009651template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009652 uint32_t method_idx,
9653 Handle<mirror::DexCache> dex_cache,
9654 Handle<mirror::ClassLoader> class_loader,
9655 ArtMethod* referrer,
9656 InvokeType type);
9657
Roland Levillain0e840272018-08-23 19:55:30 +01009658// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009659template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009660 Thread* self,
9661 ObjPtr<mirror::Class> java_lang_Class,
9662 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009663template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009664 Thread* self,
9665 ObjPtr<mirror::Class> java_lang_Class,
9666 uint32_t class_size);
9667
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009668} // namespace art