blob: d29a6b75777e3f8b935d03f4b617847b787aa38b [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>
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include <tuple>
Alex Lighteb7c1442015-08-31 13:17:42 -070029#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070030#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070031#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070032
Andreas Gampe46ee31b2016-12-14 10:11:49 -080033#include "android-base/stringprintf.h"
34
Mathieu Chartierc7853442015-03-27 14:35:38 -070035#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070036#include "art_method-inl.h"
37#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080038#include "base/casts.h"
David Sehr67bf42e2018-02-26 16:43:04 -080039#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080040#include "base/logging.h"
David Sehrc431b9d2018-03-02 12:01:51 -080041#include "base/os.h"
42#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070043#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010044#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080045#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080046#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010047#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080048#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080049#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070050#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070051#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070053#include "class_loader_utils.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010054#include "class_root.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070055#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000056#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010057#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080058#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070059#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080060#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080061#include "dex/dex_file-inl.h"
62#include "dex/dex_file_exception_helpers.h"
63#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080064#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000065#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070066#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070067#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070068#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070069#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080070#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000071#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070072#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070073#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070074#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070075#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000076#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070077#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070078#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070079#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080080#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070081#include "imt_conflict_table.h"
82#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070083#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070084#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000085#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080086#include "jit/jit.h"
87#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010088#include "jni/java_vm_ext.h"
89#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070090#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070091#include "mirror/array-alloc-inl.h"
92#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000093#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070094#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080095#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070096#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070097#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080098#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070099#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700100#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100101#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700102#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800103#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700104#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100105#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000106#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700107#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800108#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000109#include "mirror/object-refvisitor-inl.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700110#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700111#include "mirror/object_array-inl.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700112#include "mirror/object_reference.h"
113#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800114#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700115#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800116#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700117#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100118#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700119#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700120#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700121#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700122#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700123#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700124#include "oat_file_assistant.h"
125#include "oat_file_manager.h"
126#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700127#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700128#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800129#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700130#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700131#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700132#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700133#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100134#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800135#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700136#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700137
138namespace art {
139
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800140using android::base::StringPrintf;
141
Mathieu Chartierc7853442015-03-27 14:35:38 -0700142static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700143static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700144
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700145static void ThrowNoClassDefFoundError(const char* fmt, ...)
146 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700147 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700148static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700149 va_list args;
150 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800151 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000152 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800153 va_end(args);
154}
155
Andreas Gampe99babb62015-11-02 16:20:00 -0800156static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700157 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700158 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700159 StackHandleScope<1> hs(self);
160 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700161 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700162 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700163
164 if (exception_class == nullptr) {
165 // No exc class ~ no <init>-with-string.
166 CHECK(self->IsExceptionPending());
167 self->ClearException();
168 return false;
169 }
170
Vladimir Markoba118822017-06-12 15:41:56 +0100171 ArtMethod* exception_init_method = exception_class->FindConstructor(
172 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700173 return exception_init_method != nullptr;
174}
175
Alex Lightd6251582016-10-31 11:12:30 -0700176static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700177 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700178 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
179 if (ext == nullptr) {
180 return nullptr;
181 } else {
182 return ext->GetVerifyError();
183 }
184}
185
186// Helper for ThrowEarlierClassFailure. Throws the stored error.
187static void HandleEarlierVerifyError(Thread* self,
188 ClassLinker* class_linker,
189 ObjPtr<mirror::Class> c)
190 REQUIRES_SHARED(Locks::mutator_lock_) {
191 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800192 DCHECK(obj != nullptr);
193 self->AssertNoPendingException();
194 if (obj->IsClass()) {
195 // Previous error has been stored as class. Create a new exception of that type.
196
197 // It's possible the exception doesn't have a <init>(String).
198 std::string temp;
199 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
200
201 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700202 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800203 } else {
204 self->ThrowNewException(descriptor, nullptr);
205 }
206 } else {
207 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100208 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700209 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800210 CHECK(throwable_class->IsAssignableFrom(error_class));
211 self->SetException(obj->AsThrowable());
212 }
213 self->AssertPendingException();
214}
215
Andreas Gampe5b20b352018-10-11 19:03:20 -0700216// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
217// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
218// before.
219template <bool kNeedsVerified = false>
220static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
221 REQUIRES_SHARED(Locks::mutator_lock_) {
222 if (kNeedsVerified) {
223 // To not fail access-flags access checks, push a minimal state.
224 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
225 }
226 if (!klass->WasVerificationAttempted()) {
227 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
228 klass->SetVerificationAttempted();
229 }
230}
231
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800232void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
233 bool wrap_in_no_class_def,
234 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700235 // The class failed to initialize on a previous attempt, so we want to throw
236 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
237 // failed in verification, in which case v2 5.4.1 says we need to re-throw
238 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800239 Runtime* const runtime = Runtime::Current();
240 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700241 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700242 if (GetVerifyError(c) != nullptr) {
243 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800244 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700245 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800246 } else {
247 extra = verify_error->AsThrowable()->Dump();
248 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700249 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800250 if (log) {
251 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
252 << ": " << extra;
253 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700254 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700255
David Sehr709b0702016-10-13 09:12:37 -0700256 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800257 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800258 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700259 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700260 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000261 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700262 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700263 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800264 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800265 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800266 }
Alex Lightd6251582016-10-31 11:12:30 -0700267 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
268 // might have meant to go down the earlier if statement with the original error but it got
269 // swallowed by the OOM so we end up here.
270 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800271 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
272 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
273 // exception will be a cause.
274 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700275 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700276 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700277 }
278}
279
Brian Carlstromb23eab12014-10-08 17:55:21 -0700280static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700281 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700282 if (VLOG_IS_ON(class_linker)) {
283 std::string temp;
284 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000285 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700286 }
287}
288
289static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700290 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700291 Thread* self = Thread::Current();
292 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700293
294 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700295 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700296
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800297 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
298 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
299 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800300 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800301 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
302 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
303 // could have caused the error.
304 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
305 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
306 << " failed initialization: "
307 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800308 }
309
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700310 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700311 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
312 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700313
Elliott Hughesa4f94742012-05-29 16:28:38 -0700314 // We only wrap non-Error exceptions; an Error can just be used as-is.
315 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000316 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700317 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700318 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700319}
320
Fred Shih381e4ca2014-08-25 17:24:27 -0700321// Gap between two fields in object layout.
322struct FieldGap {
323 uint32_t start_offset; // The offset from the start of the object.
324 uint32_t size; // The gap size of 1, 2, or 4 bytes.
325};
326struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800327 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700328 }
329 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
330 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800331 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700332 // Note that the priority queue returns the largest element, so operator()
333 // should return true if lhs is less than rhs.
334 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700335 }
336};
Andreas Gampec55bb392018-09-21 00:02:02 +0000337using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700338
339// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800340static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700341 DCHECK(gaps != nullptr);
342
343 uint32_t current_offset = gap_start;
344 while (current_offset != gap_end) {
345 size_t remaining = gap_end - current_offset;
346 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
347 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
348 current_offset += sizeof(uint32_t);
349 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
350 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
351 current_offset += sizeof(uint16_t);
352 } else {
353 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
354 current_offset += sizeof(uint8_t);
355 }
356 DCHECK_LE(current_offset, gap_end) << "Overran gap";
357 }
358}
359// Shuffle fields forward, making use of gaps whenever possible.
360template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000361static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700362 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700363 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700364 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700365 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700366 DCHECK(current_field_idx != nullptr);
367 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700368 DCHECK(gaps != nullptr);
369 DCHECK(field_offset != nullptr);
370
371 DCHECK(IsPowerOfTwo(n));
372 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700373 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700374 Primitive::Type type = field->GetTypeAsPrimitiveType();
375 if (Primitive::ComponentSize(type) < n) {
376 break;
377 }
378 if (!IsAligned<n>(field_offset->Uint32Value())) {
379 MemberOffset old_offset = *field_offset;
380 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
381 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
382 }
David Sehr709b0702016-10-13 09:12:37 -0700383 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700384 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700385 if (!gaps->empty() && gaps->top().size >= n) {
386 FieldGap gap = gaps->top();
387 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100388 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700389 field->SetOffset(MemberOffset(gap.start_offset));
390 if (gap.size > n) {
391 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
392 }
393 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100394 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700395 field->SetOffset(*field_offset);
396 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
397 }
398 ++(*current_field_idx);
399 }
400}
401
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800402ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700403 : boot_class_table_(new ClassTable()),
404 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800405 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800406 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700407 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000408 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700409 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800410 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800411 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100412 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800413 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700414 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700415 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
416 // For CHA disabled during Aot, see b/34193647.
417
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700418 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700419 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
420 "Array cache size wrong.");
421 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700422}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700423
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800424void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700425 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800426 if (c2 == nullptr) {
427 LOG(FATAL) << "Could not find class " << descriptor;
428 UNREACHABLE();
429 }
430 if (c1.Get() != c2) {
431 std::ostringstream os1, os2;
432 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
433 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
434 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
435 << ". This is most likely the result of a broken build. Make sure that "
436 << "libcore and art projects match.\n\n"
437 << os1.str() << "\n\n" << os2.str();
438 UNREACHABLE();
439 }
440}
441
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800442bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
443 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800444 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700445
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 Thread* const self = Thread::Current();
447 Runtime* const runtime = Runtime::Current();
448 gc::Heap* const heap = runtime->GetHeap();
449
Jeff Haodcdc85b2015-12-04 14:06:18 -0800450 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700451 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700452
Mathieu Chartiere401d142015-04-22 13:56:20 -0700453 // Use the pointer size from the runtime since we are probably creating the image.
454 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
455
Elliott Hughes30646832011-10-13 16:59:46 -0700456 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700457 // 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 -0800458 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700459 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700460 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700461 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
462 // the incorrect result when comparing to-space vs from-space.
Vladimir Markobcf17522018-06-01 13:14:32 +0100463 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(MakeObjPtr(
464 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800465 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100466 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700467 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700468 if (kUseBakerReadBarrier) {
469 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800470 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700471 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700472 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800473 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700474 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700475
Elliott Hughes418d20f2011-09-22 14:00:39 -0700476 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700477 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700478 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700479 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700480 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700481
Ian Rogers23435d02012-09-24 11:23:12 -0700482 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700483 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700484 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800485 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700487 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000488 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700489
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700490 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800491 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
492 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
493 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
494 java_lang_Object.Get(),
495 java_lang_Object->GetObjectSize(),
496 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700497
Igor Murashkin86083f72017-10-27 10:59:04 -0700498 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000499 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700500 // It might seem the lock here is unnecessary, however all the SubtypeCheck
501 // functions are annotated to require locks all the way down.
502 //
503 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
504 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000505 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
506 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700507 }
508
Ian Rogers23435d02012-09-24 11:23:12 -0700509 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700510 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700511 AllocClass(self, java_lang_Class.Get(),
512 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700513 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700514
Roland Levillain0e840272018-08-23 19:55:30 +0100515 // Setup java.lang.String.
516 //
517 // We make this class non-movable for the unlikely case where it were to be
518 // moved by a sticky-bit (minor) collection when using the Generational
519 // Concurrent Copying (CC) collector, potentially creating a stale reference
520 // in the `klass_` field of one of its instances allocated in the Large-Object
521 // Space (LOS) -- see the comment about the dirty card scanning logic in
522 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700523 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700524 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100525 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700526 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000527 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400528
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700529 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700530 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700531 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700532 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000533 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700534
Ian Rogers23435d02012-09-24 11:23:12 -0700535 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700536 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100537 mirror::ObjectArray<mirror::Class>::Alloc(self,
538 object_array_class.Get(),
539 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700540 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100541 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
542 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
543 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
544 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100545 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
546 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547
Mathieu Chartier6beced42016-11-15 15:51:31 -0800548 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
549 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
550
Vladimir Marko02610552018-06-04 14:38:00 +0100551 // Create array interface entries to populate once we can load system classes.
552 object_array_class->SetIfTable(AllocIfTable(self, 2));
553 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
554
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100556 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
557 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100558 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100559 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
560 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
561 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
562 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
563 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
564 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700565
Vladimir Markoacb906d2018-05-30 10:23:49 +0100566 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700567 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100568 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100569 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100570 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700571
Vladimir Markoacb906d2018-05-30 10:23:49 +0100572 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700573 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100574 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100575 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100576 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700577
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700578 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700579
Ian Rogers52813c92012-10-11 11:50:38 -0700580 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700581 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700582 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100583 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100584 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700585 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000586 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587
Alex Lightd6251582016-10-31 11:12:30 -0700588
589 // Setup dalvik.system.ClassExt
590 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
591 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100592 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000593 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700594
Mathieu Chartier66f19252012-09-18 08:57:04 -0700595 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700596 Handle<mirror::Class> object_array_string(hs.NewHandle(
597 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700598 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700599 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100600 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700601
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000602 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700603 // Create runtime resolution and imt conflict methods.
604 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000605 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
606 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700607
Ian Rogers23435d02012-09-24 11:23:12 -0700608 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
609 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
610 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800611 if (boot_class_path.empty()) {
612 *error_msg = "Boot classpath is empty.";
613 return false;
614 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800615 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800616 if (dex_file.get() == nullptr) {
617 *error_msg = "Null dex file.";
618 return false;
619 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700620 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800621 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700622 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700623
624 // now we can use FindSystemClass
625
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700626 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
627 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700628 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800629 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700630 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700631 quick_resolution_trampoline_ = GetQuickResolutionStub();
632 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
633 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700634 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700635
Alex Lightd6251582016-10-31 11:12:30 -0700636 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000637 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800638 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700639 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000640 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800641 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000642 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800643 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700644 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000645 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700646 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
647 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648
Ian Rogers23435d02012-09-24 11:23:12 -0700649 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100650 AllocAndSetPrimitiveArrayClassRoot(self,
651 java_lang_Class.Get(),
652 ClassRoot::kBooleanArrayClass,
653 ClassRoot::kPrimitiveBoolean,
654 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700655
Roland Levillain0e840272018-08-23 19:55:30 +0100656 AllocAndSetPrimitiveArrayClassRoot(
657 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700658
Roland Levillain0e840272018-08-23 19:55:30 +0100659 AllocAndSetPrimitiveArrayClassRoot(
660 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661
Roland Levillain0e840272018-08-23 19:55:30 +0100662 AllocAndSetPrimitiveArrayClassRoot(
663 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700664
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800665 CheckSystemClass(self, int_array_class, "[I");
666 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667
Roland Levillain0e840272018-08-23 19:55:30 +0100668 AllocAndSetPrimitiveArrayClassRoot(
669 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700670
Roland Levillain0e840272018-08-23 19:55:30 +0100671 AllocAndSetPrimitiveArrayClassRoot(
672 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700673
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800674 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
675 // in class_table_.
676 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700677
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800678 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
679 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700680
Ian Rogers23435d02012-09-24 11:23:12 -0700681 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700682 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800683 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700684 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800685 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700686 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
687 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100688 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
689 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700690
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700691 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
692 // suspension.
693 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000694 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700695 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000696 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700697 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000698 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700699 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000700 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700701
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700702 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100703 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700704
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800705 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700706
Ian Rogers23435d02012-09-24 11:23:12 -0700707 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100708 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
709 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700710
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700711 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100712 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700713 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100714 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700715
716 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700717 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
718 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100719 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700720
721 // Create java.lang.reflect.Constructor.class root and array root.
722 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
723 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100724 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700725 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
726 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100727 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700728
729 // Create java.lang.reflect.Method.class root and array root.
730 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
731 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100732 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700733 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
734 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100735 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700736
Orion Hodson005ac512017-10-24 15:43:43 +0100737 // Create java.lang.invoke.CallSite.class root
738 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
739 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100740 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100741
Narayan Kamathafa48272016-08-03 12:46:58 +0100742 // Create java.lang.invoke.MethodType.class root
743 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
744 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100745 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100746
747 // Create java.lang.invoke.MethodHandleImpl.class root
748 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
749 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100750 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100751 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100752
Orion Hodsonc069a302017-01-18 09:23:12 +0000753 // Create java.lang.invoke.MethodHandles.Lookup.class root
754 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
755 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100756 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000757
Orion Hodson005ac512017-10-24 15:43:43 +0100758 // Create java.lang.invoke.VarHandle.class root
759 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000760 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100761 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100762
763 // Create java.lang.invoke.FieldVarHandle.class root
764 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
765 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100766 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100767
768 // Create java.lang.invoke.ArrayElementVarHandle.class root
769 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
770 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100771 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100772
773 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
774 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
775 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100776 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100777
778 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
779 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
780 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100781 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000782
Narayan Kamath000e1882016-10-24 17:14:25 +0100783 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
784 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100785 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100786
Brian Carlstrom1f870082011-08-23 16:02:11 -0700787 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700788 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000789 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800790 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700791 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700792 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
793 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700794 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700795 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700796 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700797 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700798 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700799 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700800 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700801 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700802 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700803 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700804 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700805 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700806
Ian Rogers23435d02012-09-24 11:23:12 -0700807 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700808 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700809 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700810 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100811 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700812
jeffhao8cd6dda2012-02-22 10:15:34 -0800813 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700814 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100815 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100816 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700817 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100818 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
819 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
820 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700821 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000822 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
823 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700824
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700825 // Create conflict tables that depend on the class linker.
826 runtime->FixupConflictTables();
827
Ian Rogers98379392014-02-24 16:53:16 -0800828 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700829
Brian Carlstroma004aa92012-02-08 18:05:09 -0800830 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800831
832 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700833}
834
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700835static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
836 REQUIRES_SHARED(Locks::mutator_lock_) {
837 // Find String.<init> -> StringFactory bindings.
838 ObjPtr<mirror::Class> string_factory_class =
839 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
840 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100841 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700842 WellKnownClasses::InitStringInit(string_class, string_factory_class);
843 // Update the primordial thread.
844 self->InitStringEntryPoints();
845}
846
Ian Rogers98379392014-02-24 16:53:16 -0800847void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800848 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700849
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700850 CreateStringInitBindings(self, this);
851
Brian Carlstrom16192862011-09-12 17:50:06 -0700852 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700853 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700854 // as the types of the field can't be resolved prior to the runtime being
855 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700856 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100857 Handle<mirror::Class> java_lang_ref_Reference =
858 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700859 Handle<mirror::Class> java_lang_ref_FinalizerReference =
860 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800861
Mathieu Chartierc7853442015-03-27 14:35:38 -0700862 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700863 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
864 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700865
Mathieu Chartierc7853442015-03-27 14:35:38 -0700866 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700867 CHECK_STREQ(queue->GetName(), "queue");
868 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700869
Mathieu Chartierc7853442015-03-27 14:35:38 -0700870 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700871 CHECK_STREQ(queueNext->GetName(), "queueNext");
872 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700873
Mathieu Chartierc7853442015-03-27 14:35:38 -0700874 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700875 CHECK_STREQ(referent->GetName(), "referent");
876 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700877
Mathieu Chartierc7853442015-03-27 14:35:38 -0700878 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700879 CHECK_STREQ(zombie->GetName(), "zombie");
880 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700881
Brian Carlstroma663ea52011-08-19 23:33:41 -0700882 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100883 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700884 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700885 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700886 CHECK(klass != nullptr);
887 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700888 // note SetClassRoot does additional validation.
889 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700890 }
891
Vladimir Marko02610552018-06-04 14:38:00 +0100892 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700893
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700894 // disable the slow paths in FindClass and CreatePrimitiveClass now
895 // that Object, Class, and Object[] are setup
896 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700897
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700898 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
899 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
900 // ensure that the class will be initialized.
901 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
902 verifier::MethodVerifier::Init(); // Need to prepare the verifier.
903
904 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
905 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
906 // Strange, but don't crash.
907 LOG(WARNING) << "Could not prepare StackOverflowError.";
908 self->ClearException();
909 }
910 }
911
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800912 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700913}
914
Vladimir Markodcfcce42018-06-27 10:00:28 +0000915void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100916 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
917 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700918 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700919 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100920 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700921 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000923 } else {
924 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700925 }
926 }
927}
928
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200929// Set image methods' entry point to interpreter.
930class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
931 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700932 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200933 : image_pointer_size_(image_pointer_size) {}
934
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100935 void Visit(ArtMethod* method) override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200936 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
937 CHECK(method->GetDeclaringClass() != nullptr);
938 }
939 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
940 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
941 image_pointer_size_);
942 }
943 }
944
945 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700946 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200947
948 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
949};
950
Jeff Haodcdc85b2015-12-04 14:06:18 -0800951struct TrampolineCheckData {
952 const void* quick_resolution_trampoline;
953 const void* quick_imt_conflict_trampoline;
954 const void* quick_generic_jni_trampoline;
955 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700956 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800957 ArtMethod* m;
958 bool error;
959};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800960
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800961bool ClassLinker::InitFromBootImage(std::string* error_msg) {
962 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700963 CHECK(!init_done_);
964
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700965 Runtime* const runtime = Runtime::Current();
966 Thread* const self = Thread::Current();
967 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800968 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
969 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700970 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
971 if (!ValidPointerSize(pointer_size_unchecked)) {
972 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800973 return false;
974 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700975 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800976 if (!runtime->IsAotCompiler()) {
977 // Only the Aot compiler supports having an image with a different pointer size than the
978 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
979 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700980 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800981 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700982 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800983 sizeof(void*));
984 return false;
985 }
986 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800987 std::vector<const OatFile*> oat_files =
988 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
989 DCHECK(!oat_files.empty());
990 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800991 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
992 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
993 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
994 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
995 if (kIsDebugBuild) {
996 // Check that the other images use the same trampoline.
997 for (size_t i = 1; i < oat_files.size(); ++i) {
998 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
999 const void* ith_quick_resolution_trampoline =
1000 ith_oat_header.GetQuickResolutionTrampoline();
1001 const void* ith_quick_imt_conflict_trampoline =
1002 ith_oat_header.GetQuickImtConflictTrampoline();
1003 const void* ith_quick_generic_jni_trampoline =
1004 ith_oat_header.GetQuickGenericJniTrampoline();
1005 const void* ith_quick_to_interpreter_bridge_trampoline =
1006 ith_oat_header.GetQuickToInterpreterBridge();
1007 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1008 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1009 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1010 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1011 // Make sure that all methods in this image do not contain those trampolines as
1012 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1013 TrampolineCheckData data;
1014 data.error = false;
1015 data.pointer_size = GetImagePointerSize();
1016 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1017 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1018 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1019 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1020 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001021 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1022 if (obj->IsClass()) {
1023 ObjPtr<mirror::Class> klass = obj->AsClass();
1024 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1025 const void* entrypoint =
1026 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1027 if (entrypoint == data.quick_resolution_trampoline ||
1028 entrypoint == data.quick_imt_conflict_trampoline ||
1029 entrypoint == data.quick_generic_jni_trampoline ||
1030 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1031 data.m = &m;
1032 data.error = true;
1033 return;
1034 }
1035 }
1036 }
1037 };
1038 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001039 if (data.error) {
1040 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001041 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001042 *error_msg = "Found an ArtMethod with a bad entrypoint";
1043 return false;
1044 }
1045 }
1046 }
1047 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001048
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001049 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001050 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1051 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001052 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001053
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001054 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001055 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001056 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1057 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001058 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1059 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001060
Vladimir Marko4433c432018-12-04 14:57:47 +00001061 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1062 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001063 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001064 // Boot class loader, use a null handle.
1065 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001066 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001067 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001068 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001069 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001070 /*out*/&dex_files,
1071 error_msg)) {
1072 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001073 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001074 // Append opened dex files at the end.
1075 boot_dex_files_.insert(boot_dex_files_.end(),
1076 std::make_move_iterator(dex_files.begin()),
1077 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001078 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001079 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1080 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1081 }
Ian Rogers98379392014-02-24 16:53:16 -08001082 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001083
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001084 VLOG(startup) << __FUNCTION__ << " exiting";
1085 return true;
1086}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001087
Vladimir Marko4433c432018-12-04 14:57:47 +00001088void ClassLinker::AddExtraBootDexFiles(
1089 Thread* self,
1090 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1091 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1092 AppendToBootClassPath(self, *dex_file);
1093 boot_dex_files_.push_back(std::move(dex_file));
1094 }
1095}
1096
Jeff Hao5872d7c2016-04-27 11:07:41 -07001097bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001098 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001099 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001100 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1101 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001102}
1103
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001104static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1105 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001106 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001107 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001108 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001109 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001110 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001111 DCHECK(dex_file_field != nullptr);
1112 DCHECK(dex_file_name_field != nullptr);
1113 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001114 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001115 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001117 // Null dex file means it was probably a jar with no dex files, return a null string.
1118 *out_name = nullptr;
1119 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001121 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001123 *out_name = name_object->AsString();
1124 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001126 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001127}
1128
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001129static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1130 ObjPtr<mirror::ClassLoader> class_loader,
1131 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1132 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001133 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001134 StackHandleScope<1> hs(soa.Self());
1135 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001136 // Get element names. Sets error to true on failure.
1137 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1138 REQUIRES_SHARED(Locks::mutator_lock_) {
1139 if (element == nullptr) {
1140 *error_msg = "Null dex element";
1141 *error = true; // Null element is a critical error.
1142 return false; // Had an error, stop the visit.
1143 }
1144 ObjPtr<mirror::String> name;
1145 if (!GetDexPathListElementName(element, &name)) {
1146 *error_msg = "Invalid dex path list element";
1147 *error = true; // Invalid element, make it a critical error.
1148 return false; // Stop the visit.
1149 }
1150 if (name != nullptr) {
1151 dex_files->push_front(name);
1152 }
1153 return true; // Continue with the next Element.
1154 };
1155 bool error = VisitClassLoaderDexElements(soa,
1156 handle,
1157 add_element_names,
1158 /*defaultReturn=*/ false);
1159 return !error;
1160}
1161
1162static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1163 ObjPtr<mirror::ClassLoader> image_class_loader,
1164 ObjPtr<mirror::ClassLoader> class_loader,
1165 std::string* error_msg)
1166 REQUIRES_SHARED(Locks::mutator_lock_) {
1167 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1168 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1169 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001170 return false;
1171 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001172 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1173 *error_msg = "Hierarchies don't match";
1174 return false;
1175 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1176 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1177 image_class_loader->PrettyTypeOf().c_str(),
1178 class_loader->PrettyTypeOf().c_str());
1179 return false;
1180 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1181 class_loader->GetClass()) {
1182 *error_msg = StringPrintf("Unknown class loader type %s",
1183 class_loader->PrettyTypeOf().c_str());
1184 // Unsupported class loader.
1185 return false;
1186 }
1187 return true;
1188}
1189
1190static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1191 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1192 std::string* error_msg)
1193 REQUIRES_SHARED(Locks::mutator_lock_) {
1194 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1195 std::equal(image_dex_files.begin(),
1196 image_dex_files.end(),
1197 loader_dex_files.begin(),
1198 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1199 REQUIRES_SHARED(Locks::mutator_lock_) {
1200 return lhs->Equals(rhs);
1201 });
1202 if (!equal) {
1203 VLOG(image) << "Image dex files " << image_dex_files.size();
1204 for (ObjPtr<mirror::String> name : image_dex_files) {
1205 VLOG(image) << name->ToModifiedUtf8();
1206 }
1207 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1208 for (ObjPtr<mirror::String> name : loader_dex_files) {
1209 VLOG(image) << name->ToModifiedUtf8();
1210 }
1211 *error_msg = "Mismatch in dex files";
1212 }
1213 return equal;
1214}
1215
1216static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1217 ObjPtr<mirror::ClassLoader> image_class_loader,
1218 ObjPtr<mirror::ClassLoader> class_loader,
1219 bool check_dex_file_names,
1220 std::string* error_msg)
1221 REQUIRES_SHARED(Locks::mutator_lock_) {
1222 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1223 return false;
1224 }
1225
1226 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1227 // No need to check further.
1228 return true;
1229 }
1230
1231 if (check_dex_file_names) {
1232 std::list<ObjPtr<mirror::String>> image_dex_files;
1233 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001234 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001235 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001236
1237 std::list<ObjPtr<mirror::String>> loader_dex_files;
1238 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1239 return false;
1240 }
1241
1242 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1243 return false;
1244 }
1245 }
1246
1247 ArtField* field =
1248 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1249 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1250 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1251 if (shared_libraries_image_loader == nullptr) {
1252 if (shared_libraries_loader != nullptr) {
1253 *error_msg = "Mismatch in shared libraries";
1254 return false;
1255 }
1256 } else if (shared_libraries_loader == nullptr) {
1257 *error_msg = "Mismatch in shared libraries";
1258 return false;
1259 } else {
1260 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1261 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1262 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1263 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1264 if (array1->GetLength() != array2->GetLength()) {
1265 *error_msg = "Mismatch in number of shared libraries";
1266 return false;
1267 }
1268
1269 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1270 // Do a full comparison of the class loaders, including comparing their dex files.
1271 if (!CompareClassLoaders(soa,
1272 array1->Get(i),
1273 array2->Get(i),
1274 /*check_dex_file_names=*/ true,
1275 error_msg)) {
1276 return false;
1277 }
1278 }
1279 }
1280
1281 // Do a full comparison of the class loaders, including comparing their dex files.
1282 if (!CompareClassLoaders(soa,
1283 image_class_loader->GetParent(),
1284 class_loader->GetParent(),
1285 /*check_dex_file_names=*/ true,
1286 error_msg)) {
1287 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001288 }
1289 return true;
1290}
1291
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001292class CHAOnDeleteUpdateClassVisitor {
1293 public:
1294 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1295 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1296 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1297 self_(Thread::Current()) {}
1298
1299 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1300 // This class is going to be unloaded. Tell CHA about it.
1301 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1302 return true;
1303 }
1304 private:
1305 const LinearAlloc* allocator_;
1306 const ClassHierarchyAnalysis* cha_;
1307 const PointerSize pointer_size_;
1308 const Thread* self_;
1309};
1310
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001311class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1312 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001313 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001314 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1315
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001316 void Visit(ArtMethod* method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001317 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001318 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001319 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001320 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001321 }
1322 }
1323
1324 private:
1325 gc::accounting::HeapBitmap* const live_bitmap_;
1326};
1327
Chris Wailes0c61be42018-09-26 17:27:34 -07001328/*
1329 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001330 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001331 */
1332class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001333 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001334 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001335 space_(space),
1336 intern_table_(*Runtime::Current()->GetInternTable()) {}
1337
Chris Wailes0c61be42018-09-26 17:27:34 -07001338 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001339 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001340 if (referred_obj != nullptr &&
1341 space_.HasAddress(referred_obj.Ptr()) &&
1342 referred_obj->IsString()) {
1343 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001344
1345 if (kIsDebugBuild) {
1346 // Saved to temporary variables to aid in debugging.
1347 ObjPtr<mirror::String> strong_lookup_result =
1348 intern_table_.LookupStrong(Thread::Current(), referred_str);
1349 ObjPtr<mirror::String> weak_lookup_result =
1350 intern_table_.LookupWeak(Thread::Current(), referred_str);
1351
1352 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1353 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001354 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001355 }
1356
Chris Wailes0c61be42018-09-26 17:27:34 -07001357 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001358 mirror::CompressedReference<mirror::Object>* root) const
1359 REQUIRES_SHARED(Locks::mutator_lock_) {
1360 if (!root->IsNull()) {
1361 VisitRoot(root);
1362 }
1363 }
1364
Chris Wailes0c61be42018-09-26 17:27:34 -07001365 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001366 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001367 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001368 }
1369
1370 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001371 void operator()(ObjPtr<mirror::Object> obj,
1372 MemberOffset offset,
1373 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001374 REQUIRES_SHARED(Locks::mutator_lock_) {
1375 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1376 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1377 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1378 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001379 ObjPtr<mirror::Object> referred_obj =
1380 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1381
1382 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001383 }
1384 }
1385
1386 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1387 ObjPtr<mirror::Reference> ref) const
1388 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001389 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001390 }
1391
Chris Wailes0c61be42018-09-26 17:27:34 -07001392 const gc::space::ImageSpace& space_;
1393 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001394};
1395
Chris Wailes0c61be42018-09-26 17:27:34 -07001396/*
1397 * This function verifies that string references in the AppImage have been
1398 * properly interned. To be considered properly interned a reference must
1399 * point to the same version of the string that the intern table does.
1400 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001401void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001402 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1403 const ImageHeader& image_header = space.GetImageHeader();
1404 const uint8_t* target_base = space.GetMemMap()->Begin();
1405 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001406
1407 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1408 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001409
1410 VerifyStringInterningVisitor visitor(space);
1411 bitmap->VisitMarkedRange(objects_begin,
1412 objects_end,
1413 [&space, &visitor](mirror::Object* obj)
1414 REQUIRES_SHARED(Locks::mutator_lock_) {
1415 if (space.HasAddress(obj)) {
1416 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001417 obj->VisitReferences</* kVisitNativeRoots= */ true,
1418 kVerifyNone,
1419 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001420 } else {
1421 // Don't visit native roots for non-dex-cache as they can't contain
1422 // native references to strings. This is verified during compilation
1423 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001424 obj->VisitReferences</* kVisitNativeRoots= */ false,
1425 kVerifyNone,
1426 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001427 }
1428 }
1429 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001430}
1431
Andreas Gampe2af99022017-04-25 08:32:59 -07001432// new_class_set is the set of classes that were read from the class table section in the image.
1433// If there was no class table section, it is null.
1434// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001435class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001436 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001437 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001438 ClassLinker* class_linker,
1439 gc::space::ImageSpace* space,
1440 Handle<mirror::ClassLoader> class_loader,
1441 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001442 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001443 REQUIRES(!Locks::dex_lock_)
1444 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001445
Chris Wailesfbeef462018-10-19 14:16:35 -07001446 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001447 REQUIRES_SHARED(Locks::mutator_lock_);
1448
1449 static void UpdateInternStrings(
1450 gc::space::ImageSpace* space,
1451 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1452 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001453};
1454
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001455void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001456 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001457 gc::space::ImageSpace* space,
1458 Handle<mirror::ClassLoader> class_loader,
1459 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001460 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001461 REQUIRES(!Locks::dex_lock_)
1462 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001463 ScopedTrace app_image_timing("AppImage:Updating");
1464
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001465 Thread* const self = Thread::Current();
1466 gc::Heap* const heap = Runtime::Current()->GetHeap();
1467 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001468 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001469 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001470 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001471 const size_t num_dex_caches = dex_caches->GetLength();
1472 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001473 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001474 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001475 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001476 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001477 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1478 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001479 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001480
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001481 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001482 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001483 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001484 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001485 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001486 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001487 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001488
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001489 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001490 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001491 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001492 DCHECK(it != new_class_set->end());
1493 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001494 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001495
Vladimir Marko1a1de672016-10-13 12:53:15 +01001496 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001497 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001498 DCHECK(it2 != new_class_set->end());
1499 DCHECK_EQ(it2->Read(), super_class);
1500 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001501
Vladimir Marko1a1de672016-10-13 12:53:15 +01001502 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1503 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001504 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1505 if (!class_linker->IsQuickResolutionStub(code) &&
1506 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001507 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001508 !m.IsNative()) {
1509 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001510 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001511 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001512
Vladimir Marko1a1de672016-10-13 12:53:15 +01001513 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1514 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001515 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1516 if (!class_linker->IsQuickResolutionStub(code) &&
1517 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001518 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001519 !m.IsNative()) {
1520 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001521 }
1522 }
1523 }
1524 }
1525 }
1526 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001527 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001528
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001529 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001530 HandleAppImageStrings(space);
1531
1532 if (kIsDebugBuild) {
1533 VerifyStringInterning(*space);
1534 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001535 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001536
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001537 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001538 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001539 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1540 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001541 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001542 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001543}
1544
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001545void AppImageLoadingHelper::UpdateInternStrings(
1546 gc::space::ImageSpace* space,
1547 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1548 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001549 const ImageSection& sro_section =
1550 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1551 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001552
1553 VLOG(image)
1554 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1555 << num_string_offsets;
1556
Chris Wailesfbeef462018-10-19 14:16:35 -07001557 const auto* sro_base =
1558 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001559
1560 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001561 uint32_t base_offset = sro_base[offset_index].first;
1562
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001563 if (HasDexCacheStringNativeRefTag(base_offset)) {
1564 base_offset = ClearDexCacheNativeRefTags(base_offset);
1565 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001566
1567 ObjPtr<mirror::DexCache> dex_cache =
1568 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1569 uint32_t string_index = sro_base[offset_index].second;
1570
1571 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1572 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001573 DCHECK(referred_string != nullptr);
1574
Chris Wailesfbeef462018-10-19 14:16:35 -07001575 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001576 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001577 // This doesn't use SetResolvedString to maintain consistency with how
1578 // we load the string. The index from the source string must be
1579 // re-used due to the circular nature of the cache. Because we are not
1580 // using a helper function we need to mark the GC card manually.
1581 WriteBarrier::ForEveryFieldWrite(dex_cache);
1582 dex_cache->GetStrings()[string_index].store(
1583 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001584 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001585 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1586 base_offset = ClearDexCacheNativeRefTags(base_offset);
1587 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001588
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001589 ObjPtr<mirror::DexCache> dex_cache =
1590 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1591 uint32_t string_index = sro_base[offset_index].second;
1592
1593 ObjPtr<mirror::String> referred_string =
1594 dex_cache->GetPreResolvedStrings()[string_index].Read();
1595 DCHECK(referred_string != nullptr);
1596
1597 auto it = intern_remap.find(referred_string.Ptr());
1598 if (it != intern_remap.end()) {
1599 // Because we are not using a helper function we need to mark the GC card manually.
1600 WriteBarrier::ForEveryFieldWrite(dex_cache);
1601 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1602 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001603 } else {
1604 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001605 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001606 DCHECK_ALIGNED(raw_member_offset, 2);
1607
1608 ObjPtr<mirror::Object> obj_ptr =
1609 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1610 MemberOffset member_offset(raw_member_offset);
1611 ObjPtr<mirror::String> referred_string =
1612 obj_ptr->GetFieldObject<mirror::String,
1613 kVerifyNone,
1614 kWithoutReadBarrier,
1615 /* kIsVolatile= */ false>(member_offset);
1616 DCHECK(referred_string != nullptr);
1617
1618 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001619 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001620 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1621 /* kCheckTransaction= */ false,
1622 kVerifyNone,
1623 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001624 }
1625 }
1626 }
1627}
1628
Chris Wailesfbeef462018-10-19 14:16:35 -07001629void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001630 // Iterate over the string reference offsets stored in the image and intern
1631 // the strings they point to.
1632 ScopedTrace timing("AppImage:InternString");
1633
Chris Wailesfbeef462018-10-19 14:16:35 -07001634 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001635
1636 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1637 // for faster lookup.
1638 // TODO: Optimize with a bitmap or bloom filter
1639 SafeMap<mirror::String*, mirror::String*> intern_remap;
1640 intern_table->AddImageStringsToTable(space, [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001641 REQUIRES_SHARED(Locks::mutator_lock_)
1642 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001643 const size_t non_boot_image_strings = intern_table->CountInterns(
1644 /*visit_boot_images=*/false,
1645 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001646 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001647 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1648 // Visit the smaller of the two sets to compute the intersection.
1649 if (interns.size() < non_boot_image_strings) {
1650 for (auto it = interns.begin(); it != interns.end(); ) {
1651 ObjPtr<mirror::String> string = it->Read();
1652 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1653 if (existing == nullptr) {
1654 existing = intern_table->LookupStrongLocked(string);
1655 }
1656 if (existing != nullptr) {
1657 intern_remap.Put(string.Ptr(), existing.Ptr());
1658 it = interns.erase(it);
1659 } else {
1660 ++it;
1661 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001662 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001663 } else {
1664 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1665 REQUIRES_SHARED(Locks::mutator_lock_)
1666 REQUIRES(Locks::intern_table_lock_) {
1667 auto it = interns.find(root);
1668 if (it != interns.end()) {
1669 ObjPtr<mirror::String> existing = root.Read();
1670 intern_remap.Put(it->Read(), existing.Ptr());
1671 it = interns.erase(it);
1672 }
1673 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1674 }
1675 // Sanity check to ensure correctness.
1676 if (kIsDebugBuild) {
1677 for (GcRoot<mirror::String>& root : interns) {
1678 ObjPtr<mirror::String> string = root.Read();
1679 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1680 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001681 }
1682 }
1683 });
1684
Chris Wailesfbeef462018-10-19 14:16:35 -07001685 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001686
1687 // For debug builds, always run the code below to get coverage.
1688 if (kIsDebugBuild || !intern_remap.empty()) {
1689 // Slow path case is when there are conflicting intern strings to fix up.
1690 UpdateInternStrings(space, intern_remap);
1691 }
1692}
1693
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001694static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1695 const char* location,
1696 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001697 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001698 DCHECK(error_msg != nullptr);
1699 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001700 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001701 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001702 return std::unique_ptr<const DexFile>();
1703 }
1704 std::string inner_error_msg;
1705 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1706 if (dex_file == nullptr) {
1707 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1708 location,
1709 oat_file->GetLocation().c_str(),
1710 inner_error_msg.c_str());
1711 return std::unique_ptr<const DexFile>();
1712 }
1713
1714 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1715 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1716 location,
1717 dex_file->GetLocationChecksum(),
1718 oat_dex_file->GetDexFileLocationChecksum());
1719 return std::unique_ptr<const DexFile>();
1720 }
1721 return dex_file;
1722}
1723
1724bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1725 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1726 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001727 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001728 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001729 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001730 DCHECK(dex_caches_object != nullptr);
1731 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1732 dex_caches_object->AsObjectArray<mirror::DexCache>();
1733 const OatFile* oat_file = space->GetOatFile();
1734 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001735 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001736 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1737 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1738 dex_file_location.c_str(),
1739 error_msg);
1740 if (dex_file == nullptr) {
1741 return false;
1742 }
1743 dex_cache->SetDexFile(dex_file.get());
1744 out_dex_files->push_back(std::move(dex_file));
1745 }
1746 return true;
1747}
1748
Andreas Gampe0793bec2016-12-01 11:37:33 -08001749// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1750// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001751class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001752 public:
1753 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1754 REQUIRES_SHARED(Locks::mutator_lock_) {
1755 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001756 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1757 DCHECK(obj != nullptr);
1758 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1759 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1760 if (obj->IsClass()) {
1761 auto klass = obj->AsClass();
1762 for (ArtField& field : klass->GetIFields()) {
1763 CHECK_EQ(field.GetDeclaringClass(), klass);
1764 }
1765 for (ArtField& field : klass->GetSFields()) {
1766 CHECK_EQ(field.GetDeclaringClass(), klass);
1767 }
1768 const auto pointer_size = isc.pointer_size_;
1769 for (auto& m : klass->GetMethods(pointer_size)) {
1770 isc.SanityCheckArtMethod(&m, klass);
1771 }
1772 auto* vtable = klass->GetVTable();
1773 if (vtable != nullptr) {
1774 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1775 }
1776 if (klass->ShouldHaveImt()) {
1777 ImTable* imt = klass->GetImt(pointer_size);
1778 for (size_t i = 0; i < ImTable::kSize; ++i) {
1779 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1780 }
1781 }
1782 if (klass->ShouldHaveEmbeddedVTable()) {
1783 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1784 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1785 }
1786 }
1787 mirror::IfTable* iftable = klass->GetIfTable();
1788 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1789 if (iftable->GetMethodArrayCount(i) > 0) {
1790 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1791 }
1792 }
1793 }
1794 };
1795 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001796 }
1797
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001798 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1799 ClassLinker* class_linker,
1800 mirror::MethodDexCacheType* arr,
1801 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001802 REQUIRES_SHARED(Locks::mutator_lock_) {
1803 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001804 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001805 }
1806
Andreas Gampe0793bec2016-12-01 11:37:33 -08001807 private:
1808 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1809 : spaces_(heap->GetBootImageSpaces()),
1810 pointer_size_(class_linker->GetImagePointerSize()) {
1811 space_begin_.reserve(spaces_.size());
1812 method_sections_.reserve(spaces_.size());
1813 runtime_method_sections_.reserve(spaces_.size());
1814 for (gc::space::ImageSpace* space : spaces_) {
1815 space_begin_.push_back(space->Begin());
1816 auto& header = space->GetImageHeader();
1817 method_sections_.push_back(&header.GetMethodsSection());
1818 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1819 }
1820 }
1821
1822 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1823 REQUIRES_SHARED(Locks::mutator_lock_) {
1824 if (m->IsRuntimeMethod()) {
1825 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1826 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1827 } else if (m->IsCopied()) {
1828 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1829 } else if (expected_class != nullptr) {
1830 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1831 }
1832 if (!spaces_.empty()) {
1833 bool contains = false;
1834 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1835 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1836 contains = method_sections_[i]->Contains(offset) ||
1837 runtime_method_sections_[i]->Contains(offset);
1838 }
1839 CHECK(contains) << m << " not found";
1840 }
1841 }
1842
1843 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1844 ObjPtr<mirror::Class> expected_class)
1845 REQUIRES_SHARED(Locks::mutator_lock_) {
1846 CHECK(arr != nullptr);
1847 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1848 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1849 // expected_class == null means we are a dex cache.
1850 if (expected_class != nullptr) {
1851 CHECK(method != nullptr);
1852 }
1853 if (method != nullptr) {
1854 SanityCheckArtMethod(method, expected_class);
1855 }
1856 }
1857 }
1858
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001859 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001860 REQUIRES_SHARED(Locks::mutator_lock_) {
1861 CHECK_EQ(arr != nullptr, size != 0u);
1862 if (arr != nullptr) {
1863 bool contains = false;
1864 for (auto space : spaces_) {
1865 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001866 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001867 contains = true;
1868 break;
1869 }
1870 }
1871 CHECK(contains);
1872 }
1873 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001874 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1875 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001876 // expected_class == null means we are a dex cache.
1877 if (method != nullptr) {
1878 SanityCheckArtMethod(method, nullptr);
1879 }
1880 }
1881 }
1882
1883 const std::vector<gc::space::ImageSpace*>& spaces_;
1884 const PointerSize pointer_size_;
1885
1886 // Cached sections from the spaces.
1887 std::vector<const uint8_t*> space_begin_;
1888 std::vector<const ImageSection*> method_sections_;
1889 std::vector<const ImageSection*> runtime_method_sections_;
1890};
1891
Andreas Gampebe7af222017-07-25 09:57:28 -07001892static void VerifyAppImage(const ImageHeader& header,
1893 const Handle<mirror::ClassLoader>& class_loader,
1894 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1895 ClassTable* class_table, gc::space::ImageSpace* space)
1896 REQUIRES_SHARED(Locks::mutator_lock_) {
1897 {
1898 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1899 public:
1900 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1901
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001902 void Visit(ArtMethod* method) override
Andreas Gampebe7af222017-07-25 09:57:28 -07001903 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1904 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1905 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1906 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1907 }
1908 }
1909
1910 private:
1911 ClassTable* const table_;
1912 };
1913 VerifyClassInTableArtMethodVisitor visitor(class_table);
1914 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1915 }
1916 {
1917 // Verify that all direct interfaces of classes in the class table are also resolved.
1918 std::vector<ObjPtr<mirror::Class>> classes;
1919 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1920 REQUIRES_SHARED(Locks::mutator_lock_) {
1921 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1922 classes.push_back(klass);
1923 }
1924 return true;
1925 };
1926 class_table->Visit(verify_direct_interfaces_in_table);
1927 Thread* self = Thread::Current();
1928 for (ObjPtr<mirror::Class> klass : classes) {
1929 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1930 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1931 << klass->PrettyDescriptor() << " iface #" << i;
1932 }
1933 }
1934 }
1935 // Check that all non-primitive classes in dex caches are also in the class table.
1936 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1937 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1938 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1939 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1940 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1941 if (klass != nullptr && !klass->IsPrimitive()) {
1942 CHECK(class_table->Contains(klass))
1943 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1944 }
1945 }
1946 }
1947}
1948
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001949bool ClassLinker::AddImageSpace(
1950 gc::space::ImageSpace* space,
1951 Handle<mirror::ClassLoader> class_loader,
1952 jobjectArray dex_elements,
1953 const char* dex_location,
1954 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1955 std::string* error_msg) {
1956 DCHECK(out_dex_files != nullptr);
1957 DCHECK(error_msg != nullptr);
1958 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001959 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001960 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001961 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001962 DCHECK(dex_caches_object != nullptr);
1963 Runtime* const runtime = Runtime::Current();
1964 gc::Heap* const heap = runtime->GetHeap();
1965 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001966 // Check that the image is what we are expecting.
1967 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1968 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1969 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1970 image_pointer_size_);
1971 return false;
1972 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001973 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1974 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1975 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1976 expected_image_roots,
1977 header.GetImageRoots()->GetLength());
1978 return false;
1979 }
1980 StackHandleScope<3> hs(self);
1981 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1982 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1983 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1984 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001985 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001986 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1987 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001988 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001989 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001990 *error_msg = StringPrintf("Expected %d class roots but got %d",
1991 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001992 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001993 return false;
1994 }
1995 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001996 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1997 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1998 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001999 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2000 return false;
2001 }
2002 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002003 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002004 if (oat_file->GetOatHeader().GetDexFileCount() !=
2005 static_cast<uint32_t>(dex_caches->GetLength())) {
2006 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2007 "image";
2008 return false;
2009 }
2010
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002011 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002012 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2013 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002014 // TODO: Only store qualified paths.
2015 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002016 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002017 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2018 dex_file_location.c_str(),
2019 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002020 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002021 return false;
2022 }
2023
2024 if (app_image) {
2025 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2026 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002027 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002028 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002029 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002030 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002031 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002032 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002033 }
2034 }
2035 } else {
2036 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002037 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2038 this,
2039 dex_cache->GetResolvedMethods(),
2040 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002041 }
2042 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002043 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002044 }
2045 out_dex_files->push_back(std::move(dex_file));
2046 }
2047
2048 if (app_image) {
2049 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002050 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002051 // Check that the class loader resolves the same way as the ones in the image.
2052 // Image class loader [A][B][C][image dex files]
2053 // Class loader = [???][dex_elements][image dex files]
2054 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002055 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002056 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2057 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2058 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002059 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2060 *error_msg = "Unexpected BootClassLoader in app image";
2061 return false;
2062 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002063 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2064 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2065 // special case the comparison of dex files of the two class loaders, but then do full
2066 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002067 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002068 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002069 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2070 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2071 if (element != nullptr) {
2072 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002073 ObjPtr<mirror::String> name;
2074 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2075 loader_dex_file_names.push_back(name);
2076 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002077 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002078 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002079 std::string temp_error_msg;
2080 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2081 bool success = GetDexFileNames(
2082 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2083 if (success) {
2084 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2085 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2086 static_cast<size_t>(dex_caches->GetLength()));
2087 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2088 image_dex_file_names.resize(image_count);
2089 success = success && CompareDexFiles(image_dex_file_names,
2090 loader_dex_file_names,
2091 &temp_error_msg);
2092 success = success && CompareClassLoaders(soa,
2093 image_class_loader.Get(),
2094 class_loader.Get(),
2095 /*check_dex_file_names=*/ false,
2096 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002097 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002098 if (!success) {
2099 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2100 temp_error_msg.c_str());
2101 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002102 }
2103 }
2104
2105 if (kSanityCheckObjects) {
2106 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2107 auto* dex_cache = dex_caches->Get(i);
2108 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2109 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2110 if (field != nullptr) {
2111 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2112 }
2113 }
2114 }
2115 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002116 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002117 }
2118 }
2119
2120 // Set entry point to interpreter if in InterpretOnly mode.
2121 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002122 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07002123 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002124 }
2125
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002126 ClassTable* class_table = nullptr;
2127 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002128 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002129 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002130 }
2131 // If we have a class table section, read it and use it for verification in
2132 // UpdateAppImageClassLoadersAndDexCaches.
2133 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002134 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002135 const bool added_class_table = class_table_section.Size() > 0u;
2136 if (added_class_table) {
2137 const uint64_t start_time2 = NanoTime();
2138 size_t read_count = 0;
2139 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2140 /*make copy*/false,
2141 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002142 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002143 }
2144 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002145 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002146
2147 {
2148 ScopedTrace trace("AppImage:UpdateClassLoaders");
2149 // Update class loader and resolved strings. If added_class_table is false, the resolved
2150 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002151 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002152 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002153 // Note: We probably don't need the read barrier unless we copy the app image objects into
2154 // the region space.
2155 ObjPtr<mirror::Class> klass(root.Read());
2156 // Do not update class loader for boot image classes where the app image
2157 // class loader is only the initiating loader but not the defining loader.
2158 // Avoid read barrier since we are comparing against null.
2159 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2160 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2161 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002162 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002163 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002164
Vladimir Marko305c38b2018-02-14 11:50:07 +00002165 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002166 // Every class in the app image has initially SubtypeCheckInfo in the
2167 // Uninitialized state.
2168 //
2169 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2170 // after class initialization is complete. The app image ClassStatus as-is
2171 // are almost all ClassStatus::Initialized, and being in the
2172 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2173 //
2174 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2175 //
2176 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002177 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002178 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2179 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002180 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002181 }
2182 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002183 }
2184 if (!oat_file->GetBssGcRoots().empty()) {
2185 // Insert oat file to class table for visiting .bss GC roots.
2186 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002187 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002188
Mathieu Chartier69731002016-03-02 16:08:31 -08002189 if (added_class_table) {
2190 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2191 class_table->AddClassSet(std::move(temp_set));
2192 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002193
Mathieu Chartier69731002016-03-02 16:08:31 -08002194 if (kIsDebugBuild && app_image) {
2195 // This verification needs to happen after the classes have been added to the class loader.
2196 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002197 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002198 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002199 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002200
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002201 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002202 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002203}
2204
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002205bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002206 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2207 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002208}
2209
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002210void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002211 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2212 // enabling tracing requires the mutator lock, there are no race conditions here.
2213 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002214 Thread* const self = Thread::Current();
2215 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002216 if (kUseReadBarrier) {
2217 // We do not track new roots for CC.
2218 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2219 kVisitRootFlagClearRootLog |
2220 kVisitRootFlagStartLoggingNewRoots |
2221 kVisitRootFlagStopLoggingNewRoots));
2222 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002223 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002224 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2225 // There is 3 GC cases to handle:
2226 // Non moving concurrent:
2227 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002228 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002229 //
2230 // Moving non-concurrent:
2231 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2232 // To prevent missing roots, this case needs to ensure that there is no
2233 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2234 // class which is in the class table.
2235 //
2236 // Moving concurrent:
2237 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2238 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002239 //
2240 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2241 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2242 // these objects.
2243 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002244 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002245 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002246 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002247 for (const ClassLoaderData& data : class_loaders_) {
2248 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2249 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2250 }
2251 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002252 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002253 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002254 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002255 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002256 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002257 // Concurrent moving GC marked new roots through the to-space invariant.
2258 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002259 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002260 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2261 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2262 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2263 if (old_ref != nullptr) {
2264 DCHECK(old_ref->IsClass());
2265 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2266 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2267 // Concurrent moving GC marked new roots through the to-space invariant.
2268 CHECK_EQ(new_ref, old_ref);
2269 }
2270 }
2271 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002272 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002273 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002274 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002275 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002276 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002277 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002278 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002279 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002280 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002281 }
2282 // We deliberately ignore the class roots in the image since we
2283 // handle image roots by using the MS/CMS rescanning of dirty cards.
2284}
2285
Brian Carlstroma663ea52011-08-19 23:33:41 -07002286// Keep in sync with InitCallback. Anything we visit, we need to
2287// reinit references to when reinitializing a ClassLinker from a
2288// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002289void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002290 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002291 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002292 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2293 // unloading if we are marking roots.
2294 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002295}
2296
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002297class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2298 public:
2299 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2300 : visitor_(visitor),
2301 done_(false) {}
2302
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002303 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002304 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002305 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002306 if (!done_ && class_table != nullptr) {
2307 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2308 if (!class_table->Visit(visitor)) {
2309 // If the visitor ClassTable returns false it means that we don't need to continue.
2310 done_ = true;
2311 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002312 }
2313 }
2314
2315 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002316 // Class visitor that limits the class visits from a ClassTable to the classes with
2317 // the provided defining class loader. This filter is used to avoid multiple visits
2318 // of the same class which can be recorded for multiple initiating class loaders.
2319 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2320 public:
2321 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2322 ClassVisitor* visitor)
2323 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2324
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002325 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002326 if (klass->GetClassLoader() != defining_class_loader_) {
2327 return true;
2328 }
2329 return (*visitor_)(klass);
2330 }
2331
2332 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2333 ClassVisitor* const visitor_;
2334 };
2335
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002336 ClassVisitor* const visitor_;
2337 // If done is true then we don't need to do any more visiting.
2338 bool done_;
2339};
2340
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002341void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002342 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002343 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2344 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002345 }
2346}
2347
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002348void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002349 Thread* const self = Thread::Current();
2350 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2351 // Not safe to have thread suspension when we are holding a lock.
2352 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002353 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002354 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002355 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002356 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002357 }
2358}
2359
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002360class GetClassesInToVector : public ClassVisitor {
2361 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002362 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002363 classes_.push_back(klass);
2364 return true;
2365 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002366 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002367};
2368
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002369class GetClassInToObjectArray : public ClassVisitor {
2370 public:
2371 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2372 : arr_(arr), index_(0) {}
2373
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002374 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002375 ++index_;
2376 if (index_ <= arr_->GetLength()) {
2377 arr_->Set(index_ - 1, klass);
2378 return true;
2379 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002380 return false;
2381 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002382
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002383 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002384 return index_ <= arr_->GetLength();
2385 }
2386
2387 private:
2388 mirror::ObjectArray<mirror::Class>* const arr_;
2389 int32_t index_;
2390};
2391
2392void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002393 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2394 // is avoiding duplicates.
2395 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002396 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002397 GetClassesInToVector accumulator;
2398 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002399 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002400 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002401 return;
2402 }
2403 }
2404 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002405 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002406 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002407 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002408 // We size the array assuming classes won't be added to the class table during the visit.
2409 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002410 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002411 size_t class_table_size;
2412 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002413 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002414 // Add 100 in case new classes get loaded when we are filling in the object array.
2415 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002416 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002417 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002418 classes.Assign(
2419 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002420 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002421 GetClassInToObjectArray accumulator(classes.Get());
2422 VisitClasses(&accumulator);
2423 if (accumulator.Succeeded()) {
2424 break;
2425 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002426 }
2427 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2428 // If the class table shrank during creation of the clases array we expect null elements. If
2429 // the class table grew then the loop repeats. If classes are created after the loop has
2430 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002431 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002432 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002433 return;
2434 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002435 }
2436 }
2437}
2438
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002439ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002440 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002441 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002442 // CHA unloading analysis is not needed. No negative consequences are expected because
2443 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002444 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002445 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002446 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002447}
2448
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002449void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002450 Runtime* const runtime = Runtime::Current();
2451 JavaVMExt* const vm = runtime->GetJavaVM();
2452 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002453 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002454 if (runtime->GetJit() != nullptr) {
2455 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2456 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002457 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002458 code_cache->RemoveMethodsIn(self, *data.allocator);
2459 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002460 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002461 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002462 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002463 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002464 // Cleanup references to single implementation ArtMethods that will be deleted.
2465 if (cleanup_cha) {
2466 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2467 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2468 }
2469
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002470 delete data.allocator;
2471 delete data.class_table;
2472}
2473
Vladimir Markobcf17522018-06-01 13:14:32 +01002474ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2475 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002476 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002477 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2478 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002479}
2480
Vladimir Markobcf17522018-06-01 13:14:32 +01002481ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2482 Thread* self,
2483 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002484 StackHandleScope<1> hs(self);
2485 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002486 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002487 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002488 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002489 self->AssertPendingOOMException();
2490 return nullptr;
2491 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002492 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002493 if (location == nullptr) {
2494 self->AssertPendingOOMException();
2495 return nullptr;
2496 }
2497 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002498 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002499}
2500
Vladimir Markobcf17522018-06-01 13:14:32 +01002501ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2502 const DexFile& dex_file,
2503 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002504 ObjPtr<mirror::String> location = nullptr;
2505 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002506 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002507 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002508 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002509 mirror::DexCache::InitializeDexCache(self,
2510 dex_cache,
2511 location,
2512 &dex_file,
2513 linear_alloc,
2514 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002515 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002516 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002517}
2518
Roland Levillain0e840272018-08-23 19:55:30 +01002519template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002520ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2521 ObjPtr<mirror::Class> java_lang_Class,
2522 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002523 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002524 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002525 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002526 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002527 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2528 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002529 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002530 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002531 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002532 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002533 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002534}
2535
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002536ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002537 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002538}
2539
Roland Levillain0e840272018-08-23 19:55:30 +01002540ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2541 ObjPtr<mirror::Class> java_lang_Class) {
2542 // We make this class non-movable for the unlikely case where it were to be
2543 // moved by a sticky-bit (minor) collection when using the Generational
2544 // Concurrent Copying (CC) collector, potentially creating a stale reference
2545 // in the `klass_` field of one of its instances allocated in the Large-Object
2546 // Space (LOS) -- see the comment about the dirty card scanning logic in
2547 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002548 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002549 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2550}
2551
Vladimir Markobcf17522018-06-01 13:14:32 +01002552ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002553 Thread* self,
2554 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002555 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002556 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002557}
2558
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002559ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2560 const char* descriptor,
2561 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002562 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002563 if (kIsDebugBuild) {
2564 StackHandleScope<1> hs(self);
2565 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2566 Thread::PoisonObjectPointersIfDebug();
2567 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002568
2569 // For temporary classes we must wait for them to be retired.
2570 if (init_done_ && klass->IsTemp()) {
2571 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002572 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002573 ThrowEarlierClassFailure(klass);
2574 return nullptr;
2575 }
2576 StackHandleScope<1> hs(self);
2577 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2578 ObjectLock<mirror::Class> lock(self, h_class);
2579 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002580 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002581 lock.WaitIgnoringInterrupts();
2582 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002583 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002584 ThrowEarlierClassFailure(h_class.Get());
2585 return nullptr;
2586 }
2587 CHECK(h_class->IsRetired());
2588 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002589 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002590 }
2591
Brian Carlstromaded5f72011-10-07 17:15:04 -07002592 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002593 size_t index = 0;
2594 // Maximum number of yield iterations until we start sleeping.
2595 static const size_t kNumYieldIterations = 1000;
2596 // How long each sleep is in us.
2597 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002598 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002599 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002600 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002601 {
2602 ObjectTryLock<mirror::Class> lock(self, h_class);
2603 // Can not use a monitor wait here since it may block when returning and deadlock if another
2604 // thread has locked klass.
2605 if (lock.Acquired()) {
2606 // Check for circular dependencies between classes, the lock is required for SetStatus.
2607 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2608 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002609 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002610 return nullptr;
2611 }
2612 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002613 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002614 {
2615 // Handle wrapper deals with klass moving.
2616 ScopedThreadSuspension sts(self, kSuspended);
2617 if (index < kNumYieldIterations) {
2618 sched_yield();
2619 } else {
2620 usleep(kSleepDurationUS);
2621 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002622 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002623 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002624 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002625
Vladimir Marko72ab6842017-01-20 19:32:50 +00002626 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002627 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002628 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 }
2630 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002631 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002632 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002633 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002634}
2635
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002636using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002637
2638// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002639ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002640 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002641 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002642 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002643 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002644 return ClassPathEntry(dex_file, dex_class_def);
2645 }
2646 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002647 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002648}
2649
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002650bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2651 Thread* self,
2652 const char* descriptor,
2653 size_t hash,
2654 Handle<mirror::ClassLoader> class_loader,
2655 /*out*/ ObjPtr<mirror::Class>* result) {
2656 ArtField* field =
2657 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2658 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2659 if (raw_shared_libraries == nullptr) {
2660 return true;
2661 }
2662
2663 StackHandleScope<2> hs(self);
2664 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2665 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2666 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2667 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2668 temp_loader.Assign(shared_libraries->Get(i));
2669 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2670 return false; // One of the shared libraries is not supported.
2671 }
2672 if (*result != nullptr) {
2673 return true; // Found the class up the chain.
2674 }
2675 }
2676 return true;
2677}
2678
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002679bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2680 Thread* self,
2681 const char* descriptor,
2682 size_t hash,
2683 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002684 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002685 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002686 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002687 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002688 return true;
2689 }
2690
David Brazdil05909d82018-12-06 16:25:16 +00002691 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002692 // For regular path or dex class loader the search order is:
2693 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002694 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002695 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002696
Calin Juravlecdd49122017-07-05 20:09:53 -07002697 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2698 StackHandleScope<1> hs(self);
2699 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2700 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2701 return false; // One of the parents is not supported.
2702 }
2703 if (*result != nullptr) {
2704 return true; // Found the class up the chain.
2705 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002706
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002707 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2708 return false; // One of the shared library loader is not supported.
2709 }
2710 if (*result != nullptr) {
2711 return true; // Found the class in a shared library.
2712 }
2713
Calin Juravlecdd49122017-07-05 20:09:53 -07002714 // Search the current class loader classpath.
2715 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002716 return true;
2717 }
2718
Calin Juravlecdd49122017-07-05 20:09:53 -07002719 if (IsDelegateLastClassLoader(soa, class_loader)) {
2720 // For delegate last, the search order is:
2721 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002722 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002723 // - class loader dex files
2724 // - parent
2725 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2726 if (*result != nullptr) {
2727 return true; // The class is part of the boot class path.
2728 }
2729
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002730 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2731 return false; // One of the shared library loader is not supported.
2732 }
2733 if (*result != nullptr) {
2734 return true; // Found the class in a shared library.
2735 }
2736
Calin Juravlecdd49122017-07-05 20:09:53 -07002737 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2738 if (*result != nullptr) {
2739 return true; // Found the class in the current class loader
2740 }
2741
2742 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2743 StackHandleScope<1> hs(self);
2744 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2745 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2746 }
2747
2748 // Unsupported class loader.
2749 *result = nullptr;
2750 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002751}
2752
2753// Finds the class in the boot class loader.
2754// If the class is found the method returns the resolved class. Otherwise it returns null.
2755ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2756 const char* descriptor,
2757 size_t hash) {
2758 ObjPtr<mirror::Class> result = nullptr;
2759 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2760 if (pair.second != nullptr) {
2761 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2762 if (klass != nullptr) {
2763 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002764 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002765 result = DefineClass(self,
2766 descriptor,
2767 hash,
2768 ScopedNullHandle<mirror::ClassLoader>(),
2769 *pair.first,
2770 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002771 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002772 if (result == nullptr) {
2773 CHECK(self->IsExceptionPending()) << descriptor;
2774 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002775 }
2776 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002777 return result;
2778}
Andreas Gampef865ea92015-04-13 22:14:19 -07002779
Calin Juravle415dc3d2017-06-28 11:03:12 -07002780ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2781 ScopedObjectAccessAlreadyRunnable& soa,
2782 const char* descriptor,
2783 size_t hash,
2784 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002785 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2786 IsInMemoryDexClassLoader(soa, class_loader) ||
2787 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002788 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002789
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002790 ObjPtr<mirror::Class> ret;
2791 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002792 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002793 if (dex_class_def != nullptr) {
2794 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2795 descriptor,
2796 hash,
2797 class_loader,
2798 *cp_dex_file,
2799 *dex_class_def);
2800 if (klass == nullptr) {
2801 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2802 soa.Self()->ClearException();
2803 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002804 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002805 ret = klass;
2806 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002807 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002808 return true; // Continue with the next DexFile.
2809 };
2810
2811 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2812 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002813}
2814
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002815ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2816 const char* descriptor,
2817 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002818 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002819 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002820 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002821 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002822 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002823 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2824 // for primitive classes that aren't backed by dex files.
2825 return FindPrimitiveClass(descriptor[0]);
2826 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002827 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002828 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002829 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002830 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002831 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002832 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002833 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002834 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002835 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002836 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002837 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002838 return DefineClass(self,
2839 descriptor,
2840 hash,
2841 ScopedNullHandle<mirror::ClassLoader>(),
2842 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002843 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002844 } else {
2845 // The boot class loader is searched ahead of the application class loader, failures are
2846 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2847 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002848 ObjPtr<mirror::Throwable> pre_allocated =
2849 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002850 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002851 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002852 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002853 }
2854 ObjPtr<mirror::Class> result_ptr;
2855 bool descriptor_equals;
2856 if (descriptor[0] == '[') {
2857 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2858 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2859 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2860 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002861 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002862 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002863 bool known_hierarchy =
2864 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2865 if (result_ptr != nullptr) {
2866 // The chain was understood and we found the class. We still need to add the class to
2867 // the class table to protect from racy programs that can try and redefine the path list
2868 // which would change the Class<?> returned for subsequent evaluation of const-class.
2869 DCHECK(known_hierarchy);
2870 DCHECK(result_ptr->DescriptorEquals(descriptor));
2871 descriptor_equals = true;
2872 } else {
2873 // Either the chain wasn't understood or the class wasn't found.
2874 //
2875 // If the chain was understood but we did not find the class, let the Java-side
2876 // rediscover all this and throw the exception with the right stack trace. Note that
2877 // the Java-side could still succeed for racy programs if another thread is actively
2878 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002879
Alex Light185a4612018-10-04 15:54:25 -07002880 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002881 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002882 // Oops, we can't call into java so we can't run actual class-loader code.
2883 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002884 ObjPtr<mirror::Throwable> pre_allocated =
2885 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2886 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002887 return nullptr;
2888 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002889
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002890 // Inlined DescriptorToDot(descriptor) with extra validation.
2891 //
2892 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2893 // the DescriptorEquals() check below and give a confusing error message. For example,
2894 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2895 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2896 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2897 size_t descriptor_length = strlen(descriptor);
2898 if (UNLIKELY(descriptor[0] != 'L') ||
2899 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2900 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2901 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2902 return nullptr;
2903 }
2904 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2905 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2906
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002907 ScopedLocalRef<jobject> class_loader_object(
2908 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002909 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2910 {
2911 ScopedThreadStateChange tsc(self, kNative);
2912 ScopedLocalRef<jobject> class_name_object(
2913 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2914 if (class_name_object.get() == nullptr) {
2915 DCHECK(self->IsExceptionPending()); // OOME.
2916 return nullptr;
2917 }
2918 CHECK(class_loader_object.get() != nullptr);
2919 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2920 WellKnownClasses::java_lang_ClassLoader_loadClass,
2921 class_name_object.get()));
2922 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002923 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002924 // broken loader - throw NPE to be compatible with Dalvik
2925 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2926 class_name_string.c_str()).c_str());
2927 return nullptr;
2928 }
2929 result_ptr = soa.Decode<mirror::Class>(result.get());
2930 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002931 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002932 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002933 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002934
2935 if (self->IsExceptionPending()) {
2936 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2937 // However, to comply with the RI behavior, first check if another thread succeeded.
2938 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2939 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2940 self->ClearException();
2941 return EnsureResolved(self, descriptor, result_ptr);
2942 }
2943 return nullptr;
2944 }
2945
2946 // Try to insert the class to the class table, checking for mismatch.
2947 ObjPtr<mirror::Class> old;
2948 {
2949 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2950 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2951 old = class_table->Lookup(descriptor, hash);
2952 if (old == nullptr) {
2953 old = result_ptr; // For the comparison below, after releasing the lock.
2954 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002955 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002956 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002957 } // else throw below, after releasing the lock.
2958 }
2959 }
2960 if (UNLIKELY(old != result_ptr)) {
2961 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2962 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2963 mirror::Class* loader_class = class_loader->GetClass();
2964 const char* loader_class_name =
2965 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2966 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2967 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2968 << DescriptorToDot(descriptor) << "\").";
2969 return EnsureResolved(self, descriptor, old);
2970 }
2971 if (UNLIKELY(!descriptor_equals)) {
2972 std::string result_storage;
2973 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2974 std::string loader_storage;
2975 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2976 ThrowNoClassDefFoundError(
2977 "Initiating class loader of type %s returned class %s instead of %s.",
2978 DescriptorToDot(loader_class_name).c_str(),
2979 DescriptorToDot(result_name).c_str(),
2980 DescriptorToDot(descriptor).c_str());
2981 return nullptr;
2982 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002983 // Success.
2984 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002985}
2986
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002987ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
2988 const char* descriptor,
2989 size_t hash,
2990 Handle<mirror::ClassLoader> class_loader,
2991 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002992 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002993 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002994 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002995
Brian Carlstromaded5f72011-10-07 17:15:04 -07002996 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002997 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002998 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002999 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003000 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003001 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003002 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003003 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003004 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003005 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003006 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003007 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003008 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003009 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003010 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003011 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003012 }
3013
Alex Lighte9f61032018-09-24 16:04:51 -07003014 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3015 // code to be executed. We put it up here so we can avoid all the allocations associated with
3016 // creating the class. This can happen with (eg) jit threads.
3017 if (!self->CanLoadClasses()) {
3018 // Make sure we don't try to load anything, potentially causing an infinite loop.
3019 ObjPtr<mirror::Throwable> pre_allocated =
3020 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3021 self->SetException(pre_allocated);
3022 return nullptr;
3023 }
3024
Andreas Gampefa4333d2017-02-14 11:10:34 -08003025 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003026 // Allocate a class with the status of not ready.
3027 // Interface object should get the right size here. Regular class will
3028 // figure out the right size later and be replaced with one of the right
3029 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003030 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003031 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003032 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003033 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003034 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003035 }
Alex Lightb0f11922017-01-23 14:25:17 -08003036 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3037 // nothing.
3038 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003039 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003040 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3041 // will only be called once.
3042 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3043 klass,
3044 class_loader,
3045 dex_file,
3046 dex_class_def,
3047 &new_dex_file,
3048 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003049 // Check to see if an exception happened during runtime callbacks. Return if so.
3050 if (self->IsExceptionPending()) {
3051 return nullptr;
3052 }
Alex Lightb0f11922017-01-23 14:25:17 -08003053 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003054 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003055 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003056 return nullptr;
3057 }
3058 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003059 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003060
Jeff Hao848f70a2014-01-15 13:49:50 -08003061 // Mark the string class by setting its access flag.
3062 if (UNLIKELY(!init_done_)) {
3063 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3064 klass->SetStringClass();
3065 }
3066 }
3067
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003068 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003069 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003070 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003071 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003072
Mathieu Chartier590fee92013-09-13 13:46:47 -07003073 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003074 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003075 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003076 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3077 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003078 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003079 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003080
Mathieu Chartierc7853442015-03-27 14:35:38 -07003081 // Load the fields and other things after we are inserted in the table. This is so that we don't
3082 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3083 // other reason is that the field roots are only visited from the class table. So we need to be
3084 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003085 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003086 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003087 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003088 // An exception occured during load, set status to erroneous while holding klass' lock in case
3089 // notification is necessary.
3090 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003091 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003092 }
3093 return nullptr;
3094 }
3095
Brian Carlstromaded5f72011-10-07 17:15:04 -07003096 // Finish loading (if necessary) by finding parents
3097 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003098 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003099 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003100 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003101 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003102 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003103 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003104 }
3105 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003106
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003107 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003108 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003109 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003110
Brian Carlstromaded5f72011-10-07 17:15:04 -07003111 // Link the class (if necessary)
3112 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003113 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003114 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003115
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003116 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003117 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003118 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003119 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003120 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003121 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003122 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003123 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003124 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003125 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003126 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003127
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003128 // Instrumentation may have updated entrypoints for all methods of all
3129 // classes. However it could not update methods of this class while we
3130 // were loading it. Now the class is resolved, we can update entrypoints
3131 // as required by instrumentation.
3132 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3133 // We must be in the kRunnable state to prevent instrumentation from
3134 // suspending all threads to update entrypoints while we are doing it
3135 // for this class.
3136 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003137 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003138 }
3139
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003140 /*
3141 * We send CLASS_PREPARE events to the debugger from here. The
3142 * definition of "preparation" is creating the static fields for a
3143 * class and initializing them to the standard default values, but not
3144 * executing any code (that comes later, during "initialization").
3145 *
3146 * We did the static preparation in LinkClass.
3147 *
3148 * The class has been prepared and resolved but possibly not yet verified
3149 * at this point.
3150 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003151 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003152
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003153 // Notify native debugger of the new class and its layout.
3154 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3155
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003156 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003157}
3158
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003159uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003160 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003161 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003162 size_t num_8 = 0;
3163 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003164 size_t num_32 = 0;
3165 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003166 ClassAccessor accessor(dex_file, dex_class_def);
3167 // We allow duplicate definitions of the same field in a class_data_item
3168 // but ignore the repeated indexes here, b/21868015.
3169 uint32_t last_field_idx = dex::kDexNoIndex;
3170 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3171 uint32_t field_idx = field.GetIndex();
3172 // Ordering enforced by DexFileVerifier.
3173 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3174 if (UNLIKELY(field_idx == last_field_idx)) {
3175 continue;
3176 }
3177 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003178 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003179 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3180 char c = descriptor[0];
3181 switch (c) {
3182 case 'L':
3183 case '[':
3184 num_ref++;
3185 break;
3186 case 'J':
3187 case 'D':
3188 num_64++;
3189 break;
3190 case 'I':
3191 case 'F':
3192 num_32++;
3193 break;
3194 case 'S':
3195 case 'C':
3196 num_16++;
3197 break;
3198 case 'B':
3199 case 'Z':
3200 num_8++;
3201 break;
3202 default:
3203 LOG(FATAL) << "Unknown descriptor: " << c;
3204 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003205 }
3206 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003207 return mirror::Class::ComputeClassSize(false,
3208 0,
3209 num_8,
3210 num_16,
3211 num_32,
3212 num_64,
3213 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003214 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003215}
3216
Alex Lightfc49fec2018-01-16 22:28:36 +00003217// Special case to get oat code without overwriting a trampoline.
3218const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003219 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003220 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003221 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003222 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003223 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3224 if (code != nullptr) {
3225 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003226 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003227 if (method->IsNative()) {
3228 // No code and native? Use generic trampoline.
3229 return GetQuickGenericJniStub();
3230 }
3231 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003232}
3233
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003234bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003235 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003236 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3237 return false;
3238 }
3239
Elliott Hughes956af0f2014-12-11 14:34:28 -08003240 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003241 return true;
3242 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003243
3244 Runtime* runtime = Runtime::Current();
3245 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3246 if (instr->InterpretOnly()) {
3247 return true;
3248 }
3249
3250 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3251 // Doing this check avoids doing compiled/interpreter transitions.
3252 return true;
3253 }
3254
3255 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
3256 // Force the use of interpreter when it is required by the debugger.
3257 return true;
3258 }
3259
Alex Light8f34aba2017-10-09 13:46:32 -07003260 if (Thread::Current()->IsAsyncExceptionPending()) {
3261 // Force use of interpreter to handle async-exceptions
3262 return true;
3263 }
3264
Alex Light2d441b12018-06-08 15:33:21 -07003265 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3266 const void* instr_target = instr->GetCodeForInvoke(method);
3267 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3268 return ShouldUseInterpreterEntrypoint(method, instr_target);
3269 }
3270
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003271 if (runtime->IsJavaDebuggable()) {
3272 // For simplicity, we ignore precompiled code and go to the interpreter
3273 // assuming we don't already have jitted code.
3274 // We could look at the oat file where `quick_code` is being defined,
3275 // and check whether it's been compiled debuggable, but we decided to
3276 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003277 jit::Jit* jit = Runtime::Current()->GetJit();
3278 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3279 }
3280
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003281 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003282 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003283 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003284 // since we want to JIT it (at first use) with extra stackmaps for native
3285 // debugging. We keep however all AOT code from the boot image,
3286 // since the JIT-at-first-use is blocking and would result in non-negligible
3287 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003288 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003289 }
3290
3291 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003292}
3293
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003294void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003295 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003296 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003297 if (klass->NumDirectMethods() == 0) {
3298 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003299 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003300 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003301 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003302 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003303 return; // OAT file unavailable.
3304 }
Ian Rogers19846512012-02-24 11:42:47 -08003305 }
Alex Light64ad14d2014-08-19 14:23:13 -07003306
Mathieu Chartierf8322842014-05-16 10:59:25 -07003307 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003308 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3309 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3310 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003311 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003312 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003313 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003314 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3315 klass->GetDexClassDefIndex(),
3316 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003317 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003318 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003319 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003320 if (!method->IsStatic()) {
3321 // Only update static methods.
3322 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003323 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003324 const void* quick_code = nullptr;
3325 if (has_oat_class) {
3326 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003327 quick_code = oat_method.GetQuickCode();
3328 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003329 // Check whether the method is native, in which case it's generic JNI.
3330 if (quick_code == nullptr && method->IsNative()) {
3331 quick_code = GetQuickGenericJniStub();
3332 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003333 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003334 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003335 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003336 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003337 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003338 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003339}
3340
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003341// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3342// method. Should only be called on non-invokable methods.
3343inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003344 DCHECK(method != nullptr);
3345 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003346 method->SetEntryPointFromQuickCompiledCodePtrSize(
3347 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3348 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003349}
3350
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003351static void LinkCode(ClassLinker* class_linker,
3352 ArtMethod* method,
3353 const OatFile::OatClass* oat_class,
3354 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003355 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003356 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003357 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003358 // The following code only applies to a non-compiler runtime.
3359 return;
3360 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003361 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003362 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003363 if (oat_class != nullptr) {
3364 // Every kind of method should at least get an invoke stub from the oat_method.
3365 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003366 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003367 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003368 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003369
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003370 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003371 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003372 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003373
Alex Light9139e002015-10-09 15:59:48 -07003374 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003375 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003376 return;
3377 }
Ian Rogers19846512012-02-24 11:42:47 -08003378
3379 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003380 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003381 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3382 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003383 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003384 } else if (quick_code == nullptr && method->IsNative()) {
3385 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003386 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003387 // Set entry point from compiled code if there's no code or in interpreter only mode.
3388 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003389 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003390
Ian Rogers62d6c772013-02-27 08:32:07 -08003391 if (method->IsNative()) {
3392 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003393 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003394
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003395 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003396 // We have a native method here without code. Then it should have either the generic JNI
3397 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3398 // TODO: this doesn't handle all the cases where trampolines may be installed.
3399 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003400 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3401 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003402 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003403 }
3404}
3405
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003406void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003407 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003408 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003409 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003410 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003411 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003412 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003413 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003414 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003415
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003416 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003417 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003418 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003419 klass->SetAccessFlags(access_flags);
3420 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003421 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003422 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003423
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003424 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003425 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003426}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003427
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003428LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3429 LinearAlloc* allocator,
3430 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003431 if (length == 0) {
3432 return nullptr;
3433 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003434 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3435 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3436 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003437 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003438 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003439 CHECK(ret != nullptr);
3440 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3441 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003442}
3443
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003444LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3445 LinearAlloc* allocator,
3446 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003447 if (length == 0) {
3448 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003449 }
Vladimir Marko14632852015-08-17 12:07:23 +01003450 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3451 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003452 const size_t storage_size =
3453 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003454 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003455 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003456 CHECK(ret != nullptr);
3457 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003458 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003459 }
3460 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003461}
3462
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003463LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003464 if (class_loader == nullptr) {
3465 return Runtime::Current()->GetLinearAlloc();
3466 }
3467 LinearAlloc* allocator = class_loader->GetAllocator();
3468 DCHECK(allocator != nullptr);
3469 return allocator;
3470}
3471
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003472LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003473 if (class_loader == nullptr) {
3474 return Runtime::Current()->GetLinearAlloc();
3475 }
3476 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3477 LinearAlloc* allocator = class_loader->GetAllocator();
3478 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003479 RegisterClassLoader(class_loader);
3480 allocator = class_loader->GetAllocator();
3481 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003482 }
3483 return allocator;
3484}
3485
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003486void ClassLinker::LoadClass(Thread* self,
3487 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003488 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003489 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003490 ClassAccessor accessor(dex_file,
3491 dex_class_def,
3492 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003493 if (!accessor.HasClassData()) {
3494 return;
3495 }
3496 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003497 {
3498 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3499 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003500 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003501 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003502 // We allow duplicate definitions of the same field in a class_data_item
3503 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003504 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003505 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3506 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003507 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003508 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3509 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003510 accessor.NumInstanceFields());
3511 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003512 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003513 uint32_t last_static_field_idx = 0u;
3514 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003515
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003516 // Methods
3517 bool has_oat_class = false;
3518 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3519 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3520 : OatFile::OatClass::Invalid();
3521 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3522 klass->SetMethodsPtr(
3523 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3524 accessor.NumDirectMethods(),
3525 accessor.NumVirtualMethods());
3526 size_t class_def_method_index = 0;
3527 uint32_t last_dex_method_index = dex::kDexNoIndex;
3528 size_t last_class_def_method_index = 0;
3529
3530 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3531 // methods needs to decode all of the fields.
3532 accessor.VisitFieldsAndMethods([&](
3533 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3534 uint32_t field_idx = field.GetIndex();
3535 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3536 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3537 LoadField(field, klass, &sfields->At(num_sfields));
3538 ++num_sfields;
3539 last_static_field_idx = field_idx;
3540 }
3541 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3542 uint32_t field_idx = field.GetIndex();
3543 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3544 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3545 LoadField(field, klass, &ifields->At(num_ifields));
3546 ++num_ifields;
3547 last_instance_field_idx = field_idx;
3548 }
3549 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3550 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3551 image_pointer_size_);
3552 LoadMethod(dex_file, method, klass, art_method);
3553 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3554 uint32_t it_method_index = method.GetIndex();
3555 if (last_dex_method_index == it_method_index) {
3556 // duplicate case
3557 art_method->SetMethodIndex(last_class_def_method_index);
3558 } else {
3559 art_method->SetMethodIndex(class_def_method_index);
3560 last_dex_method_index = it_method_index;
3561 last_class_def_method_index = class_def_method_index;
3562 }
3563 ++class_def_method_index;
3564 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3565 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3566 class_def_method_index - accessor.NumDirectMethods(),
3567 image_pointer_size_);
3568 LoadMethod(dex_file, method, klass, art_method);
3569 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3570 ++class_def_method_index;
3571 });
3572
3573 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003574 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003575 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3576 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3577 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003578 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3579 if (sfields != nullptr) {
3580 sfields->SetSize(num_sfields);
3581 }
3582 if (ifields != nullptr) {
3583 ifields->SetSize(num_ifields);
3584 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003585 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003586 // Set the field arrays.
3587 klass->SetSFieldsPtr(sfields);
3588 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003589 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003590 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003591 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003592 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003593 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003594 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003595}
3596
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003597void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003598 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003599 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003600 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003601 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003602 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003603
David Brazdil85865692018-10-30 17:26:20 +00003604 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3605 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003606}
3607
Mathieu Chartier268764d2016-09-13 12:09:38 -07003608void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003609 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003610 Handle<mirror::Class> klass,
3611 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003612 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003613 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003614 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003615
Mathieu Chartier268764d2016-09-13 12:09:38 -07003616 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003617 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003618 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003619 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003620
David Brazdil85865692018-10-30 17:26:20 +00003621 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3622 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003623
Ian Rogersdfb325e2013-10-30 01:00:44 -07003624 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003625 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003626 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3627 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003628 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003629 klass->SetFinalizable();
3630 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003631 std::string temp;
3632 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003633 // The Enum class declares a "final" finalize() method to prevent subclasses from
3634 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3635 // subclasses, so we exclude it here.
3636 // We also want to avoid setting the flag on Object, where we know that finalize() is
3637 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003638 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3639 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003640 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003641 }
3642 }
3643 }
3644 } else if (method_name[0] == '<') {
3645 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003646 bool is_init = (strcmp("<init>", method_name) == 0);
3647 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003648 if (UNLIKELY(!is_init && !is_clinit)) {
3649 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3650 } else {
3651 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3652 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003653 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003654 access_flags |= kAccConstructor;
3655 }
3656 }
3657 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003658 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3659 // Check if the native method is annotated with @FastNative or @CriticalNative.
3660 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3661 dex_file, dst->GetClassDef(), dex_method_idx);
3662 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003663 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003664 // Must be done after SetAccessFlags since IsAbstract depends on it.
3665 if (klass->IsInterface() && dst->IsAbstract()) {
3666 dst->CalculateAndSetImtIndex();
3667 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003668}
3669
Ian Rogers7b078e82014-09-10 14:44:24 -07003670void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003671 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003672 self,
3673 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003674 Runtime::Current()->GetLinearAlloc());
3675 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003676 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003677}
3678
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003679void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003680 ObjPtr<mirror::DexCache> dex_cache) {
3681 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003682 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003683 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003684 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003685}
3686
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003687void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003688 ObjPtr<mirror::DexCache> dex_cache,
3689 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003690 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003691 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003692 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003693 // For app images, the dex cache location may be a suffix of the dex file location since the
3694 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003695 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3696 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003697 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3698 std::string dex_file_location = dex_file.GetLocation();
3699 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003700 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003701 // Take suffix.
3702 const std::string dex_file_suffix = dex_file_location.substr(
3703 dex_file_location.length() - dex_cache_length,
3704 dex_cache_length);
3705 // Example dex_cache location is SettingsProvider.apk and
3706 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003707 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003708 const OatFile* oat_file =
3709 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003710 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3711 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3712 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3713 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003714 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003715 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3716 DexCacheData data = *it;
3717 if (self->IsJWeakCleared(data.weak_root)) {
3718 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003719 it = dex_caches_.erase(it);
3720 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003721 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003722 it->dex_file->GetOatDexFile() != nullptr &&
3723 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003724 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003725 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003726 ++it;
3727 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003728 }
Vladimir Markob066d432018-01-03 13:14:37 +00003729 if (initialize_oat_file_data) {
3730 // Initialize the .data.bimg.rel.ro section.
3731 if (!oat_file->GetBootImageRelocations().empty()) {
3732 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3733 CheckedCall(mprotect,
3734 "un-protect boot image relocations",
3735 reloc_begin,
3736 oat_file->DataBimgRelRoSize(),
3737 PROT_READ | PROT_WRITE);
3738 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3739 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3740 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3741 const_cast<uint32_t&>(relocation) += boot_image_begin;
3742 }
3743 CheckedCall(mprotect,
3744 "protect boot image relocations",
3745 reloc_begin,
3746 oat_file->DataBimgRelRoSize(),
3747 PROT_READ);
3748 }
3749
3750 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003751 // TODO: Pre-initialize from boot/app image?
3752 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3753 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3754 entry = resolution_method;
3755 }
3756 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003757 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003758 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003759 DexCacheData data;
3760 data.weak_root = dex_cache_jweak;
3761 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003762 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003763 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003764 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003765 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3766 // path dex caches without an image.
3767 data.class_table->InsertStrongRoot(dex_cache);
3768 if (class_loader != nullptr) {
3769 // Since we added a strong root to the class table, do the write barrier as required for
3770 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003771 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003772 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003773 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003774}
3775
Vladimir Markocd556b02017-02-03 11:47:34 +00003776ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3777 return data.IsValid()
3778 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3779 : nullptr;
3780}
3781
3782ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3783 Thread* self,
3784 ObjPtr<mirror::DexCache> dex_cache,
3785 const DexCacheData& data,
3786 ObjPtr<mirror::ClassLoader> class_loader) {
3787 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3788 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3789 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3790 "Attempt to register dex file %s with multiple class loaders",
3791 data.dex_file->GetLocation().c_str());
3792 return nullptr;
3793 }
3794 return dex_cache;
3795}
3796
Alex Light07f06212017-06-01 14:01:43 -07003797void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3798 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003799 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003800 Thread* self = Thread::Current();
3801 StackHandleScope<2> hs(self);
3802 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3803 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3804 const DexFile* dex_file = dex_cache->GetDexFile();
3805 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3806 if (kIsDebugBuild) {
3807 DexCacheData old_data;
3808 {
3809 ReaderMutexLock mu(self, *Locks::dex_lock_);
3810 old_data = FindDexCacheDataLocked(*dex_file);
3811 }
3812 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3813 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3814 << "been registered on dex file " << dex_file->GetLocation();
3815 }
3816 ClassTable* table;
3817 {
3818 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3819 table = InsertClassTableForClassLoader(h_class_loader.Get());
3820 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003821 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3822 // a thread holding the dex lock and blocking on a condition variable regarding
3823 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003824 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003825 WriterMutexLock mu(self, *Locks::dex_lock_);
3826 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3827 table->InsertStrongRoot(h_dex_cache.Get());
3828 if (h_class_loader.Get() != nullptr) {
3829 // Since we added a strong root to the class table, do the write barrier as required for
3830 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003831 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003832 }
3833}
3834
Vladimir Markocd556b02017-02-03 11:47:34 +00003835ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3836 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003837 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003838 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003839 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003840 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003841 old_data = FindDexCacheDataLocked(dex_file);
3842 }
3843 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3844 if (old_dex_cache != nullptr) {
3845 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003846 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003847 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003848 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3849 DCHECK(linear_alloc != nullptr);
3850 ClassTable* table;
3851 {
3852 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3853 table = InsertClassTableForClassLoader(class_loader);
3854 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003855 // Don't alloc while holding the lock, since allocation may need to
3856 // suspend all threads and another thread may need the dex_lock_ to
3857 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003858 StackHandleScope<3> hs(self);
3859 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003860 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003861 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3862 self,
3863 dex_file)));
3864 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003865 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003866 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3867 // a thread holding the dex lock and blocking on a condition variable regarding
3868 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003869 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003870 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003871 old_data = FindDexCacheDataLocked(dex_file);
3872 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003873 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003874 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3875 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3876 // that the arrays are null.
3877 mirror::DexCache::InitializeDexCache(self,
3878 h_dex_cache.Get(),
3879 h_location.Get(),
3880 &dex_file,
3881 linear_alloc,
3882 image_pointer_size_);
3883 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003884 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003885 }
3886 if (old_dex_cache != nullptr) {
3887 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3888 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003889 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003890 self->ClearException();
3891 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3892 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3893 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003894 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003895 self->AssertPendingOOMException();
3896 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003897 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003898 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003899 if (h_class_loader.Get() != nullptr) {
3900 // Since we added a strong root to the class table, do the write barrier as required for
3901 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003902 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003903 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003904 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003905}
3906
Vladimir Markocd556b02017-02-03 11:47:34 +00003907bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003908 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003909 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003910}
3911
Vladimir Markocd556b02017-02-03 11:47:34 +00003912ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3913 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003914 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3915 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003916 if (dex_cache != nullptr) {
3917 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003918 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003919 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003920 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003921 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003922 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003923 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003924 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003925 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3926 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003927 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003928}
3929
Vladimir Markocd556b02017-02-03 11:47:34 +00003930ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3931 const DexFile* dex_file = dex_cache->GetDexFile();
3932 DCHECK(dex_file != nullptr);
3933 ReaderMutexLock mu(self, *Locks::dex_lock_);
3934 // Search assuming unique-ness of dex file.
3935 for (const DexCacheData& data : dex_caches_) {
3936 // Avoid decoding (and read barriers) other unrelated dex caches.
3937 if (data.dex_file == dex_file) {
3938 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3939 if (registered_dex_cache != nullptr) {
3940 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3941 return data.class_table;
3942 }
3943 }
3944 }
3945 return nullptr;
3946}
3947
3948ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3949 // Search assuming unique-ness of dex file.
3950 for (const DexCacheData& data : dex_caches_) {
3951 // Avoid decoding (and read barriers) other unrelated dex caches.
3952 if (data.dex_file == &dex_file) {
3953 return data;
3954 }
3955 }
3956 return DexCacheData();
3957}
3958
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003959ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003960 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003961 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003962 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003963 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003964 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003965 }
Ian Rogers1f539342012-10-03 21:09:42 -07003966 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003967 StackHandleScope<1> hs(self);
3968 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003969 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003970 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3971 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003972 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003973 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003974 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003975 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003976 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3977 h_class.Get(),
3978 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003979 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003980 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003981}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003982
Vladimir Marko02610552018-06-04 14:38:00 +01003983inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
3984 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
3985}
3986
Brian Carlstrombe977852011-07-19 14:54:54 -07003987// Create an array class (i.e. the class object for the array, not the
3988// array itself). "descriptor" looks like "[C" or "[[[[B" or
3989// "[Ljava/lang/String;".
3990//
3991// If "descriptor" refers to an array of primitives, look up the
3992// primitive type's internally-generated class object.
3993//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003994// "class_loader" is the class loader of the class that's referring to
3995// us. It's used to ensure that we're looking for the element type in
3996// the right context. It does NOT become the class loader for the
3997// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003998//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003999// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004000ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4001 const char* descriptor,
4002 size_t hash,
4003 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004004 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004005 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004006 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004007
4008 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4009 // code to be executed. We put it up here so we can avoid all the allocations associated with
4010 // creating the class. This can happen with (eg) jit threads.
4011 if (!self->CanLoadClasses()) {
4012 // Make sure we don't try to load anything, potentially causing an infinite loop.
4013 ObjPtr<mirror::Throwable> pre_allocated =
4014 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4015 self->SetException(pre_allocated);
4016 return nullptr;
4017 }
4018
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004019 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4020 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004021 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004022 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004023 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004024 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4025 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004026 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004027 DCHECK(self->IsExceptionPending());
4028 return nullptr;
4029 } else {
4030 self->ClearException();
4031 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004032 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004033 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4034 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4035 return nullptr;
4036 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004037 // See if the component type is already loaded. Array classes are
4038 // always associated with the class loader of their underlying
4039 // element type -- an array of Strings goes with the loader for
4040 // java/lang/String -- so we need to look for it there. (The
4041 // caller should have checked for the existence of the class
4042 // before calling here, but they did so with *their* class loader,
4043 // not the component type's loader.)
4044 //
4045 // If we find it, the caller adds "loader" to the class' initiating
4046 // loader list, which should prevent us from going through this again.
4047 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004048 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004049 // are the same, because our caller (FindClass) just did the
4050 // lookup. (Even if we get this wrong we still have correct behavior,
4051 // because we effectively do this lookup again when we add the new
4052 // class to the hash table --- necessary because of possible races with
4053 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004054 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004055 ObjPtr<mirror::Class> new_class =
4056 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004057 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004058 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004059 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004060 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004061
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004062 // Fill out the fields in the Class.
4063 //
4064 // It is possible to execute some methods against arrays, because
4065 // all arrays are subclasses of java_lang_Object_, so we need to set
4066 // up a vtable. We can just point at the one in java_lang_Object_.
4067 //
4068 // Array classes are simple enough that we don't need to do a full
4069 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004070 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004071 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004072 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004073 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004074 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004075 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004076 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4077 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4078 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004079 } else if (strcmp(descriptor, "[Z") == 0) {
4080 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4081 } else if (strcmp(descriptor, "[B") == 0) {
4082 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4083 } else if (strcmp(descriptor, "[C") == 0) {
4084 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4085 } else if (strcmp(descriptor, "[S") == 0) {
4086 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004087 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004088 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004089 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004090 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004091 } else if (strcmp(descriptor, "[F") == 0) {
4092 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4093 } else if (strcmp(descriptor, "[D") == 0) {
4094 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004095 }
4096 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004097 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004098 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004099 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004100 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004101 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004102 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004103 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004104 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004105 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004106 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004107 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004108 new_class->SetSuperClass(java_lang_Object);
4109 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004110 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004111 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004112 if (component_type->IsPrimitive()) {
4113 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4114 } else {
4115 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4116 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004117 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004118 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4119 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4120 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004121 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004122 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004123 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004124 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004125
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004126 // All arrays have java/lang/Cloneable and java/io/Serializable as
4127 // interfaces. We need to set that up here, so that stuff like
4128 // "instanceof" works right.
4129 //
4130 // Note: The GC could run during the call to FindSystemClass,
4131 // so we need to make sure the class object is GC-valid while we're in
4132 // there. Do this by clearing the interface list so the GC will just
4133 // think that the entries are null.
4134
4135
4136 // Use the single, global copies of "interfaces" and "iftable"
4137 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004138 {
Vladimir Marko02610552018-06-04 14:38:00 +01004139 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004140 CHECK(array_iftable != nullptr);
4141 new_class->SetIfTable(array_iftable);
4142 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004143
Elliott Hughes00626c22013-06-14 15:04:14 -07004144 // Inherit access flags from the component type.
4145 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4146 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4147 access_flags &= kAccJavaFlagsMask;
4148 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004149 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004150 access_flags |= kAccAbstract | kAccFinal;
4151 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004152 // Arrays are access-checks-clean and preverified.
4153 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004154
4155 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004156
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004157 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004158 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004159 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4160 // duplicate events in case of races. Array classes don't really follow dedicated
4161 // load and prepare, anyways.
4162 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4163 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4164
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004165 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004166 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004167 }
4168 // Another thread must have loaded the class after we
4169 // started but before we finished. Abandon what we've
4170 // done.
4171 //
4172 // (Yes, this happens.)
4173
Vladimir Markobcf17522018-06-01 13:14:32 +01004174 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004175}
4176
Vladimir Marko9186b182018-11-06 14:55:54 +00004177ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4178 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004179 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004180 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4181 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4182 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4183 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4184 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4185 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4186 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4187 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4188 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004189 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004190 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004191 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004192 return GetClassRoot(class_root, this);
4193}
4194
4195ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4196 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4197 if (UNLIKELY(result == nullptr)) {
4198 std::string printable_type(PrintableChar(type));
4199 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4200 }
4201 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004202}
4203
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004204ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4205 ObjPtr<mirror::Class> klass,
4206 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004207 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004208 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004209 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004210 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004211 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004212 source += " from ";
4213 source += dex_cache->GetLocation()->ToModifiedUtf8();
4214 }
4215 LOG(INFO) << "Loaded class " << descriptor << source;
4216 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004217 {
4218 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004219 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004220 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004221 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004222 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004223 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004224 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004225 VerifyObject(klass);
4226 class_table->InsertWithHash(klass, hash);
4227 if (class_loader != nullptr) {
4228 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004229 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004230 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004231 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004232 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004233 }
4234 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004235 if (kIsDebugBuild) {
4236 // Test that copied methods correctly can find their holder.
4237 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4238 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4239 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004240 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004241 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004242}
4243
Vladimir Marko1998cd02017-01-13 13:02:58 +00004244void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004245 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4246 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4247 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4248 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004249 }
4250}
4251
Alex Lighte64300b2015-12-15 15:02:47 -08004252// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004253void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004254 LengthPrefixedArray<ArtMethod>* new_methods) {
4255 klass->SetMethodsPtrUnchecked(new_methods,
4256 klass->NumDirectMethods(),
4257 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004258 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004259 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004260}
4261
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004262ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4263 const char* descriptor,
4264 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004265 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4266}
4267
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004268ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4269 const char* descriptor,
4270 size_t hash,
4271 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004272 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4273 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4274 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004275 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004276 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004277 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004278 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004279 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004280 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004281}
4282
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004283class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4284 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004285 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004286
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004287 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004288 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004289 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004290 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004291 if (class_table != nullptr) {
4292 class_table->FreezeSnapshot();
4293 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004294 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004295};
4296
4297void ClassLinker::MoveClassTableToPreZygote() {
4298 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004299 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004300 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004301 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004302}
4303
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004304// Look up classes by hash and descriptor and put all matching ones in the result array.
4305class LookupClassesVisitor : public ClassLoaderVisitor {
4306 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004307 LookupClassesVisitor(const char* descriptor,
4308 size_t hash,
4309 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004310 : descriptor_(descriptor),
4311 hash_(hash),
4312 result_(result) {}
4313
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004314 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004315 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004316 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004317 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004318 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4319 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004320 result_->push_back(klass);
4321 }
4322 }
4323
4324 private:
4325 const char* const descriptor_;
4326 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004327 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004328};
4329
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004330void ClassLinker::LookupClasses(const char* descriptor,
4331 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004332 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004333 Thread* const self = Thread::Current();
4334 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004335 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004336 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004337 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004338 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004339 result.push_back(klass);
4340 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004341 LookupClassesVisitor visitor(descriptor, hash, &result);
4342 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004343}
4344
Alex Lightf1f10492015-10-07 16:08:36 -07004345bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4346 Handle<mirror::Class> klass,
4347 Handle<mirror::Class> supertype) {
4348 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004349 DCHECK(klass != nullptr);
4350 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004351
Alex Lightf1f10492015-10-07 16:08:36 -07004352 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4353 VerifyClass(self, supertype);
4354 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004355
4356 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4357 // The supertype is either verified, or we soft failed at AOT time.
4358 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004359 return true;
4360 }
4361 // If we got this far then we have a hard failure.
4362 std::string error_msg =
4363 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004364 klass->PrettyDescriptor().c_str(),
4365 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004366 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004367 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004368 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004369 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004370 // Set during VerifyClass call (if at all).
4371 self->ClearException();
4372 }
4373 // Change into a verify error.
4374 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004375 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004376 self->GetException()->SetCause(cause.Get());
4377 }
4378 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4379 if (Runtime::Current()->IsAotCompiler()) {
4380 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4381 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004382 // Need to grab the lock to change status.
4383 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004384 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004385 return false;
4386}
4387
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004388verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004389 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004390 {
4391 // TODO: assert that the monitor on the Class is held
4392 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004393
Andreas Gampe884f3b82016-03-30 19:52:58 -07004394 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004395 ClassStatus old_status = klass->GetStatus();
4396 while (old_status == ClassStatus::kVerifying ||
4397 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004398 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004399 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4400 // case we may see the same status again. b/62912904. This is why the check is
4401 // greater or equal.
4402 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004403 << "Class '" << klass->PrettyClass()
4404 << "' performed an illegal verification state transition from " << old_status
4405 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004406 old_status = klass->GetStatus();
4407 }
jeffhao98eacac2011-09-14 16:11:53 -07004408
Andreas Gampe884f3b82016-03-30 19:52:58 -07004409 // The class might already be erroneous, for example at compile time if we attempted to verify
4410 // this class as a parent to another.
4411 if (klass->IsErroneous()) {
4412 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004413 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004414 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004415
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004416 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004417 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004418 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004419 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004420 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004421
4422 // For AOT, don't attempt to re-verify if we have already found we should
4423 // verify at runtime.
4424 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004425 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004426 }
jeffhao98eacac2011-09-14 16:11:53 -07004427
Vladimir Marko2c64a832018-01-04 11:31:56 +00004428 if (klass->GetStatus() == ClassStatus::kResolved) {
4429 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004430 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004431 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004432 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004433 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004434 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004435 }
4436
4437 // Skip verification if disabled.
4438 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004439 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004440 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004441 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004442 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004443 }
4444
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004445 VLOG(class_linker) << "Beginning verification for class: "
4446 << klass->PrettyDescriptor()
4447 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4448
Ian Rogers9ffb0392012-09-10 11:56:50 -07004449 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004450 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004451 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4452 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004453 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004454 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004455 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004456 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004457
Alex Lightf1f10492015-10-07 16:08:36 -07004458 // Verify all default super-interfaces.
4459 //
4460 // (1) Don't bother if the superclass has already had a soft verification failure.
4461 //
4462 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4463 // recursive initialization by themselves. This is because when an interface is initialized
4464 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4465 // but choose not to for an optimization. If the interfaces is being verified due to a class
4466 // initialization (which would need all the default interfaces to be verified) the class code
4467 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004468 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004469 && !klass->IsInterface()) { // See (2)
4470 int32_t iftable_count = klass->GetIfTableCount();
4471 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4472 // Loop through all interfaces this class has defined. It doesn't matter the order.
4473 for (int32_t i = 0; i < iftable_count; i++) {
4474 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004475 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004476 // We only care if we have default interfaces and can skip if we are already verified...
4477 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4478 continue;
4479 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4480 // We had a hard failure while verifying this interface. Just return immediately.
4481 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004482 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004483 } else if (UNLIKELY(!iface->IsVerified())) {
4484 // We softly failed to verify the iface. Stop checking and clean up.
4485 // Put the iface into the supertype handle so we know what caused us to fail.
4486 supertype.Assign(iface.Get());
4487 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004488 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004489 }
4490 }
4491
Alex Lightf1f10492015-10-07 16:08:36 -07004492 // At this point if verification failed, then supertype is the "first" supertype that failed
4493 // verification (without a specific order). If verification succeeded, then supertype is either
4494 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004495 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004496 supertype.Get() == klass->GetSuperClass() ||
4497 !supertype->IsVerified());
4498
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004499 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004500 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004501 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004502 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004503
4504 VLOG(class_linker) << "Class preverified status for class "
4505 << klass->PrettyDescriptor()
4506 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4507 << ": "
4508 << preverified;
4509
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004510 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4511 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004512 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4513 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004514
Ian Rogers62d6c772013-02-27 08:32:07 -08004515 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004516 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004517 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004518 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004519 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004520
4521 // Verification is done, grab the lock again.
4522 ObjectLock<mirror::Class> lock(self, klass);
4523
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004524 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4525 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004526 VLOG(class_linker) << "Soft verification failure in class "
4527 << klass->PrettyDescriptor()
4528 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4529 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004530 }
Ian Rogers1f539342012-10-03 21:09:42 -07004531 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004532 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004533 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004534 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004535 // Even though there were no verifier failures we need to respect whether the super-class and
4536 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004537 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004538 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004539 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004540 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4541 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004542 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004543 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004544 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004545 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004546 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004547 // Soft failures at compile time should be retried at runtime. Soft
4548 // failures at runtime will be handled by slow paths in the generated
4549 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004550 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004551 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004552 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004553 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004554 // As this is a fake verified status, make sure the methods are _not_ marked
4555 // kAccSkipAccessChecks later.
4556 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004557 }
4558 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004559 } else {
David Sehr709b0702016-10-13 09:12:37 -07004560 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004561 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4562 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004563 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004564 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004565 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004566 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004567 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004568 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004569 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004570 // method.
4571 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004572 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004573 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004574
4575 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4576 // Never skip access checks if the verification soft fail is forced.
4577 // Mark the class as having a verification attempt to avoid re-running the verifier.
4578 klass->SetVerificationAttempted();
4579 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004580 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004581 }
Andreas Gampe48498592014-09-10 19:48:05 -07004582 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004583 // Done verifying. Notify the compiler about the verification status, in case the class
4584 // was verified implicitly (eg super class of a compiled class).
4585 if (Runtime::Current()->IsAotCompiler()) {
4586 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4587 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4588 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004589 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004590}
4591
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004592verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4593 Handle<mirror::Class> klass,
4594 verifier::HardFailLogMode log_level,
4595 std::string* error_msg) {
4596 Runtime* const runtime = Runtime::Current();
4597 return verifier::MethodVerifier::VerifyClass(self,
4598 klass.Get(),
4599 runtime->GetCompilerCallbacks(),
4600 runtime->IsAotCompiler(),
4601 log_level,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07004602 Runtime::Current()->GetTargetSdkVersion(),
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004603 error_msg);
4604}
4605
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004606bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004607 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004608 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004609 // If we're compiling, we can only verify the class using the oat file if
4610 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004611 // the compilation unit (app - dependencies). We will let the compiler callback
4612 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004613 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004614 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004615 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004616 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004617 return false;
4618 }
4619 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004620 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004621 return false;
4622 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004623 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004624
Andreas Gampeb40d3612018-06-26 15:49:42 -07004625 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004626 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004627 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004628 return false;
4629 }
4630
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004631 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004632 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004633 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004634 return true;
4635 }
4636 // If we only verified a subset of the classes at compile time, we can end up with classes that
4637 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004638 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004639 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004640 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004641 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004642 // Compile time verification failed with a soft error. Compile time verification can fail
4643 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004644 // class ... {
4645 // Foo x;
4646 // .... () {
4647 // if (...) {
4648 // v1 gets assigned a type of resolved class Foo
4649 // } else {
4650 // v1 gets assigned a type of unresolved class Bar
4651 // }
4652 // iput x = v1
4653 // } }
4654 // when we merge v1 following the if-the-else it results in Conflict
4655 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4656 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4657 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4658 // at compile time).
4659 return false;
4660 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004661 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004662 // Compile time verification failed with a hard error. This is caused by invalid instructions
4663 // in the class. These errors are unrecoverable.
4664 return false;
4665 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004666 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004667 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4668 // not loading the class.
4669 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4670 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004671 return false;
4672 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004673 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004674 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004675 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004676 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004677 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004678}
4679
Alex Light5a559862016-01-29 12:24:48 -08004680void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004681 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004682 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004683 }
4684}
4685
Alex Light5a559862016-01-29 12:24:48 -08004686void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004687 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004688 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004689 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004690 return; // native or abstract method
4691 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004692 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004693 return; // nothing to process
4694 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004695 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004696 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004697 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4698 CatchHandlerIterator iterator(handlers_ptr);
4699 for (; iterator.HasNext(); iterator.Next()) {
4700 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4701 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004702 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004703 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004704 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004705 DCHECK(Thread::Current()->IsExceptionPending());
4706 Thread::Current()->ClearException();
4707 }
4708 }
4709 }
4710 handlers_ptr = iterator.EndDataPointer();
4711 }
4712}
4713
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004714ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4715 jstring name,
4716 jobjectArray interfaces,
4717 jobject loader,
4718 jobjectArray methods,
4719 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004720 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004721
4722 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4723 // code to be executed. We put it up here so we can avoid all the allocations associated with
4724 // creating the class. This can happen with (eg) jit-threads.
4725 if (!self->CanLoadClasses()) {
4726 // Make sure we don't try to load anything, potentially causing an infinite loop.
4727 ObjPtr<mirror::Throwable> pre_allocated =
4728 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4729 self->SetException(pre_allocated);
4730 return nullptr;
4731 }
4732
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004733 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004734 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004735 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004736 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004737 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004738 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004739 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004740 DCHECK(temp_klass->GetClass() != nullptr);
4741 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004742 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4743 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004744 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4745 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4746 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4747 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004748 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004749 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004750 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004751 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004752 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004753 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004754
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004755 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004756 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004757
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004758 // Insert the class before loading the fields as the field roots
4759 // (ArtField::declaring_class_) are only visited from the class
4760 // table. There can't be any suspend points between inserting the
4761 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004762 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004763 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004764
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004765 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004766 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004767 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004768 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004769
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004770 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4771 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004772 ArtField& interfaces_sfield = sfields->At(0);
4773 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004774 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004775 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004776
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004777 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004778 ArtField& throws_sfield = sfields->At(1);
4779 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004780 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004781 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004782
Ian Rogers466bb252011-10-14 03:29:56 -07004783 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004784 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004785
Alex Lighte64300b2015-12-15 15:02:47 -08004786 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004787 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004788 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004789 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004790 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004791
4792 // Create the methods array.
4793 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4794 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004795 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4796 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004797 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004798 self->AssertPendingOOMException();
4799 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004800 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004801 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004802
4803 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004804 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004805
4806 // Create virtual method using specified prototypes.
4807 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004808 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004809 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004810 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004811 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004812 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4813 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004814 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004815
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004816 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004817 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004818 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004819 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004820 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004821
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004822 // At this point the class is loaded. Publish a ClassLoad event.
4823 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4824 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4825
4826 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004827 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004828 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004829 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004830 // Link the fields and virtual methods, creating vtable and iftables.
4831 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004832 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004833 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004834 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004835 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004836 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004837 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004838 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004839 CHECK(temp_klass->IsRetired());
4840 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004841
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004842 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004843 interfaces_sfield.SetObject<false>(
4844 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004845 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004846 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4847 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004848 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004849 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004850
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004851 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4852
Vladimir Marko305c38b2018-02-14 11:50:07 +00004853 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4854 // See also ClassLinker::EnsureInitialized().
4855 if (kBitstringSubtypeCheckEnabled) {
4856 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4857 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4858 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4859 }
4860
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004861 {
4862 // Lock on klass is released. Lock new class object.
4863 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004864 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004865 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004866 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004867
4868 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004869 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004870 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004871 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4872
Ian Rogersc2b44472011-12-14 21:17:17 -08004873 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004874 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4875 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004876 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004877 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004878
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004879 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004880 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004881 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004882 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004883 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004884
4885 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004886 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004887 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004888
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004889 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004890 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004891 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004892 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004893 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004894 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004895}
4896
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004897std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004898 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004899 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004900 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004901 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4902}
4903
Mathieu Chartiere401d142015-04-22 13:56:20 -07004904void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4905 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004906 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4907 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004908
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004909 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4910 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004911 ArtMethod* proxy_constructor =
4912 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004913 DCHECK(proxy_constructor != nullptr)
4914 << "Could not find <init> method in java.lang.reflect.Proxy";
4915
Jeff Haodb8a6642014-08-14 17:18:52 -07004916 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4917 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004918 DCHECK(out != nullptr);
4919 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004920 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004921 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004922 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004923 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4924 kAccPublic |
4925 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004926 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004927
4928 // Set the original constructor method.
4929 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004930}
4931
Mathieu Chartiere401d142015-04-22 13:56:20 -07004932void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004933 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004934 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4935 CHECK_STREQ(np->GetName(), "<init>");
4936 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004937 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004938}
4939
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004940void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004941 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004942 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004943 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004944 DCHECK(out != nullptr);
4945 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004946
Alex Lighte9dd04f2016-03-16 16:09:45 -07004947 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004948 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004949 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4950 // preference to the invocation handler.
4951 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4952 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004953 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4954 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004955 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4956
4957 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4958 // method they copy might (if it's a default method).
4959 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004960
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004961 // Set the original interface method.
4962 out->SetDataPtrSize(prototype, image_pointer_size_);
4963
Ian Rogers466bb252011-10-14 03:29:56 -07004964 // At runtime the method looks like a reference and argument saving method, clone the code
4965 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004966 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004967}
Jesse Wilson95caa792011-10-12 18:14:17 -04004968
Mathieu Chartiere401d142015-04-22 13:56:20 -07004969void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004970 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004971 CHECK(!prototype->IsFinal());
4972 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004973 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004974
4975 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4976 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004977 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004978 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004979}
4980
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004981bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004982 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004983 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004984 return true;
4985 }
4986 if (!can_init_statics) {
4987 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004988 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004989 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004990 return false;
4991 }
4992 // Check if there are encoded static values needing initialization.
4993 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004994 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004995 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004996 if (dex_class_def->static_values_off_ != 0) {
4997 return false;
4998 }
4999 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005000 // If we are a class we need to initialize all interfaces with default methods when we are
5001 // initialized. Check all of them.
5002 if (!klass->IsInterface()) {
5003 size_t num_interfaces = klass->GetIfTableCount();
5004 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005005 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005006 if (iface->HasDefaultMethods() &&
5007 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5008 return false;
5009 }
5010 }
5011 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005012 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005013 if (klass->IsInterface() || !klass->HasSuperClass()) {
5014 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005015 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005016 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005017 if (!can_init_parents && !super_class->IsInitialized()) {
5018 return false;
5019 }
5020 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005021}
5022
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005023bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5024 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005025 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5026
5027 // Are we already initialized and therefore done?
5028 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5029 // an initialized class will never change its state.
5030 if (klass->IsInitialized()) {
5031 return true;
5032 }
5033
5034 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005035 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005036 return false;
5037 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005038
Ian Rogers7b078e82014-09-10 14:44:24 -07005039 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005040 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005041 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005042 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005043
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005044 // Re-check under the lock in case another thread initialized ahead of us.
5045 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005046 return true;
5047 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005048
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005049 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005050 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005051 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005052 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005053 return false;
5054 }
5055
Vladimir Marko72ab6842017-01-20 19:32:50 +00005056 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5057 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005058
5059 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005060 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005061 if (!klass->IsVerified()) {
5062 // We failed to verify, expect either the klass to be erroneous or verification failed at
5063 // compile time.
5064 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005065 // The class is erroneous. This may be a verifier error, or another thread attempted
5066 // verification and/or initialization and failed. We can distinguish those cases by
5067 // whether an exception is already pending.
5068 if (self->IsExceptionPending()) {
5069 // Check that it's a VerifyError.
5070 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005071 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005072 } else {
5073 // Check that another thread attempted initialization.
5074 DCHECK_NE(0, klass->GetClinitThreadId());
5075 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5076 // Need to rethrow the previous failure now.
5077 ThrowEarlierClassFailure(klass.Get(), true);
5078 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005079 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005080 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005081 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005082 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005083 self->AssertNoPendingException();
5084 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005085 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005086 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005087 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005088 } else {
5089 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005090 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005091
5092 // A separate thread could have moved us all the way to initialized. A "simple" example
5093 // involves a subclass of the current class being initialized at the same time (which
5094 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005095 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005096 if (klass->IsInitialized()) {
5097 return true;
5098 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005099 }
5100
Vladimir Marko2c64a832018-01-04 11:31:56 +00005101 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005102 // initializing higher up the stack or another thread has beat us
5103 // to initializing and we need to wait. Either way, this
5104 // invocation of InitializeClass will not be responsible for
5105 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005106 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005107 // Could have got an exception during verification.
5108 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005109 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005110 return false;
5111 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005112 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005113 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005114 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005115 return true;
5116 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005117 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005118 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005119 }
5120
Jeff Haoe2e40342017-07-19 10:45:18 -07005121 // Try to get the oat class's status for this class if the oat file is present. The compiler
5122 // tries to validate superclass descriptors, and writes the result into the oat file.
5123 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5124 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5125 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005126 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005127 const Runtime* runtime = Runtime::Current();
5128 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5129 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5130 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005131 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005132 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005133 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005134 return false;
5135 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005136 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005137
Vladimir Marko2c64a832018-01-04 11:31:56 +00005138 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005139 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005140
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005141 // From here out other threads may observe that we're initializing and so changes of state
5142 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005143 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005144 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005145
5146 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005147 }
5148
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005149 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005150 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005151 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005152 if (!super_class->IsInitialized()) {
5153 CHECK(!super_class->IsInterface());
5154 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005155 StackHandleScope<1> hs(self);
5156 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005157 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005158 if (!super_initialized) {
5159 // The super class was verified ahead of entering initializing, we should only be here if
5160 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005161 // For the case of aot compiler, the super class might also be initializing but we don't
5162 // want to process circular dependencies in pre-compile.
5163 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005164 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005165 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005166 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005167 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005168 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005169 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005170 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005171 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005172 return false;
5173 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005174 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005175 }
5176
Alex Lighteb7c1442015-08-31 13:17:42 -07005177 if (!klass->IsInterface()) {
5178 // Initialize interfaces with default methods for the JLS.
5179 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005180 // Only setup the (expensive) handle scope if we actually need to.
5181 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005182 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005183 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5184 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005185 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005186 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005187 CHECK(handle_scope_iface->IsInterface());
5188 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5189 // We have already done this for this interface. Skip it.
5190 continue;
5191 }
5192 // We cannot just call initialize class directly because we need to ensure that ALL
5193 // interfaces with default methods are initialized. Non-default interface initialization
5194 // will not affect other non-default super-interfaces.
5195 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5196 handle_scope_iface,
5197 can_init_statics,
5198 can_init_parents);
5199 if (!iface_initialized) {
5200 ObjectLock<mirror::Class> lock(self, klass);
5201 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005202 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005203 return false;
5204 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005205 }
5206 }
5207 }
5208
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005209 const size_t num_static_fields = klass->NumStaticFields();
5210 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005211 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005212 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005213 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005214 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005215 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005216
5217 // Eagerly fill in static fields so that the we don't have to do as many expensive
5218 // Class::FindStaticField in ResolveField.
5219 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005220 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005221 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005222 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005223 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005224 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005225 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5226 field,
5227 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5228 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005229 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005230 } else {
5231 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005232 }
5233 }
5234
Vladimir Markoe11dd502017-12-08 14:09:45 +00005235 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5236 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005237 this,
5238 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005239 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005240
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005241 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005242 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005243 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005244 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5245 if (!value_it.HasNext()) {
5246 break;
5247 }
5248 ArtField* art_field = ResolveField(field.GetIndex(),
5249 dex_cache,
5250 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005251 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005252 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005253 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005254 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005255 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005256 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005257 if (self->IsExceptionPending()) {
5258 break;
5259 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005260 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005261 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005262 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005263 }
5264 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005265
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005266
Mathieu Chartierda595be2016-08-10 13:57:39 -07005267 if (!self->IsExceptionPending()) {
5268 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5269 if (clinit != nullptr) {
5270 CHECK(can_init_statics);
5271 JValue result;
5272 clinit->Invoke(self, nullptr, 0, &result, "V");
5273 }
5274 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005275 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005276 uint64_t t1 = NanoTime();
5277
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005278 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005279 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005280 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005281
5282 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005283 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005284 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005285 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005286 } else if (Runtime::Current()->IsTransactionAborted()) {
5287 // The exception thrown when the transaction aborted has been caught and cleared
5288 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005289 VLOG(compiler) << "Return from class initializer of "
5290 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005291 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005292 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005293 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005294 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005295 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005296 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5297 RuntimeStats* thread_stats = self->GetStats();
5298 ++global_stats->class_init_count;
5299 ++thread_stats->class_init_count;
5300 global_stats->class_init_time_ns += (t1 - t0);
5301 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005302 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005303 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005304 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005305 std::string temp;
5306 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005307 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005308 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005309 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005310 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005311 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005312 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005313 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005314}
5315
Alex Lighteb7c1442015-08-31 13:17:42 -07005316// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5317// and perform the initialization only on those interfaces that contain default methods.
5318bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5319 Handle<mirror::Class> iface,
5320 bool can_init_statics,
5321 bool can_init_parents) {
5322 CHECK(iface->IsInterface());
5323 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005324 // Only create the (expensive) handle scope if we need it.
5325 if (UNLIKELY(num_direct_ifaces > 0)) {
5326 StackHandleScope<1> hs(self);
5327 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5328 // First we initialize all of iface's super-interfaces recursively.
5329 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005330 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005331 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005332 if (!super_iface->HasBeenRecursivelyInitialized()) {
5333 // Recursive step
5334 handle_super_iface.Assign(super_iface);
5335 if (!InitializeDefaultInterfaceRecursive(self,
5336 handle_super_iface,
5337 can_init_statics,
5338 can_init_parents)) {
5339 return false;
5340 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005341 }
5342 }
5343 }
5344
5345 bool result = true;
5346 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5347 // initialize if we don't have default methods.
5348 if (iface->HasDefaultMethods()) {
5349 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5350 }
5351
5352 // Mark that this interface has undergone recursive default interface initialization so we know we
5353 // can skip it on any later class initializations. We do this even if we are not a default
5354 // interface since we can still avoid the traversal. This is purely a performance optimization.
5355 if (result) {
5356 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005357 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5358 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5359 // initialization is a performance optimization (to avoid another idempotent visit
5360 // for other implementing classes/interfaces), and can be revisited later.
5361 ObjectTryLock<mirror::Class> lock(self, iface);
5362 if (lock.Acquired()) {
5363 iface->SetRecursivelyInitialized();
5364 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005365 }
5366 return result;
5367}
5368
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005369bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5370 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005371 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005372 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005373 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005374 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005375 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005376 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005377
5378 // When we wake up, repeat the test for init-in-progress. If
5379 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005380 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005381 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005382 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005383 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005384 return false;
5385 }
5386 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005387 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005388 continue;
5389 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005390 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005391 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005392 // Compile time initialization failed.
5393 return false;
5394 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005395 if (klass->IsErroneous()) {
5396 // The caller wants an exception, but it was thrown in a
5397 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005398 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005399 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005400 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005401 return false;
5402 }
5403 if (klass->IsInitialized()) {
5404 return true;
5405 }
David Sehr709b0702016-10-13 09:12:37 -07005406 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005407 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005408 }
Ian Rogers07140832014-09-30 15:43:59 -07005409 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005410}
5411
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005412static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5413 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005414 ArtMethod* method,
5415 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005416 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005417 DCHECK(Thread::Current()->IsExceptionPending());
5418 DCHECK(!m->IsProxyMethod());
5419 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005420 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5421 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005422 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005423 std::string return_type = dex_file->PrettyType(return_type_idx);
5424 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005425 ThrowWrappedLinkageError(klass.Get(),
5426 "While checking class %s method %s signature against %s %s: "
5427 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005428 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5429 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005430 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005431 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005432 return_type.c_str(), class_loader.c_str());
5433}
5434
5435static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5436 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005437 ArtMethod* method,
5438 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005439 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005440 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005441 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005442 DCHECK(Thread::Current()->IsExceptionPending());
5443 DCHECK(!m->IsProxyMethod());
5444 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005445 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5446 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005447 ThrowWrappedLinkageError(klass.Get(),
5448 "While checking class %s method %s signature against %s %s: "
5449 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005450 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5451 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005452 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005453 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005454 index, arg_type.c_str(), class_loader.c_str());
5455}
5456
5457static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5458 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005459 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005460 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005461 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005462 ThrowLinkageError(klass.Get(),
5463 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005464 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5465 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005466 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005467 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005468 error_msg.c_str());
5469}
5470
Ian Rogersb5fb2072014-12-02 17:22:02 -08005471static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005472 Handle<mirror::Class> klass,
5473 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005474 ArtMethod* method1,
5475 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005476 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005477 {
5478 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005479 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005480 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005481 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005482 return false;
5483 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005484 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005485 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005486 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005487 return false;
5488 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005489 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005490 ThrowSignatureMismatch(klass, super_klass, method1,
5491 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005492 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005493 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005494 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005495 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005496 return false;
5497 }
5498 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005499 const dex::TypeList* types1 = method1->GetParameterTypeList();
5500 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005501 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005502 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005503 ThrowSignatureMismatch(klass, super_klass, method1,
5504 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005505 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005506 return false;
5507 }
5508 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005509 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005510 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005511 ThrowSignatureMismatch(klass, super_klass, method1,
5512 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005513 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005514 return false;
5515 }
5516 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005517 }
5518 uint32_t num_types = types1->Size();
5519 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005520 ThrowSignatureMismatch(klass, super_klass, method1,
5521 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005522 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005523 return false;
5524 }
5525 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005526 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005527 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005528 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005529 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005530 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005531 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005532 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005533 return false;
5534 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005535 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005536 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005537 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005538 if (UNLIKELY(other_param_type == nullptr)) {
5539 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005540 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005541 return false;
5542 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005543 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005544 ThrowSignatureMismatch(klass, super_klass, method1,
5545 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5546 i,
David Sehr709b0702016-10-13 09:12:37 -07005547 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005548 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005549 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005550 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005551 return false;
5552 }
5553 }
5554 return true;
5555}
5556
5557
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005558bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005559 if (klass->IsInterface()) {
5560 return true;
5561 }
Ian Rogers151f2212014-05-06 11:27:27 -07005562 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005563 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005564 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005565 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005566 if (klass->HasSuperClass() &&
5567 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005568 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005569 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005570 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5571 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5572 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005573 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5574 klass,
5575 super_klass,
5576 m,
5577 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005578 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005579 return false;
5580 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005581 }
5582 }
5583 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005584 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005585 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5586 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5587 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005588 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005589 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5590 j, image_pointer_size_);
5591 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5592 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005593 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5594 klass,
5595 super_klass,
5596 m,
5597 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005598 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005599 return false;
5600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005601 }
5602 }
5603 }
5604 }
5605 return true;
5606}
5607
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005608bool ClassLinker::EnsureInitialized(Thread* self,
5609 Handle<mirror::Class> c,
5610 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005611 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005612 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005613
Mathieu Chartier524507a2014-08-27 15:28:28 -07005614 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005615 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005616 return true;
5617 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005618 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5619 //
5620 // Ensure the bitstring is initialized before any of the class initialization
5621 // logic occurs. Once a class initializer starts running, objects can
5622 // escape into the heap and use the subtype checking code.
5623 //
5624 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5625 // can be used as a source for the IsSubClass check, and that all ancestors
5626 // of the class are Assigned (can be used as a target for IsSubClass check)
5627 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005628 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005629 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005630 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005631 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5632 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005633 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005634 if (!success) {
5635 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005636 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005637 }
5638 } else {
5639 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005640 }
5641 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005642}
5643
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005644void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5645 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005646 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005647 for (ArtField& field : new_class->GetIFields()) {
5648 if (field.GetDeclaringClass() == temp_class) {
5649 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005650 }
5651 }
5652
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005653 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005654 for (ArtField& field : new_class->GetSFields()) {
5655 if (field.GetDeclaringClass() == temp_class) {
5656 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005657 }
5658 }
5659
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005660 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005661 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005662 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005663 if (method.GetDeclaringClass() == temp_class) {
5664 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005665 }
5666 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005667
5668 // Make sure the remembered set and mod-union tables know that we updated some of the native
5669 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005670 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005671}
5672
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005673void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005674 CHECK(class_loader->GetAllocator() == nullptr);
5675 CHECK(class_loader->GetClassTable() == nullptr);
5676 Thread* const self = Thread::Current();
5677 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005678 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005679 // Create and set the class table.
5680 data.class_table = new ClassTable;
5681 class_loader->SetClassTable(data.class_table);
5682 // Create and set the linear allocator.
5683 data.allocator = Runtime::Current()->CreateLinearAlloc();
5684 class_loader->SetAllocator(data.allocator);
5685 // Add to the list so that we know to free the data later.
5686 class_loaders_.push_back(data);
5687}
5688
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005689ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005690 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005691 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005692 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005693 ClassTable* class_table = class_loader->GetClassTable();
5694 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005695 RegisterClassLoader(class_loader);
5696 class_table = class_loader->GetClassTable();
5697 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005698 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005699 return class_table;
5700}
5701
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005702ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005703 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005704}
5705
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005706static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005707 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005708 while (klass->HasSuperClass()) {
5709 klass = klass->GetSuperClass();
5710 if (klass->ShouldHaveImt()) {
5711 return klass->GetImt(pointer_size);
5712 }
5713 }
5714 return nullptr;
5715}
5716
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005717bool ClassLinker::LinkClass(Thread* self,
5718 const char* descriptor,
5719 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005720 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005721 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005722 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005723
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005724 if (!LinkSuperClass(klass)) {
5725 return false;
5726 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005727 ArtMethod* imt_data[ImTable::kSize];
5728 // If there are any new conflicts compared to super class.
5729 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005730 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005731 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005732 return false;
5733 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005734 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005735 return false;
5736 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005737 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005738 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005739 return false;
5740 }
5741 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005742 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005743
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005744 ImTable* imt = nullptr;
5745 if (klass->ShouldHaveImt()) {
5746 // If there are any new conflicts compared to the super class we can not make a copy. There
5747 // can be cases where both will have a conflict method at the same slot without having the same
5748 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5749 // will possibly create a table that is incorrect for either of the classes.
5750 // Same IMT with new_conflict does not happen very often.
5751 if (!new_conflict) {
5752 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5753 if (super_imt != nullptr) {
5754 bool imt_equals = true;
5755 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5756 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5757 }
5758 if (imt_equals) {
5759 imt = super_imt;
5760 }
5761 }
5762 }
5763 if (imt == nullptr) {
5764 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5765 imt = reinterpret_cast<ImTable*>(
5766 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5767 if (imt == nullptr) {
5768 return false;
5769 }
5770 imt->Populate(imt_data, image_pointer_size_);
5771 }
5772 }
5773
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005774 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5775 // We don't need to retire this class as it has no embedded tables or it was created the
5776 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005777 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005778
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005779 if (klass->ShouldHaveEmbeddedVTable()) {
5780 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005781 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005782 if (klass->ShouldHaveImt()) {
5783 klass->SetImt(imt, image_pointer_size_);
5784 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005785
5786 // Update CHA info based on whether we override methods.
5787 // Have to do this before setting the class as resolved which allows
5788 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005789 if (cha_ != nullptr) {
5790 cha_->UpdateAfterLoadingOf(klass);
5791 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005792
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005793 // This will notify waiters on klass that saw the not yet resolved
5794 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005795 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005796 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005797 } else {
5798 CHECK(!klass->IsResolved());
5799 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005800 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005801 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005802 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5803 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5804 // may not see any references to the target space and clean the card for a class if another
5805 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005806 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005807 klass->SetSFieldsPtrUnchecked(nullptr);
5808 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005809 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005810 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005811 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005812 return false;
5813 }
5814
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005815 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5816 ObjectLock<mirror::Class> lock(self, h_new_class);
5817 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005818
5819 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005820 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005821 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005822 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005823 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005824 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005825 if (class_loader != nullptr) {
5826 // We updated the class in the class table, perform the write barrier so that the GC knows
5827 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005828 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005829 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005830 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005831 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005832 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5833 }
5834 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005835
Mingyao Yang063fc772016-08-02 11:02:54 -07005836 // Update CHA info based on whether we override methods.
5837 // Have to do this before setting the class as resolved which allows
5838 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005839 if (cha_ != nullptr) {
5840 cha_->UpdateAfterLoadingOf(h_new_class);
5841 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005842
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005843 // This will notify waiters on temp class that saw the not yet resolved class in the
5844 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005845 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005846
Vladimir Marko2c64a832018-01-04 11:31:56 +00005847 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005848 // This will notify waiters on new_class that saw the not yet resolved
5849 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005850 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005851 // Return the new class.
5852 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005853 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005854 return true;
5855}
5856
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005857bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005858 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005859 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005860 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5861 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005862 // Check that a class does not inherit from itself directly.
5863 //
5864 // TODO: This is a cheap check to detect the straightforward case
5865 // of a class extending itself (b/28685551), but we should do a
5866 // proper cycle detection on loaded classes, to detect all cases
5867 // of class circularity errors (b/28830038).
5868 if (super_class_idx == class_def.class_idx_) {
5869 ThrowClassCircularityError(klass.Get(),
5870 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005871 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005872 return false;
5873 }
5874
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005875 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005876 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005877 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005878 return false;
5879 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005880 // Verify
5881 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005882 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005883 super_class->PrettyDescriptor().c_str(),
5884 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005885 return false;
5886 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005887 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005888 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005889 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005890 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005891 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005892 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005893 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005894 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005895 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005896 DCHECK(Thread::Current()->IsExceptionPending());
5897 return false;
5898 }
5899 // Verify
5900 if (!klass->CanAccess(interface)) {
5901 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005902 ThrowIllegalAccessError(klass.Get(),
5903 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005904 interface->PrettyDescriptor().c_str(),
5905 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005906 return false;
5907 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005908 }
5909 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005910 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005911 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005912 return true;
5913}
5914
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005915bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005916 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005917 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005918 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5919 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005920 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005921 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005922 return false;
5923 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005924 return true;
5925 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005926 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005927 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005928 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005929 return false;
5930 }
5931 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005932 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005933 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5934 return false;
5935 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005936 if (super->IsFinal()) {
5937 ThrowVerifyError(klass.Get(),
5938 "Superclass %s of %s is declared final",
5939 super->PrettyDescriptor().c_str(),
5940 klass->PrettyDescriptor().c_str());
5941 return false;
5942 }
5943 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005944 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005945 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005946 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005947 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005948 return false;
5949 }
5950 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005951 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005952 super->PrettyDescriptor().c_str(),
5953 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005954 return false;
5955 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005956
Brian Carlstromf3632832014-05-20 15:36:53 -07005957 // Inherit kAccClassIsFinalizable from the superclass in case this
5958 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005959 if (super->IsFinalizable()) {
5960 klass->SetFinalizable();
5961 }
5962
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005963 // Inherit class loader flag form super class.
5964 if (super->IsClassLoaderClass()) {
5965 klass->SetClassLoaderClass();
5966 }
5967
Elliott Hughes2da50362011-10-10 16:57:08 -07005968 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005969 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005970 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005971 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005972 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005973 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005974 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005975 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005976 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005977 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005978 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005979 return false;
5980 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005981
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005982 if (kIsDebugBuild) {
5983 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005984 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005985 CHECK(super->IsResolved());
5986 super = super->GetSuperClass();
5987 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005988 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005989 return true;
5990}
5991
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005992// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005993bool ClassLinker::LinkMethods(Thread* self,
5994 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005995 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005996 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005997 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005998 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005999 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6000 // need to have default methods be in the virtuals array of each class but we don't set that up
6001 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006002 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006003 // Link virtual methods then interface methods.
6004 // We set up the interface lookup table first because we need it to determine if we need to update
6005 // any vtable entries with new default method implementations.
6006 return SetupInterfaceLookupTable(self, klass, interfaces)
6007 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006008 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006009}
6010
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006011// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6012// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6013// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006014class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006015 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006016 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006017 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006018 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6019 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006020 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006021 }
6022
6023 const char* GetName() {
6024 if (name_ == nullptr) {
6025 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6026 }
6027 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006028 }
6029
Mathieu Chartiere401d142015-04-22 13:56:20 -07006030 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006031 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006032 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006033 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006034 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006035 if (dex_file_ == other_dex_file) {
6036 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6037 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006038 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006039 uint32_t other_name_len;
6040 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6041 &other_name_len);
6042 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6043 return false;
6044 }
6045 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6046 }
6047
6048 private:
6049 // Dex file for the method to compare against.
6050 const DexFile* const dex_file_;
6051 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006052 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006053 // Lazily computed name from the dex file's strings.
6054 const char* name_;
6055 // Lazily computed name length.
6056 uint32_t name_len_;
6057};
6058
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006059class LinkVirtualHashTable {
6060 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006061 LinkVirtualHashTable(Handle<mirror::Class> klass,
6062 size_t hash_size,
6063 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006064 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006065 : klass_(klass),
6066 hash_size_(hash_size),
6067 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006068 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006069 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6070 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006071
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006072 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006073 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6074 virtual_method_index, image_pointer_size_);
6075 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006076 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006077 uint32_t index = hash % hash_size_;
6078 // Linear probe until we have an empty slot.
6079 while (hash_table_[index] != invalid_index_) {
6080 if (++index == hash_size_) {
6081 index = 0;
6082 }
6083 }
6084 hash_table_[index] = virtual_method_index;
6085 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006086
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006087 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006088 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006089 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006090 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006091 size_t index = hash % hash_size_;
6092 while (true) {
6093 const uint32_t value = hash_table_[index];
6094 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6095 // the block and can safely assume not found.
6096 if (value == invalid_index_) {
6097 break;
6098 }
6099 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006100 ArtMethod* virtual_method =
6101 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6102 if (comparator->HasSameNameAndSignature(
6103 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006104 hash_table_[index] = removed_index_;
6105 return value;
6106 }
6107 }
6108 if (++index == hash_size_) {
6109 index = 0;
6110 }
6111 }
6112 return GetNotFoundIndex();
6113 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006114
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006115 static uint32_t GetNotFoundIndex() {
6116 return invalid_index_;
6117 }
6118
6119 private:
6120 static const uint32_t invalid_index_;
6121 static const uint32_t removed_index_;
6122
6123 Handle<mirror::Class> klass_;
6124 const size_t hash_size_;
6125 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006126 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006127};
6128
6129const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6130const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6131
Stephen Hines1ddd9132017-02-08 01:51:18 -08006132bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006133 Thread* self,
6134 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006135 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006136 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006137 if (klass->IsInterface()) {
6138 // No vtable.
6139 if (!IsUint<16>(num_virtual_methods)) {
6140 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6141 return false;
6142 }
6143 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006144 // Assign each method an IMT index and set the default flag.
6145 for (size_t i = 0; i < num_virtual_methods; ++i) {
6146 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6147 m->SetMethodIndex(i);
6148 if (!m->IsAbstract()) {
6149 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6150 has_defaults = true;
6151 }
6152 }
6153 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6154 // during initialization. This is a performance optimization. We could simply traverse the
6155 // virtual_methods_ array again during initialization.
6156 if (has_defaults) {
6157 klass->SetHasDefaultMethods();
6158 }
6159 return true;
6160 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006161 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6162 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006163 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006164 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006165 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006166 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006167 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006168 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006169 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006170 return false;
6171 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006172 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006173 vtable->SetElementPtrSize(
6174 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006175 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006176 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6177 // might give us new default methods). If no new interfaces then we can skip the rest since
6178 // the class cannot override any of the super-class's methods. This is required for
6179 // correctness since without it we might not update overridden default method vtable entries
6180 // correctly.
6181 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006182 klass->SetVTable(vtable.Get());
6183 return true;
6184 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006185 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006186 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006187 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006188 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006189 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6190 // might give us new default methods). See comment above.
6191 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006192 klass->SetVTable(super_vtable);
6193 return true;
6194 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006195 vtable = hs.NewHandle(
6196 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006197 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006198 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006199 return false;
6200 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006201 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006202 // How the algorithm works:
6203 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6204 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6205 // method which has not been matched to a vtable method, and j if the virtual method at the
6206 // index overrode the super virtual method at index j.
6207 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6208 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6209 // the need for the initial vtable which we later shrink back down).
6210 // 3. Add non overridden methods to the end of the vtable.
6211 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006212 // + 1 so that even if we only have new default methods we will still be able to use this hash
6213 // table (i.e. it will never have 0 size).
6214 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006215 uint32_t* hash_table_ptr;
6216 std::unique_ptr<uint32_t[]> hash_heap_storage;
6217 if (hash_table_size <= kMaxStackHash) {
6218 hash_table_ptr = reinterpret_cast<uint32_t*>(
6219 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6220 } else {
6221 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6222 hash_table_ptr = hash_heap_storage.get();
6223 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006224 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006225 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006226 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006227 DCHECK(klass->GetVirtualMethodDuringLinking(
6228 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006229 hash_table.Add(i);
6230 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006231 // 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 -07006232 // the hash table.
6233 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006234 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006235 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006236 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6237 super_method->GetAccessFlags())) {
6238 // Continue on to the next method since this one is package private and canot be overridden.
6239 // Before Android 4.1, the package-private method super_method might have been incorrectly
6240 // overridden.
6241 continue;
6242 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006243 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006244 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006245 // We remove the method so that subsequent lookups will be faster by making the hash-map
6246 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006247 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6248 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006249 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6250 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006251 if (super_method->IsFinal()) {
6252 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6253 virtual_method->PrettyMethod().c_str(),
6254 super_method->GetDeclaringClassDescriptor());
6255 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006256 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006257 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6258 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006259 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006260 // We didn't directly override this method but we might through default methods...
6261 // Check for default method update.
6262 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006263 switch (FindDefaultMethodImplementation(self,
6264 super_method,
6265 klass,
6266 /*out*/&default_method)) {
6267 case DefaultMethodSearchResult::kDefaultConflict: {
6268 // A conflict was found looking for default methods. Note this (assuming it wasn't
6269 // pre-existing) in the translations map.
6270 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6271 // Don't generate another conflict method to reduce memory use as an optimization.
6272 default_translations->insert(
6273 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6274 }
6275 break;
6276 }
6277 case DefaultMethodSearchResult::kAbstractFound: {
6278 // No conflict but method is abstract.
6279 // We note that this vtable entry must be made abstract.
6280 if (UNLIKELY(!super_method->IsAbstract())) {
6281 default_translations->insert(
6282 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6283 }
6284 break;
6285 }
6286 case DefaultMethodSearchResult::kDefaultFound: {
6287 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6288 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6289 // Found a default method implementation that is new.
6290 // TODO Refactor this add default methods to virtuals here and not in
6291 // LinkInterfaceMethods maybe.
6292 // The problem is default methods might override previously present
6293 // default-method or miranda-method vtable entries from the superclass.
6294 // Unfortunately we need these to be entries in this class's virtuals. We do not
6295 // give these entries there until LinkInterfaceMethods so we pass this map around
6296 // to let it know which vtable entries need to be updated.
6297 // Make a note that vtable entry j must be updated, store what it needs to be updated
6298 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6299 // then.
6300 default_translations->insert(
6301 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006302 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6303 << " overridden by default "
6304 << default_method->PrettyMethod()
6305 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006306 }
6307 break;
6308 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006309 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006310 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006311 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006312 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006313 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006314 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006315 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006316 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6317 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006318 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006319 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006320 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006321 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006322 local_method->SetMethodIndex(actual_count);
6323 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006324 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006325 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006326 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006327 return false;
6328 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006329 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006330 CHECK_LE(actual_count, max_count);
6331 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006332 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006333 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006334 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006335 return false;
6336 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006337 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006338 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006339 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006340 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006341 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006342 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6343 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006344 return false;
6345 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006346 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006347 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006348 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006349 return false;
6350 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006351 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006352 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6353 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006354 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006355 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006356 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006357 }
6358 return true;
6359}
6360
Alex Light9139e002015-10-09 15:59:48 -07006361// Determine if the given iface has any subinterface in the given list that declares the method
6362// specified by 'target'.
6363//
6364// Arguments
6365// - self: The thread we are running on
6366// - target: A comparator that will match any method that overrides the method we are checking for
6367// - iftable: The iftable we are searching for an overriding method on.
6368// - ifstart: The index of the interface we are checking to see if anything overrides
6369// - iface: The interface we are checking to see if anything overrides.
6370// - image_pointer_size:
6371// The image pointer size.
6372//
6373// Returns
6374// - True: There is some method that matches the target comparator defined in an interface that
6375// is a subtype of iface.
6376// - False: There is no method that matches the target comparator in any interface that is a subtype
6377// of iface.
6378static bool ContainsOverridingMethodOf(Thread* self,
6379 MethodNameAndSignatureComparator& target,
6380 Handle<mirror::IfTable> iftable,
6381 size_t ifstart,
6382 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006383 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006384 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006385 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006386 DCHECK(iface != nullptr);
6387 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006388 DCHECK_GE(ifstart, 0u);
6389 DCHECK_LT(ifstart, iftable->Count());
6390 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6391 DCHECK(iface->IsInterface());
6392
6393 size_t iftable_count = iftable->Count();
6394 StackHandleScope<1> hs(self);
6395 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6396 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6397 // Skip ifstart since our current interface obviously cannot override itself.
6398 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006399 // Iterate through every method on this interface. The order does not matter.
6400 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006401 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006402 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006403 // Check if the i'th interface is a subtype of this one.
6404 if (iface->IsAssignableFrom(current_iface.Get())) {
6405 return true;
6406 }
6407 break;
6408 }
6409 }
6410 }
6411 return false;
6412}
6413
Alex Lighteb7c1442015-08-31 13:17:42 -07006414// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006415// out_default_method and returns kDefaultFound on success. If no default method was found return
6416// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6417// default_method conflict) it will return kDefaultConflict.
6418ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6419 Thread* self,
6420 ArtMethod* target_method,
6421 Handle<mirror::Class> klass,
6422 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006423 DCHECK(self != nullptr);
6424 DCHECK(target_method != nullptr);
6425 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006426
6427 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006428
6429 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6430 // table. This lets us walk the table backwards when searching for default methods. The first one
6431 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6432 // track of it and then continue checking all other interfaces, since we need to throw an error if
6433 // we encounter conflicting default method implementations (one is not a subtype of the other).
6434 //
6435 // The order of unrelated interfaces does not matter and is not defined.
6436 size_t iftable_count = klass->GetIfTableCount();
6437 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006438 // No interfaces. We have already reset out to null so just return kAbstractFound.
6439 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006440 }
6441
Alex Light9139e002015-10-09 15:59:48 -07006442 StackHandleScope<3> hs(self);
6443 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006444 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006445 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006446 MethodNameAndSignatureComparator target_name_comparator(
6447 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6448 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006449 for (size_t k = iftable_count; k != 0; ) {
6450 --k;
6451
Alex Lighteb7c1442015-08-31 13:17:42 -07006452 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006453
6454 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006455 // Iterate through every declared method on this interface. The order does not matter.
6456 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6457 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006458 // Skip abstract methods and methods with different names.
6459 if (current_method->IsAbstract() ||
6460 !target_name_comparator.HasSameNameAndSignature(
6461 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6462 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006463 } else if (!current_method->IsPublic()) {
6464 // The verifier should have caught the non-public method for dex version 37. Just warn and
6465 // skip it since this is from before default-methods so we don't really need to care that it
6466 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006467 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6468 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006469 << "This will be a fatal error in subsequent versions of android. "
6470 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006471 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006472 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006473 // We have multiple default impls of the same method. This is a potential default conflict.
6474 // We need to check if this possibly conflicting method is either a superclass of the chosen
6475 // default implementation or is overridden by a non-default interface method. In either case
6476 // there is no conflict.
6477 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6478 !ContainsOverridingMethodOf(self,
6479 target_name_comparator,
6480 iftable,
6481 k,
6482 iface,
6483 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006484 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006485 << current_method->PrettyMethod() << " and "
6486 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6487 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006488 *out_default_method = nullptr;
6489 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006490 } else {
6491 break; // Continue checking at the next interface.
6492 }
6493 } else {
Alex Light9139e002015-10-09 15:59:48 -07006494 // chosen_iface == null
6495 if (!ContainsOverridingMethodOf(self,
6496 target_name_comparator,
6497 iftable,
6498 k,
6499 iface,
6500 image_pointer_size_)) {
6501 // Don't set this as the chosen interface if something else is overriding it (because that
6502 // other interface would be potentially chosen instead if it was default). If the other
6503 // interface was abstract then we wouldn't select this interface as chosen anyway since
6504 // the abstract method masks it.
6505 *out_default_method = current_method;
6506 chosen_iface.Assign(iface.Get());
6507 // We should now finish traversing the graph to find if we have default methods that
6508 // conflict.
6509 } else {
David Sehr709b0702016-10-13 09:12:37 -07006510 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6511 << "' was "
6512 << "skipped because it was overridden by an abstract method in a "
6513 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006514 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006515 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006516 break;
6517 }
6518 }
Alex Light9139e002015-10-09 15:59:48 -07006519 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006520 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6521 << "' selected "
6522 << "as the implementation for '" << target_method->PrettyMethod()
6523 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006524 return DefaultMethodSearchResult::kDefaultFound;
6525 } else {
6526 return DefaultMethodSearchResult::kAbstractFound;
6527 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006528}
6529
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006530ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006531 ArtMethod* conflict_method,
6532 ArtMethod* interface_method,
6533 ArtMethod* method,
6534 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006535 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006536 Runtime* const runtime = Runtime::Current();
6537 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6538 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6539
6540 // Create a new entry if the existing one is the shared conflict method.
6541 ArtMethod* new_conflict_method = new_entry
6542 ? runtime->CreateImtConflictMethod(linear_alloc)
6543 : conflict_method;
6544
6545 // Allocate a new table. Note that we will leak this table at the next conflict,
6546 // but that's a tradeoff compared to making the table fixed size.
6547 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006548 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6549 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006550 if (data == nullptr) {
6551 LOG(ERROR) << "Failed to allocate conflict table";
6552 return conflict_method;
6553 }
6554 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6555 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006556 method,
6557 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006558
6559 // Do a fence to ensure threads see the data in the table before it is assigned
6560 // to the conflict method.
6561 // Note that there is a race in the presence of multiple threads and we may leak
6562 // memory from the LinearAlloc, but that's a tradeoff compared to using
6563 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006564 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006565 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006566 return new_conflict_method;
6567}
6568
Vladimir Marko921094a2017-01-12 18:37:06 +00006569bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6570 Handle<mirror::Class> klass,
6571 Handle<mirror::IfTable> iftable) {
6572 DCHECK(!klass->IsInterface());
6573 const bool has_superclass = klass->HasSuperClass();
6574 const bool extend_super_iftable = has_superclass;
6575 const size_t ifcount = klass->GetIfTableCount();
6576 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6577 for (size_t i = 0; i < ifcount; ++i) {
6578 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6579 if (num_methods > 0) {
6580 const bool is_super = i < super_ifcount;
6581 // This is an interface implemented by a super-class. Therefore we can just copy the method
6582 // array from the superclass.
6583 const bool super_interface = is_super && extend_super_iftable;
6584 ObjPtr<mirror::PointerArray> method_array;
6585 if (super_interface) {
6586 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6587 DCHECK(if_table != nullptr);
6588 DCHECK(if_table->GetMethodArray(i) != nullptr);
6589 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006590 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6591 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006592 } else {
6593 method_array = AllocPointerArray(self, num_methods);
6594 }
6595 if (UNLIKELY(method_array == nullptr)) {
6596 self->AssertPendingOOMException();
6597 return false;
6598 }
6599 iftable->SetMethodArray(i, method_array);
6600 }
6601 }
6602 return true;
6603}
6604
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006605void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6606 ArtMethod* imt_conflict_method,
6607 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006608 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006609 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006610 // Place method in imt if entry is empty, place conflict otherwise.
6611 if (*imt_ref == unimplemented_method) {
6612 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006613 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006614 // If we are not a conflict and we have the same signature and name as the imt
6615 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006616 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6617 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006618 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006619 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006620 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006621 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006622 *imt_ref = current_method;
6623 } else {
Alex Light9139e002015-10-09 15:59:48 -07006624 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006625 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006626 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006627 } else {
6628 // Place the default conflict method. Note that there may be an existing conflict
6629 // method in the IMT, but it could be one tailored to the super class, with a
6630 // specific ImtConflictTable.
6631 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006632 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006633 }
6634}
6635
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006636void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006637 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6638 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006639 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006640 Runtime* const runtime = Runtime::Current();
6641 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6642 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006643 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006644 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006645 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006646 FillIMTFromIfTable(klass->GetIfTable(),
6647 unimplemented_method,
6648 conflict_method,
6649 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006650 /*create_conflict_tables=*/true,
6651 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006652 &new_conflict,
6653 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006654 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006655 if (!klass->ShouldHaveImt()) {
6656 return;
6657 }
6658 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6659 // we can just use the same pointer.
6660 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006661 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006662 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6663 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6664 bool same = true;
6665 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6666 ArtMethod* method = imt_data[i];
6667 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6668 if (method != super_method) {
6669 bool is_conflict_table = method->IsRuntimeMethod() &&
6670 method != unimplemented_method &&
6671 method != conflict_method;
6672 // Verify conflict contents.
6673 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6674 super_method != unimplemented_method &&
6675 super_method != conflict_method;
6676 if (!is_conflict_table || !super_conflict_table) {
6677 same = false;
6678 } else {
6679 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6680 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6681 same = same && table1->Equals(table2, image_pointer_size_);
6682 }
6683 }
6684 }
6685 if (same) {
6686 imt = super_imt;
6687 }
6688 }
6689 if (imt == nullptr) {
6690 imt = klass->GetImt(image_pointer_size_);
6691 DCHECK(imt != nullptr);
6692 imt->Populate(imt_data, image_pointer_size_);
6693 } else {
6694 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006695 }
6696}
6697
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006698ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6699 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006700 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006701 void* data = linear_alloc->Alloc(Thread::Current(),
6702 ImtConflictTable::ComputeSize(count,
6703 image_pointer_size));
6704 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6705}
6706
6707ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6708 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6709}
6710
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006711void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006712 ArtMethod* unimplemented_method,
6713 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006714 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006715 bool create_conflict_tables,
6716 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006717 /*out*/bool* new_conflict,
6718 /*out*/ArtMethod** imt) {
6719 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006720 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006721 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006722 const size_t num_virtuals = interface->NumVirtualMethods();
6723 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6724 // Virtual methods can be larger than the if table methods if there are default methods.
6725 DCHECK_GE(num_virtuals, method_array_count);
6726 if (kIsDebugBuild) {
6727 if (klass->IsInterface()) {
6728 DCHECK_EQ(method_array_count, 0u);
6729 } else {
6730 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6731 }
6732 }
6733 if (method_array_count == 0) {
6734 continue;
6735 }
6736 auto* method_array = if_table->GetMethodArray(i);
6737 for (size_t j = 0; j < method_array_count; ++j) {
6738 ArtMethod* implementation_method =
6739 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6740 if (ignore_copied_methods && implementation_method->IsCopied()) {
6741 continue;
6742 }
6743 DCHECK(implementation_method != nullptr);
6744 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6745 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6746 // or interface methods in the IMT here they will not create extra conflicts since we compare
6747 // names and signatures in SetIMTRef.
6748 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006749 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006750
6751 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6752 // the same implementation method, keep track of this to avoid creating a conflict table in
6753 // this case.
6754
6755 // Conflict table size for each IMT slot.
6756 ++conflict_counts[imt_index];
6757
6758 SetIMTRef(unimplemented_method,
6759 imt_conflict_method,
6760 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006761 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006762 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006763 }
6764 }
6765
6766 if (create_conflict_tables) {
6767 // Create the conflict tables.
6768 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006769 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006770 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006771 if (imt[i] == imt_conflict_method) {
6772 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6773 if (new_table != nullptr) {
6774 ArtMethod* new_conflict_method =
6775 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6776 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6777 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006778 } else {
6779 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006780 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006781 }
6782 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006783 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006784 }
6785 }
6786
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006787 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006788 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006789 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6790 // Virtual methods can be larger than the if table methods if there are default methods.
6791 if (method_array_count == 0) {
6792 continue;
6793 }
6794 auto* method_array = if_table->GetMethodArray(i);
6795 for (size_t j = 0; j < method_array_count; ++j) {
6796 ArtMethod* implementation_method =
6797 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6798 if (ignore_copied_methods && implementation_method->IsCopied()) {
6799 continue;
6800 }
6801 DCHECK(implementation_method != nullptr);
6802 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006803 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006804 if (!imt[imt_index]->IsRuntimeMethod() ||
6805 imt[imt_index] == unimplemented_method ||
6806 imt[imt_index] == imt_conflict_method) {
6807 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006808 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006809 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6810 const size_t num_entries = table->NumEntries(image_pointer_size_);
6811 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6812 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006813 }
6814 }
6815 }
6816}
6817
Alex Lighteb7c1442015-08-31 13:17:42 -07006818// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6819// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006820static bool NotSubinterfaceOfAny(
6821 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6822 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006823 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006824 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006825 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006826 for (ObjPtr<mirror::Class> c : classes) {
6827 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006828 return false;
6829 }
6830 }
6831 return true;
6832}
6833
6834// Fills in and flattens the interface inheritance hierarchy.
6835//
6836// By the end of this function all interfaces in the transitive closure of to_process are added to
6837// the iftable and every interface precedes all of its sub-interfaces in this list.
6838//
6839// all I, J: Interface | I <: J implies J precedes I
6840//
6841// (note A <: B means that A is a subtype of B)
6842//
6843// This returns the total number of items in the iftable. The iftable might be resized down after
6844// this call.
6845//
6846// We order this backwards so that we do not need to reorder superclass interfaces when new
6847// interfaces are added in subclass's interface tables.
6848//
6849// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6850// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6851// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6852// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006853static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006854 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006855 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006856 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006857 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006858 // This is the set of all class's already in the iftable. Used to make checking if a class has
6859 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006860 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006861 // The first super_ifcount elements are from the superclass. We note that they are already added.
6862 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006863 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006864 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6865 classes_in_iftable.insert(iface);
6866 }
6867 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006868 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006869 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6870 // At this point in the loop current-iface-list has the invariant that:
6871 // for every pair of interfaces I,J within it:
6872 // if index_of(I) < index_of(J) then I is not a subtype of J
6873
6874 // If we have already seen this element then all of its super-interfaces must already be in the
6875 // current-iface-list so we can skip adding it.
6876 if (!ContainsElement(classes_in_iftable, interface)) {
6877 // We haven't seen this interface so add all of its super-interfaces onto the
6878 // current-iface-list, skipping those already on it.
6879 int32_t ifcount = interface->GetIfTableCount();
6880 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006881 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006882 if (!ContainsElement(classes_in_iftable, super_interface)) {
6883 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6884 classes_in_iftable.insert(super_interface);
6885 iftable->SetInterface(filled_ifcount, super_interface);
6886 filled_ifcount++;
6887 }
6888 }
6889 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6890 // Place this interface onto the current-iface-list after all of its super-interfaces.
6891 classes_in_iftable.insert(interface);
6892 iftable->SetInterface(filled_ifcount, interface);
6893 filled_ifcount++;
6894 } else if (kIsDebugBuild) {
6895 // Check all super-interfaces are already in the list.
6896 int32_t ifcount = interface->GetIfTableCount();
6897 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006898 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006899 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006900 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6901 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006902 }
6903 }
6904 }
6905 if (kIsDebugBuild) {
6906 // Check that the iftable is ordered correctly.
6907 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006908 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006909 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006910 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006911 // !(if_a <: if_b)
6912 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006913 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6914 << ") extends "
6915 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006916 << "interface list.";
6917 }
6918 }
6919 }
6920 return filled_ifcount;
6921}
6922
6923bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6924 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6925 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006926 const bool has_superclass = klass->HasSuperClass();
6927 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006928 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006929 const size_t num_interfaces =
6930 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006931 if (num_interfaces == 0) {
6932 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006933 if (LIKELY(has_superclass)) {
6934 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6935 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006936 // Class implements no interfaces.
6937 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006938 return true;
6939 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006940 // Class implements same interfaces as parent, are any of these not marker interfaces?
6941 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006942 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006943 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006944 if (super_iftable->GetMethodArrayCount(i) > 0) {
6945 has_non_marker_interface = true;
6946 break;
6947 }
6948 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006949 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006950 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006951 klass->SetIfTable(super_iftable);
6952 return true;
6953 }
6954 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006955 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006956 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006957 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006958 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006959 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006960 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006961 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006962 if (UNLIKELY(!interface->IsInterface())) {
6963 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006964 ThrowIncompatibleClassChangeError(klass.Get(),
6965 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006966 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006967 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6968 return false;
6969 }
6970 ifcount += interface->GetIfTableCount();
6971 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006972 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006973 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006974 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006975 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006976 return false;
6977 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006978 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006979 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006980 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006981 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006982 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006983 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006984 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006985 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006986
6987 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6988 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6989 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006990 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006991
6992 size_t new_ifcount;
6993 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006994 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01006995 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07006996 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006997 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006998 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01006999 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007000 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007001
7002 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007003 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007004
Ian Rogers7b078e82014-09-10 14:44:24 -07007005 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007006
Ian Rogersb52b01a2012-01-12 17:01:38 -08007007 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007008 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007009 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007010 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007011 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007012 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007013 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007014 return false;
7015 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007016 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007017 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007018 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007019 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007020 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007021 return true;
7022}
7023
Alex Light1f3925d2016-09-07 12:04:20 -07007024// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7025// of methods must be unique.
7026static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7027 return nullptr;
7028}
7029
7030template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007031static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007032 const ScopedArenaVector<ArtMethod*>& list,
7033 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007034 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007035 for (ArtMethod* method : list) {
7036 if (cmp.HasSameNameAndSignature(method)) {
7037 return method;
7038 }
7039 }
Alex Light1f3925d2016-09-07 12:04:20 -07007040 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007041}
7042
Alex Light1f3925d2016-09-07 12:04:20 -07007043// Check that all vtable entries are present in this class's virtuals or are the same as a
7044// superclasses vtable entry.
7045static void CheckClassOwnsVTableEntries(Thread* self,
7046 Handle<mirror::Class> klass,
7047 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007048 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007049 StackHandleScope<2> hs(self);
7050 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007051 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007052 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007053 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007054 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7055 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7056 CHECK(m != nullptr);
7057
Alex Lighta41a30782017-03-29 11:33:19 -07007058 if (m->GetMethodIndexDuringLinking() != i) {
7059 LOG(WARNING) << m->PrettyMethod()
7060 << " has an unexpected method index for its spot in the vtable for class"
7061 << klass->PrettyClass();
7062 }
Alex Lighte64300b2015-12-15 15:02:47 -08007063 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7064 auto is_same_method = [m] (const ArtMethod& meth) {
7065 return &meth == m;
7066 };
Alex Light3f980532017-03-17 15:10:32 -07007067 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7068 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7069 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7070 << klass->PrettyClass() << " or any of its superclasses!";
7071 }
Alex Lighte64300b2015-12-15 15:02:47 -08007072 }
7073}
7074
Alex Light1f3925d2016-09-07 12:04:20 -07007075// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7076// method is overridden in a subclass.
7077static void CheckVTableHasNoDuplicates(Thread* self,
7078 Handle<mirror::Class> klass,
7079 PointerSize pointer_size)
7080 REQUIRES_SHARED(Locks::mutator_lock_) {
7081 StackHandleScope<1> hs(self);
7082 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7083 int32_t num_entries = vtable->GetLength();
7084 for (int32_t i = 0; i < num_entries; i++) {
7085 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7086 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
7087 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7088 vtable_entry->GetAccessFlags())) {
7089 continue;
7090 }
7091 MethodNameAndSignatureComparator name_comparator(
7092 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07007093 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07007094 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07007095 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
7096 other_entry->GetAccessFlags())) {
7097 continue;
7098 }
Alex Light3f980532017-03-17 15:10:32 -07007099 if (vtable_entry == other_entry ||
7100 name_comparator.HasSameNameAndSignature(
7101 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
7102 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7103 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
7104 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
7105 << other_entry->PrettyMethod() << " (0x" << std::hex
7106 << reinterpret_cast<uintptr_t>(other_entry) << ")";
7107 }
Alex Light1f3925d2016-09-07 12:04:20 -07007108 }
7109 }
7110}
7111
7112static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7113 REQUIRES_SHARED(Locks::mutator_lock_) {
7114 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7115 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7116}
7117
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007118void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7119 ArtMethod* unimplemented_method,
7120 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007121 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007122 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007123 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007124 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007125 if (super_class->ShouldHaveImt()) {
7126 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7127 for (size_t i = 0; i < ImTable::kSize; ++i) {
7128 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007129 }
7130 } else {
7131 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007132 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007133 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007134 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007135 FillIMTFromIfTable(if_table,
7136 unimplemented_method,
7137 imt_conflict_method,
7138 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007139 /*create_conflict_tables=*/false,
7140 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007141 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007142 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007143 }
7144 }
7145}
7146
Vladimir Marko921094a2017-01-12 18:37:06 +00007147class ClassLinker::LinkInterfaceMethodsHelper {
7148 public:
7149 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7150 Handle<mirror::Class> klass,
7151 Thread* self,
7152 Runtime* runtime)
7153 : class_linker_(class_linker),
7154 klass_(klass),
7155 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7156 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7157 self_(self),
7158 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7159 allocator_(&stack_),
7160 default_conflict_methods_(allocator_.Adapter()),
7161 overriding_default_conflict_methods_(allocator_.Adapter()),
7162 miranda_methods_(allocator_.Adapter()),
7163 default_methods_(allocator_.Adapter()),
7164 overriding_default_methods_(allocator_.Adapter()),
7165 move_table_(allocator_.Adapter()) {
7166 }
7167
7168 ArtMethod* FindMethod(ArtMethod* interface_method,
7169 MethodNameAndSignatureComparator& interface_name_comparator,
7170 ArtMethod* vtable_impl)
7171 REQUIRES_SHARED(Locks::mutator_lock_);
7172
7173 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7174 MethodNameAndSignatureComparator& interface_name_comparator)
7175 REQUIRES_SHARED(Locks::mutator_lock_);
7176
7177 bool HasNewVirtuals() const {
7178 return !(miranda_methods_.empty() &&
7179 default_methods_.empty() &&
7180 overriding_default_methods_.empty() &&
7181 overriding_default_conflict_methods_.empty() &&
7182 default_conflict_methods_.empty());
7183 }
7184
7185 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7186
7187 ObjPtr<mirror::PointerArray> UpdateVtable(
7188 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7189 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7190
7191 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7192
7193 void UpdateIMT(ArtMethod** out_imt);
7194
7195 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7196 if (kIsDebugBuild) {
7197 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7198 // Check that there are no stale methods are in the dex cache array.
7199 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7200 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007201 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7202 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007203 CHECK(move_table_.find(m) == move_table_.end() ||
7204 // The original versions of copied methods will still be present so allow those too.
7205 // Note that if the first check passes this might fail to GetDeclaringClass().
7206 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7207 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7208 [m] (ArtMethod& meth) {
7209 return &meth == m;
7210 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7211 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7212 }
7213 }
7214 }
7215
7216 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7217 LengthPrefixedArray<ArtMethod>* methods) {
7218 if (kIsDebugBuild) {
7219 CHECK(methods != nullptr);
7220 // Put some random garbage in old methods to help find stale pointers.
7221 if (methods != old_methods && old_methods != nullptr) {
7222 // Need to make sure the GC is not running since it could be scanning the methods we are
7223 // about to overwrite.
7224 ScopedThreadStateChange tsc(self_, kSuspended);
7225 gc::ScopedGCCriticalSection gcs(self_,
7226 gc::kGcCauseClassLinker,
7227 gc::kCollectorTypeClassLinker);
7228 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7229 method_size_,
7230 method_alignment_);
7231 memset(old_methods, 0xFEu, old_size);
7232 }
7233 }
7234 }
7235
7236 private:
7237 size_t NumberOfNewVirtuals() const {
7238 return miranda_methods_.size() +
7239 default_methods_.size() +
7240 overriding_default_conflict_methods_.size() +
7241 overriding_default_methods_.size() +
7242 default_conflict_methods_.size();
7243 }
7244
7245 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7246 return !klass_->IsInterface();
7247 }
7248
7249 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7250 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7251 << "Interfaces should only have default-conflict methods appended to them.";
7252 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7253 << miranda_methods_.size()
7254 << " default_methods=" << default_methods_.size()
7255 << " overriding_default_methods=" << overriding_default_methods_.size()
7256 << " default_conflict_methods=" << default_conflict_methods_.size()
7257 << " overriding_default_conflict_methods="
7258 << overriding_default_conflict_methods_.size();
7259 }
7260
7261 ClassLinker* class_linker_;
7262 Handle<mirror::Class> klass_;
7263 size_t method_alignment_;
7264 size_t method_size_;
7265 Thread* const self_;
7266
7267 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7268 // the virtual methods array.
7269 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7270 // during cross compilation.
7271 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7272 ArenaStack stack_;
7273 ScopedArenaAllocator allocator_;
7274
7275 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7276 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7277 ScopedArenaVector<ArtMethod*> miranda_methods_;
7278 ScopedArenaVector<ArtMethod*> default_methods_;
7279 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7280
7281 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7282};
7283
7284ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7285 ArtMethod* interface_method,
7286 MethodNameAndSignatureComparator& interface_name_comparator,
7287 ArtMethod* vtable_impl) {
7288 ArtMethod* current_method = nullptr;
7289 switch (class_linker_->FindDefaultMethodImplementation(self_,
7290 interface_method,
7291 klass_,
7292 /*out*/&current_method)) {
7293 case DefaultMethodSearchResult::kDefaultConflict: {
7294 // Default method conflict.
7295 DCHECK(current_method == nullptr);
7296 ArtMethod* default_conflict_method = nullptr;
7297 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7298 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7299 default_conflict_method = vtable_impl;
7300 } else {
7301 // See if we already have a conflict method for this method.
7302 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7303 interface_name_comparator,
7304 default_conflict_methods_,
7305 overriding_default_conflict_methods_);
7306 if (LIKELY(preexisting_conflict != nullptr)) {
7307 // We already have another conflict we can reuse.
7308 default_conflict_method = preexisting_conflict;
7309 } else {
7310 // Note that we do this even if we are an interface since we need to create this and
7311 // cannot reuse another classes.
7312 // Create a new conflict method for this to use.
7313 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7314 new(default_conflict_method) ArtMethod(interface_method,
7315 class_linker_->GetImagePointerSize());
7316 if (vtable_impl == nullptr) {
7317 // Save the conflict method. We need to add it to the vtable.
7318 default_conflict_methods_.push_back(default_conflict_method);
7319 } else {
7320 // Save the conflict method but it is already in the vtable.
7321 overriding_default_conflict_methods_.push_back(default_conflict_method);
7322 }
7323 }
7324 }
7325 current_method = default_conflict_method;
7326 break;
7327 } // case kDefaultConflict
7328 case DefaultMethodSearchResult::kDefaultFound: {
7329 DCHECK(current_method != nullptr);
7330 // Found a default method.
7331 if (vtable_impl != nullptr &&
7332 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7333 // We found a default method but it was the same one we already have from our
7334 // superclass. Don't bother adding it to our vtable again.
7335 current_method = vtable_impl;
7336 } else if (LIKELY(FillTables())) {
7337 // Interfaces don't need to copy default methods since they don't have vtables.
7338 // Only record this default method if it is new to save space.
7339 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7340 // would make lookup for interface super much faster. (We would only need to scan
7341 // the iftable to find if there is a NSME or AME.)
7342 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7343 default_methods_,
7344 overriding_default_methods_);
7345 if (old == nullptr) {
7346 // We found a default method implementation and there were no conflicts.
7347 if (vtable_impl == nullptr) {
7348 // Save the default method. We need to add it to the vtable.
7349 default_methods_.push_back(current_method);
7350 } else {
7351 // Save the default method but it is already in the vtable.
7352 overriding_default_methods_.push_back(current_method);
7353 }
7354 } else {
7355 CHECK(old == current_method) << "Multiple default implementations selected!";
7356 }
7357 }
7358 break;
7359 } // case kDefaultFound
7360 case DefaultMethodSearchResult::kAbstractFound: {
7361 DCHECK(current_method == nullptr);
7362 // Abstract method masks all defaults.
7363 if (vtable_impl != nullptr &&
7364 vtable_impl->IsAbstract() &&
7365 !vtable_impl->IsDefaultConflicting()) {
7366 // We need to make this an abstract method but the version in the vtable already is so
7367 // don't do anything.
7368 current_method = vtable_impl;
7369 }
7370 break;
7371 } // case kAbstractFound
7372 }
7373 return current_method;
7374}
7375
7376ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7377 ArtMethod* interface_method,
7378 MethodNameAndSignatureComparator& interface_name_comparator) {
7379 // Find out if there is already a miranda method we can use.
7380 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7381 miranda_methods_);
7382 if (miranda_method == nullptr) {
7383 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7384 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7385 CHECK(miranda_method != nullptr);
7386 // Point the interface table at a phantom slot.
7387 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7388 miranda_methods_.push_back(miranda_method);
7389 }
7390 return miranda_method;
7391}
7392
7393void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7394 LogNewVirtuals();
7395
7396 const size_t old_method_count = klass_->NumMethods();
7397 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7398 DCHECK_NE(old_method_count, new_method_count);
7399
7400 // Attempt to realloc to save RAM if possible.
7401 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7402 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7403 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7404 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7405 // CopyFrom has internal read barriers.
7406 //
7407 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7408 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7409 method_size_,
7410 method_alignment_);
7411 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7412 method_size_,
7413 method_alignment_);
7414 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7415 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007416 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007417 self_, old_methods, old_methods_ptr_size, new_size));
7418 CHECK(methods != nullptr); // Native allocation failure aborts.
7419
7420 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7421 if (methods != old_methods) {
7422 // Maps from heap allocated miranda method to linear alloc miranda method.
7423 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7424 // Copy over the old methods.
7425 for (auto& m : klass_->GetMethods(pointer_size)) {
7426 move_table_.emplace(&m, &*out);
7427 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7428 // barriers when it copies.
7429 out->CopyFrom(&m, pointer_size);
7430 ++out;
7431 }
7432 }
7433 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7434 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7435 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007436 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7437 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007438 ArtMethod& new_method = *out;
7439 new_method.CopyFrom(mir_method, pointer_size);
7440 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7441 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7442 << "Miranda method should be abstract!";
7443 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007444 // Update the entry in the method array, as the array will be used for future lookups,
7445 // where thread suspension is allowed.
7446 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7447 // would not see them.
7448 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007449 ++out;
7450 }
7451 // We need to copy the default methods into our own method table since the runtime requires that
7452 // every method on a class's vtable be in that respective class's virtual method table.
7453 // NOTE This means that two classes might have the same implementation of a method from the same
7454 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7455 // default method found on a class with one found on the declaring interface directly and must
7456 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007457 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7458 &overriding_default_methods_}) {
7459 for (size_t i = 0; i < methods_vec->size(); ++i) {
7460 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007461 ArtMethod& new_method = *out;
7462 new_method.CopyFrom(def_method, pointer_size);
7463 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7464 // verified yet it shouldn't have methods that are skipping access checks.
7465 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7466 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007467 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007468 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7469 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7470 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7471 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007472 // Update the entry in the method array, as the array will be used for future lookups,
7473 // where thread suspension is allowed.
7474 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7475 // would not see them.
7476 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007477 ++out;
7478 }
7479 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007480 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7481 &overriding_default_conflict_methods_}) {
7482 for (size_t i = 0; i < methods_vec->size(); ++i) {
7483 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007484 ArtMethod& new_method = *out;
7485 new_method.CopyFrom(conf_method, pointer_size);
7486 // This is a type of default method (there are default method impls, just a conflict) so
7487 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7488 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7489 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007490 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7491 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007492 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007493 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007494 constexpr uint32_t kMaskFlags =
7495 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007496 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7497 DCHECK(new_method.IsDefaultConflicting());
7498 // The actual method might or might not be marked abstract since we just copied it from a
7499 // (possibly default) interface method. We need to set it entry point to be the bridge so
7500 // that the compiler will not invoke the implementation of whatever method we copied from.
7501 EnsureThrowsInvocationError(class_linker_, &new_method);
7502 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007503 // Update the entry in the method array, as the array will be used for future lookups,
7504 // where thread suspension is allowed.
7505 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7506 // would not see them.
7507 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007508 ++out;
7509 }
7510 }
7511 methods->SetSize(new_method_count);
7512 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7513}
7514
7515ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7516 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7517 ObjPtr<mirror::PointerArray> old_vtable) {
7518 // Update the vtable to the new method structures. We can skip this for interfaces since they
7519 // do not have vtables.
7520 const size_t old_vtable_count = old_vtable->GetLength();
7521 const size_t new_vtable_count = old_vtable_count +
7522 miranda_methods_.size() +
7523 default_methods_.size() +
7524 default_conflict_methods_.size();
7525
7526 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007527 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007528 if (UNLIKELY(vtable == nullptr)) {
7529 self_->AssertPendingOOMException();
7530 return nullptr;
7531 }
7532
7533 size_t vtable_pos = old_vtable_count;
7534 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7535 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7536 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7537 default_conflict_methods_,
7538 miranda_methods_}) {
7539 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007540 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007541 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7542 // fields are references into the dex file the method was defined in. Since the ArtMethod
7543 // does not store that information it uses declaring_class_->dex_cache_.
7544 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7545 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7546 ++vtable_pos;
7547 }
7548 }
7549 DCHECK_EQ(vtable_pos, new_vtable_count);
7550
7551 // Update old vtable methods. We use the default_translations map to figure out what each
7552 // vtable entry should be updated to, if they need to be at all.
7553 for (size_t i = 0; i < old_vtable_count; ++i) {
7554 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7555 // Try and find what we need to change this method to.
7556 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007557 if (translation_it != default_translations.end()) {
7558 if (translation_it->second.IsInConflict()) {
7559 // Find which conflict method we are to use for this method.
7560 MethodNameAndSignatureComparator old_method_comparator(
7561 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7562 // We only need to look through overriding_default_conflict_methods since this is an
7563 // overridden method we are fixing up here.
7564 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7565 old_method_comparator, overriding_default_conflict_methods_);
7566 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7567 translated_method = new_conflict_method;
7568 } else if (translation_it->second.IsAbstract()) {
7569 // Find which miranda method we are to use for this method.
7570 MethodNameAndSignatureComparator old_method_comparator(
7571 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7572 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7573 miranda_methods_);
7574 DCHECK(miranda_method != nullptr);
7575 translated_method = miranda_method;
7576 } else {
7577 // Normal default method (changed from an older default or abstract interface method).
7578 DCHECK(translation_it->second.IsTranslation());
7579 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007580 auto it = move_table_.find(translated_method);
7581 DCHECK(it != move_table_.end());
7582 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007583 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007584 } else {
7585 auto it = move_table_.find(translated_method);
7586 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007587 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007588
7589 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007590 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007591 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007592 if (kIsDebugBuild) {
7593 auto* methods = klass_->GetMethodsPtr();
7594 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007595 reinterpret_cast<uintptr_t>(translated_method));
7596 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007597 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7598 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007599 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007600 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007601 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007602 }
7603 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007604 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007605 return vtable;
7606}
7607
7608void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7609 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7610 const size_t ifcount = klass_->GetIfTableCount();
7611 // Go fix up all the stale iftable pointers.
7612 for (size_t i = 0; i < ifcount; ++i) {
7613 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7614 auto* method_array = iftable->GetMethodArray(i);
7615 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7616 DCHECK(m != nullptr) << klass_->PrettyClass();
7617 auto it = move_table_.find(m);
7618 if (it != move_table_.end()) {
7619 auto* new_m = it->second;
7620 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7621 method_array->SetElementPtrSize(j, new_m, pointer_size);
7622 }
7623 }
7624 }
7625}
7626
7627void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7628 // Fix up IMT next.
7629 for (size_t i = 0; i < ImTable::kSize; ++i) {
7630 auto it = move_table_.find(out_imt[i]);
7631 if (it != move_table_.end()) {
7632 out_imt[i] = it->second;
7633 }
7634 }
7635}
7636
Alex Light705ad492015-09-21 11:36:30 -07007637// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007638bool ClassLinker::LinkInterfaceMethods(
7639 Thread* self,
7640 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007641 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007642 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007643 ArtMethod** out_imt) {
7644 StackHandleScope<3> hs(self);
7645 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007646
7647 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007648 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007649 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007650 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007651 const size_t ifcount = klass->GetIfTableCount();
7652
Vladimir Marko921094a2017-01-12 18:37:06 +00007653 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007654
7655 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7656 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007657 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007658 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007659 const bool extend_super_iftable = has_superclass;
7660 if (has_superclass && fill_tables) {
7661 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007662 unimplemented_method,
7663 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007664 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007665 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007666 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007667 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7668 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007669 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007670 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7671 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007672 }
7673 }
7674
Vladimir Marko921094a2017-01-12 18:37:06 +00007675 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7676
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007677 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007678 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007679 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7680 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7681 // they will already be null. This has the additional benefit that the declarer of a miranda
7682 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007683 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007684 --i;
Alex Light9139e002015-10-09 15:59:48 -07007685 DCHECK_LT(i, ifcount);
7686
Alex Light705ad492015-09-21 11:36:30 -07007687 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007688 if (num_methods > 0) {
7689 StackHandleScope<2> hs2(self);
7690 const bool is_super = i < super_ifcount;
7691 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007692 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7693 // conflict methods. Just set this as nullptr in those cases.
7694 Handle<mirror::PointerArray> method_array(fill_tables
7695 ? hs2.NewHandle(iftable->GetMethodArray(i))
7696 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007697
Alex Lighte64300b2015-12-15 15:02:47 -08007698 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007699 ScopedNullHandle<mirror::PointerArray> null_handle;
7700 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007701 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007702
Alex Light9139e002015-10-09 15:59:48 -07007703 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7704 // and confusing. Default methods should always look through all the superclasses
7705 // because they are the last choice of an implementation. We get around this by looking
7706 // at the super-classes iftable methods (copied into method_array previously) when we are
7707 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007708 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007709 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007710 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007711 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007712 using_virtuals = true;
7713 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7714 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007715 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007716 // For a new interface, however, we need the whole vtable in case a new
7717 // interface method is implemented in the whole superclass.
7718 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007719 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007720 input_vtable_array = vtable;
7721 input_array_length = input_vtable_array->GetLength();
7722 }
Alex Lighte64300b2015-12-15 15:02:47 -08007723
Alex Lighteb7c1442015-08-31 13:17:42 -07007724 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007725 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007726 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007727 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007728 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007729 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007730 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007731 // For each method listed in the interface's method list, find the
7732 // matching method in our class's method list. We want to favor the
7733 // subclass over the superclass, which just requires walking
7734 // back from the end of the vtable. (This only matters if the
7735 // superclass defines a private method and this class redefines
7736 // it -- otherwise it would use the same vtable slot. In .dex files
7737 // those don't end up in the virtual method table, so it shouldn't
7738 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007739 //
7740 // To find defaults we need to do the same but also go over interfaces.
7741 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007742 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007743 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007744 ArtMethod* vtable_method = using_virtuals ?
7745 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007746 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7747 ArtMethod* vtable_method_for_name_comparison =
7748 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007749 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007750 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007751 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007752 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7753 // allocations.
7754 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007755 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007756 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007757 vtable_method->PrettyMethod().c_str(),
7758 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007759 return false;
Alex Light9139e002015-10-09 15:59:48 -07007760 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007761 // We might have a newer, better, default method for this, so we just skip it. If we
7762 // are still using this we will select it again when scanning for default methods. To
7763 // obviate the need to copy the method again we will make a note that we already found
7764 // a default here.
7765 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007766 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007767 break;
7768 } else {
7769 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007770 if (LIKELY(fill_tables)) {
7771 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7772 // Place method in imt if entry is empty, place conflict otherwise.
7773 SetIMTRef(unimplemented_method,
7774 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007775 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007776 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007777 /*out*/imt_ptr);
7778 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007779 break;
7780 }
7781 }
Alex Light9139e002015-10-09 15:59:48 -07007782 }
7783 // Continue on to the next method if we are done.
7784 if (LIKELY(found_impl)) {
7785 continue;
7786 } else if (LIKELY(super_interface)) {
7787 // Don't look for a default implementation when the super-method is implemented directly
7788 // by the class.
7789 //
7790 // See if we can use the superclasses method and skip searching everything else.
7791 // Note: !found_impl && super_interface
7792 CHECK(extend_super_iftable);
7793 // If this is a super_interface method it is possible we shouldn't override it because a
7794 // superclass could have implemented it directly. We get the method the superclass used
7795 // to implement this to know if we can override it with a default method. Doing this is
7796 // safe since we know that the super_iftable is filled in so we can simply pull it from
7797 // there. We don't bother if this is not a super-classes interface since in that case we
7798 // have scanned the entire vtable anyway and would have found it.
7799 // TODO This is rather dirty but it is faster than searching through the entire vtable
7800 // every time.
7801 ArtMethod* supers_method =
7802 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7803 DCHECK(supers_method != nullptr);
7804 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007805 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007806 // The method is not overridable by a default method (i.e. it is directly implemented
7807 // in some class). Therefore move onto the next interface method.
7808 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007809 } else {
7810 // If the super-classes method is override-able by a default method we need to keep
7811 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7812 // 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 -07007813 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7814 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7815 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007816 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007817 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7818 << " and not 'nullptr' or "
7819 << supers_method->PrettyMethod()
7820 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007821 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007822 }
7823 }
7824 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007825 ArtMethod* current_method = helper.FindMethod(interface_method,
7826 interface_name_comparator,
7827 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007828 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007829 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007830 // We could not find an implementation for this method and since it is a brand new
7831 // interface we searched the entire vtable (and all default methods) for an
7832 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007833 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7834 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007835 }
7836
7837 if (current_method != nullptr) {
7838 // We found a default method implementation. Record it in the iftable and IMT.
7839 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7840 SetIMTRef(unimplemented_method,
7841 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007842 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007843 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007844 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007845 }
7846 }
Alex Light705ad492015-09-21 11:36:30 -07007847 } // For each method in interface end.
7848 } // if (num_methods > 0)
7849 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007850 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007851 if (helper.HasNewVirtuals()) {
7852 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7853 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7854 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7855
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007856 // 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 -07007857 // suspension assert.
7858 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007859
Alex Light705ad492015-09-21 11:36:30 -07007860 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007861 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007862 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007863 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007864 return false;
7865 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007866 helper.UpdateIfTable(iftable);
7867 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007868 }
Alex Light705ad492015-09-21 11:36:30 -07007869
Vladimir Marko921094a2017-01-12 18:37:06 +00007870 helper.CheckNoStaleMethodsInDexCache();
7871 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007872 } else {
7873 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007874 }
Alex Light705ad492015-09-21 11:36:30 -07007875 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007876 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007877 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007878 return true;
7879}
7880
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007881bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007882 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007883 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007884}
7885
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007886bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007887 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007888 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007889}
7890
Brian Carlstromdbc05252011-09-09 01:59:59 -07007891struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007892 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007893 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007894 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007895 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007896 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007897 // 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 -07007898 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7899 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007900 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007901 if (type1 == Primitive::kPrimNot) {
7902 // Reference always goes first.
7903 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007904 }
Vladimir Markod5777482014-11-12 17:02:02 +00007905 if (type2 == Primitive::kPrimNot) {
7906 // Reference always goes first.
7907 return false;
7908 }
7909 size_t size1 = Primitive::ComponentSize(type1);
7910 size_t size2 = Primitive::ComponentSize(type2);
7911 if (size1 != size2) {
7912 // Larger primitive types go first.
7913 return size1 > size2;
7914 }
7915 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7916 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007917 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007918 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7919 // by name and for equal names by type id index.
7920 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7921 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007922 }
7923};
7924
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007925bool ClassLinker::LinkFields(Thread* self,
7926 Handle<mirror::Class> klass,
7927 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007928 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007929 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007930 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007931 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7932 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007933
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007934 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007935 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007936 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007937 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007938 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007939 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007940 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007941 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007942 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007943 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007944 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007945 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007946
David Sehr709b0702016-10-13 09:12:37 -07007947 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007948
Brian Carlstromdbc05252011-09-09 01:59:59 -07007949 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007950 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007951 //
7952 // The overall sort order order is:
7953 // 1) All object reference fields, sorted alphabetically.
7954 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7955 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7956 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7957 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7958 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7959 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7960 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7961 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7962 //
7963 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7964 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007965 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007966 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007967 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007968 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007969 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007970 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007971 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7972 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007973
Fred Shih381e4ca2014-08-25 17:24:27 -07007974 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007975 size_t current_field = 0;
7976 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007977 FieldGaps gaps;
7978
Brian Carlstromdbc05252011-09-09 01:59:59 -07007979 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007980 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007981 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007982 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007983 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007984 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007985 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007986 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7987 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007988 MemberOffset old_offset = field_offset;
7989 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7990 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7991 }
Roland Levillain14d90572015-07-16 10:52:26 +01007992 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007993 grouped_and_sorted_fields.pop_front();
7994 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007995 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007996 field_offset = MemberOffset(field_offset.Uint32Value() +
7997 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007998 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007999 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8000 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008001 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8002 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8003 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8004 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008005 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8006 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008007 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008008
Elliott Hughesadb460d2011-10-05 17:02:34 -07008009 // 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 -07008010 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008011 // We know there are no non-reference fields in the Reference classes, and we know
8012 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008013 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008014 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008015 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008016 --num_reference_fields;
8017 }
8018
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008019 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008020 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008021 if (is_static) {
8022 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008023 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008024 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008025 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008026 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008027 if (num_reference_fields == 0 || super_class == nullptr) {
8028 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008029 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008030 if (super_class == nullptr ||
8031 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8032 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008033 }
8034 }
8035 if (kIsDebugBuild) {
8036 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8037 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008038 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008039 while (cur_super != nullptr) {
8040 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8041 cur_super = cur_super->GetSuperClass();
8042 }
8043 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008044 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008045 } else {
8046 // Check that there is at least num_reference_fields other than Object.class.
8047 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008048 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008049 }
8050 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008051 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008052 std::string temp;
8053 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8054 size_t previous_size = klass->GetObjectSize();
8055 if (previous_size != 0) {
8056 // Make sure that we didn't originally have an incorrect size.
8057 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008058 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008059 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008060 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008061 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008062
8063 if (kIsDebugBuild) {
8064 // Make sure that the fields array is ordered by name but all reference
8065 // offsets are at the beginning as far as alignment allows.
8066 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008067 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008068 : klass->GetFirstReferenceInstanceFieldOffset();
8069 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8070 num_reference_fields *
8071 sizeof(mirror::HeapReference<mirror::Object>));
8072 MemberOffset current_ref_offset = start_ref_offset;
8073 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008074 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008075 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008076 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8077 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008078 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008079 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008080 // NOTE: The field names can be the same. This is not possible in the Java language
8081 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008082 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008083 }
8084 Primitive::Type type = field->GetTypeAsPrimitiveType();
8085 bool is_primitive = type != Primitive::kPrimNot;
8086 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8087 strcmp("referent", field->GetName()) == 0) {
8088 is_primitive = true; // We lied above, so we have to expect a lie here.
8089 }
8090 MemberOffset offset = field->GetOffsetDuringLinking();
8091 if (is_primitive) {
8092 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8093 // Shuffled before references.
8094 size_t type_size = Primitive::ComponentSize(type);
8095 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8096 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8097 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8098 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8099 }
8100 } else {
8101 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8102 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8103 sizeof(mirror::HeapReference<mirror::Object>));
8104 }
8105 }
8106 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8107 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008108 return true;
8109}
8110
Vladimir Marko76649e82014-11-10 18:32:59 +00008111// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008112void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008113 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008114 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008115 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008116 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008117 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008118 // Compute reference offsets unless our superclass overflowed.
8119 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8120 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008121 if (num_reference_fields != 0u) {
8122 // All of the fields that contain object references are guaranteed be grouped in memory
8123 // starting at an appropriately aligned address after super class object data.
8124 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8125 sizeof(mirror::HeapReference<mirror::Object>));
8126 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008127 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008128 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008129 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008130 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008131 reference_offsets |= (0xffffffffu << start_bit) &
8132 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008133 }
8134 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008135 }
8136 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008137 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008138}
8139
Vladimir Marko18090d12018-06-01 16:53:12 +01008140ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8141 ObjPtr<mirror::DexCache> dex_cache) {
8142 StackHandleScope<1> hs(Thread::Current());
8143 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8144 return DoResolveString(string_idx, h_dex_cache);
8145}
8146
8147ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8148 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008149 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008150 uint32_t utf16_length;
8151 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008152 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008153 if (string != nullptr) {
8154 dex_cache->SetResolvedString(string_idx, string);
8155 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008156 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008157}
8158
Vladimir Marko18090d12018-06-01 16:53:12 +01008159ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8160 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008161 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008162 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008163 uint32_t utf16_length;
8164 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008165 ObjPtr<mirror::String> string =
8166 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008167 if (string != nullptr) {
8168 dex_cache->SetResolvedString(string_idx, string);
8169 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008170 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008171}
8172
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008173ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008174 ObjPtr<mirror::Class> referrer) {
8175 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8176}
8177
8178ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008179 ObjPtr<mirror::DexCache> dex_cache,
8180 ObjPtr<mirror::ClassLoader> class_loader) {
8181 const DexFile& dex_file = *dex_cache->GetDexFile();
8182 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8183 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8184 ObjPtr<mirror::Class> type = nullptr;
8185 if (descriptor[1] == '\0') {
8186 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8187 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008188 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008189 } else {
8190 Thread* const self = Thread::Current();
8191 DCHECK(self != nullptr);
8192 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8193 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008194 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008195 }
8196 if (type != nullptr) {
8197 if (type->IsResolved()) {
8198 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008199 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008200 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008201 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008202 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008203 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008204}
8205
Andreas Gampe4835d212018-11-21 14:55:10 -08008206template <typename T>
8207ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008208 StackHandleScope<2> hs(Thread::Current());
8209 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8210 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8211 return DoResolveType(type_idx, dex_cache, class_loader);
8212}
8213
Andreas Gampe4835d212018-11-21 14:55:10 -08008214// Instantiate the above.
8215template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8216 ArtField* referrer);
8217template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8218 ArtMethod* referrer);
8219template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8220 ObjPtr<mirror::Class> referrer);
8221
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008222ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008223 Handle<mirror::DexCache> dex_cache,
8224 Handle<mirror::ClassLoader> class_loader) {
8225 Thread* self = Thread::Current();
8226 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8227 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8228 if (resolved != nullptr) {
8229 // TODO: we used to throw here if resolved's class loader was not the
8230 // boot class loader. This was to permit different classes with the
8231 // same name to be loaded simultaneously by different loaders
8232 dex_cache->SetResolvedType(type_idx, resolved);
8233 } else {
8234 CHECK(self->IsExceptionPending())
8235 << "Expected pending exception for failed resolution of: " << descriptor;
8236 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8237 StackHandleScope<1> hs(self);
8238 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008239 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008240 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8241 self->ClearException();
8242 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8243 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008244 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008245 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008246 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008247 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008248 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008249}
8250
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008251ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8252 ObjPtr<mirror::DexCache> dex_cache,
8253 ObjPtr<mirror::ClassLoader> class_loader,
8254 uint32_t method_idx) {
8255 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8256 // functions can optimize the search if the dex_cache is the same as the DexCache
8257 // of the class, with fall-back to name and signature search otherwise.
8258 ArtMethod* resolved = nullptr;
8259 if (klass->IsInterface()) {
8260 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8261 } else {
8262 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8263 }
8264 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008265 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008266 hiddenapi::ShouldDenyAccessToMember(resolved,
8267 hiddenapi::AccessContext(class_loader, dex_cache),
8268 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008269 resolved = nullptr;
8270 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008271 if (resolved != nullptr) {
8272 // In case of jmvti, the dex file gets verified before being registered, so first
8273 // check if it's registered before checking class tables.
8274 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008275 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8276 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008277 << "DexFile referrer: " << dex_file.GetLocation()
8278 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8279 // Be a good citizen and update the dex cache to speed subsequent calls.
8280 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008281 // Disable the following invariant check as the verifier breaks it. b/73760543
8282 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8283 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8284 // << "Method: " << resolved->PrettyMethod() << ", "
8285 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8286 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008287 }
8288 return resolved;
8289}
8290
David Brazdil4525e0b2018-04-05 16:57:32 +01008291// Returns true if `method` is either null or hidden.
8292// Does not print any warnings if it is hidden.
8293static bool CheckNoSuchMethod(ArtMethod* method,
8294 ObjPtr<mirror::DexCache> dex_cache,
8295 ObjPtr<mirror::ClassLoader> class_loader)
8296 REQUIRES_SHARED(Locks::mutator_lock_) {
8297 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008298 hiddenapi::ShouldDenyAccessToMember(method,
8299 hiddenapi::AccessContext(class_loader, dex_cache),
8300 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008301}
8302
8303ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8304 ObjPtr<mirror::DexCache> dex_cache,
8305 ObjPtr<mirror::ClassLoader> class_loader,
8306 uint32_t method_idx) {
8307 if (klass->IsInterface()) {
8308 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8309 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8310 } else {
8311 // If there was an interface method with the same signature, we would have
8312 // found it in the "copied" methods. Only DCHECK that the interface method
8313 // really does not exist.
8314 if (kIsDebugBuild) {
8315 ArtMethod* method =
8316 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8317 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8318 }
8319 return nullptr;
8320 }
8321}
8322
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008323template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008324ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008325 Handle<mirror::DexCache> dex_cache,
8326 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008327 ArtMethod* referrer,
8328 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008329 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008330 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008331 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008332 PointerSize pointer_size = image_pointer_size_;
8333 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008334 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008335 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8336 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008337 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8338 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008339 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008340 return resolved;
8341 }
Vladimir Marko89011192017-12-11 13:45:05 +00008342 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008343 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008344 ObjPtr<mirror::Class> klass = nullptr;
8345 if (valid_dex_cache_method) {
8346 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8347 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008348 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008349 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008350 // We normaly should not end up here. However the verifier currently doesn't guarantee
8351 // the invariant of having the klass in the class table. b/73760543
8352 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008353 }
Vladimir Markoba118822017-06-12 15:41:56 +01008354 } else {
8355 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008356 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008357 if (klass == nullptr) {
8358 DCHECK(Thread::Current()->IsExceptionPending());
8359 return nullptr;
8360 }
8361 }
8362
8363 // Check if the invoke type matches the class type.
8364 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008365 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008366 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008367 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008368 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008369 }
Vladimir Markoba118822017-06-12 15:41:56 +01008370
8371 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008372 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008373 }
Vladimir Markoba118822017-06-12 15:41:56 +01008374
8375 // Note: We can check for IllegalAccessError only if we have a referrer.
8376 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8377 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8378 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8379 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8380 resolved,
8381 dex_cache.Get(),
8382 method_idx,
8383 type)) {
8384 DCHECK(Thread::Current()->IsExceptionPending());
8385 return nullptr;
8386 }
8387 }
8388
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008389 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008390 if (LIKELY(resolved != nullptr) &&
8391 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8392 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008393 return resolved;
8394 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008395 // If we had a method, or if we can find one with another lookup type,
8396 // it's an incompatible-class-change error.
8397 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008398 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008399 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008400 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008401 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008402 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008403 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008404 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8405 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008406 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008407 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008408 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008409 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008410 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008411}
8412
Vladimir Marko89011192017-12-11 13:45:05 +00008413ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008414 Handle<mirror::DexCache> dex_cache,
8415 Handle<mirror::ClassLoader> class_loader) {
8416 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008417 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008418 if (resolved != nullptr) {
8419 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008420 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8421 return resolved;
8422 }
8423 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008424 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008425 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008426 if (klass == nullptr) {
8427 Thread::Current()->AssertPendingException();
8428 return nullptr;
8429 }
8430 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008431 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8432 } else {
8433 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008434 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008435 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008436 hiddenapi::ShouldDenyAccessToMember(
8437 resolved,
8438 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8439 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008440 resolved = nullptr;
8441 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008442 return resolved;
8443}
8444
Vladimir Markof44d36c2017-03-14 14:18:46 +00008445ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8446 ObjPtr<mirror::DexCache> dex_cache,
8447 ObjPtr<mirror::ClassLoader> class_loader,
8448 bool is_static) {
8449 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008450 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008451 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8452 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008453 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008454 }
8455 if (klass == nullptr) {
8456 // The class has not been resolved yet, so the field is also unresolved.
8457 return nullptr;
8458 }
8459 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008460
David Brazdil1ab0fa82018-05-04 11:28:03 +01008461 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008462}
8463
Vladimir Markoe11dd502017-12-08 14:09:45 +00008464ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008465 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008466 Handle<mirror::ClassLoader> class_loader,
8467 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008468 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008469 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008470 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008471 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008472 return resolved;
8473 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008474 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008475 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008476 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008477 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008478 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008479 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008480 }
8481
David Brazdil1ab0fa82018-05-04 11:28:03 +01008482 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008483 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008484 const char* name = dex_file.GetFieldName(field_id);
8485 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008486 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008487 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008488 return resolved;
8489}
8490
Vladimir Markoe11dd502017-12-08 14:09:45 +00008491ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008492 Handle<mirror::DexCache> dex_cache,
8493 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008494 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008495 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008496 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008497 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008498 return resolved;
8499 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008500 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008501 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008502 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008503 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008504 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008505 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008506 }
8507
David Brazdil1ab0fa82018-05-04 11:28:03 +01008508 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8509 if (resolved == nullptr) {
8510 const char* name = dex_file.GetFieldName(field_id);
8511 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008512 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008513 }
8514 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008515}
8516
David Brazdil1ab0fa82018-05-04 11:28:03 +01008517ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8518 ObjPtr<mirror::DexCache> dex_cache,
8519 ObjPtr<mirror::ClassLoader> class_loader,
8520 uint32_t field_idx,
8521 bool is_static) {
8522 ArtField* resolved = nullptr;
8523 Thread* self = is_static ? Thread::Current() : nullptr;
8524 const DexFile& dex_file = *dex_cache->GetDexFile();
8525
8526 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8527 : klass->FindInstanceField(dex_cache, field_idx);
8528
8529 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008530 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008531 const char* name = dex_file.GetFieldName(field_id);
8532 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8533 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8534 : klass->FindInstanceField(name, type);
8535 }
8536
8537 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008538 hiddenapi::ShouldDenyAccessToMember(resolved,
8539 hiddenapi::AccessContext(class_loader, dex_cache),
8540 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008541 resolved = nullptr;
8542 }
8543
8544 if (resolved != nullptr) {
8545 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8546 }
8547
8548 return resolved;
8549}
8550
8551ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8552 ObjPtr<mirror::DexCache> dex_cache,
8553 ObjPtr<mirror::ClassLoader> class_loader,
8554 uint32_t field_idx) {
8555 ArtField* resolved = nullptr;
8556 Thread* self = Thread::Current();
8557 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008558 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008559
8560 const char* name = dex_file.GetFieldName(field_id);
8561 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8562 resolved = mirror::Class::FindField(self, klass, name, type);
8563
8564 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008565 hiddenapi::ShouldDenyAccessToMember(resolved,
8566 hiddenapi::AccessContext(class_loader, dex_cache),
8567 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008568 resolved = nullptr;
8569 }
8570
8571 if (resolved != nullptr) {
8572 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8573 }
8574
8575 return resolved;
8576}
8577
Vladimir Markoaf940202017-12-08 15:01:18 +00008578ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8579 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008580 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008581 Handle<mirror::DexCache> dex_cache,
8582 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008583 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008584 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008585
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008586 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008587 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008588 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008589 }
8590
Narayan Kamath25352fc2016-08-03 12:46:58 +01008591 StackHandleScope<4> hs(self);
8592
8593 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008594 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008595 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008596 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008597 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008598 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008599 DCHECK(self->IsExceptionPending());
8600 return nullptr;
8601 }
8602
8603 // Then resolve the argument types.
8604 //
8605 // TODO: Is there a better way to figure out the number of method arguments
8606 // other than by looking at the shorty ?
8607 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8608
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008609 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008610 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8611 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008612 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008613 DCHECK(self->IsExceptionPending());
8614 return nullptr;
8615 }
8616
8617 DexFileParameterIterator it(dex_file, proto_id);
8618 int32_t i = 0;
8619 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8620 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008621 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008622 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008623 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008624 DCHECK(self->IsExceptionPending());
8625 return nullptr;
8626 }
8627
8628 method_params->Set(i++, param_class.Get());
8629 }
8630
8631 DCHECK(!it.HasNext());
8632
8633 Handle<mirror::MethodType> type = hs.NewHandle(
8634 mirror::MethodType::Create(self, return_type, method_params));
8635 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8636
8637 return type.Get();
8638}
8639
Vladimir Markoaf940202017-12-08 15:01:18 +00008640ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008641 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008642 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008643 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008644 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8645 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008646 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008647}
8648
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008649mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8650 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008651 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008652 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008653 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008654 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8655 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008656 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008657 bool is_static;
8658 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008659 switch (handle_type) {
8660 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008661 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008662 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008663 is_static = true;
8664 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008665 break;
8666 }
8667 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008668 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008669 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008670 is_static = true;
8671 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008672 break;
8673 }
8674 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008675 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008676 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008677 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008678 num_params = 2;
8679 break;
8680 }
8681 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008682 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008683 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008684 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008685 num_params = 1;
8686 break;
8687 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008688 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008689 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008690 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008691 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008692 case DexFile::MethodHandleType::kInvokeInterface:
8693 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008694 }
8695
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008696 ArtField* target_field =
8697 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8698 if (LIKELY(target_field != nullptr)) {
8699 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8700 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8701 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8702 ThrowIllegalAccessErrorField(referring_class, target_field);
8703 return nullptr;
8704 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008705 if (UNLIKELY(is_put && target_field->IsFinal())) {
8706 ThrowIllegalAccessErrorField(referring_class, target_field);
8707 return nullptr;
8708 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008709 } else {
8710 DCHECK(Thread::Current()->IsExceptionPending());
8711 return nullptr;
8712 }
8713
8714 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008715 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008716 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8717 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008718 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008719 DCHECK(self->IsExceptionPending());
8720 return nullptr;
8721 }
8722
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008723 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008724 Handle<mirror::Class> return_type;
8725 switch (handle_type) {
8726 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008727 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008728 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008729 break;
8730 }
8731 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008732 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008733 break;
8734 }
8735 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008736 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008737 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008738 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008739 break;
8740 }
8741 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008742 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008743 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008744 break;
8745 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008746 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008747 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008748 case DexFile::MethodHandleType::kInvokeConstructor:
8749 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008750 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008751 UNREACHABLE();
8752 }
8753
8754 for (int32_t i = 0; i < num_params; ++i) {
8755 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8756 DCHECK(self->IsExceptionPending());
8757 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008758 }
8759 }
8760
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008761 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008762 DCHECK(self->IsExceptionPending());
8763 return nullptr;
8764 }
8765
8766 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008767 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8768 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008769 DCHECK(self->IsExceptionPending());
8770 return nullptr;
8771 }
Orion Hodson631827d2017-04-10 14:53:47 +01008772
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008773 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8774 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8775}
8776
8777mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8778 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008779 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008780 ArtMethod* referrer) {
8781 DexFile::MethodHandleType handle_type =
8782 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8783 mirror::MethodHandle::Kind kind;
8784 uint32_t receiver_count = 0;
8785 ArtMethod* target_method = nullptr;
8786 switch (handle_type) {
8787 case DexFile::MethodHandleType::kStaticPut:
8788 case DexFile::MethodHandleType::kStaticGet:
8789 case DexFile::MethodHandleType::kInstancePut:
8790 case DexFile::MethodHandleType::kInstanceGet:
8791 UNREACHABLE();
8792 case DexFile::MethodHandleType::kInvokeStatic: {
8793 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8794 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008795 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8796 method_handle.field_or_method_idx_,
8797 referrer,
8798 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008799 break;
8800 }
8801 case DexFile::MethodHandleType::kInvokeInstance: {
8802 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8803 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008804 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8805 method_handle.field_or_method_idx_,
8806 referrer,
8807 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008808 break;
8809 }
8810 case DexFile::MethodHandleType::kInvokeConstructor: {
8811 // Constructors are currently implemented as a transform. They
8812 // are special cased later in this method.
8813 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8814 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008815 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8816 method_handle.field_or_method_idx_,
8817 referrer,
8818 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008819 break;
8820 }
8821 case DexFile::MethodHandleType::kInvokeDirect: {
8822 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8823 receiver_count = 1;
8824 StackHandleScope<2> hs(self);
8825 // A constant method handle with type kInvokeDirect can refer to
8826 // a method that is private or to a method in a super class. To
8827 // disambiguate the two options, we resolve the method ignoring
8828 // the invocation type to determine if the method is private. We
8829 // then resolve again specifying the intended invocation type to
8830 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008831 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008832 hs.NewHandle(referrer->GetDexCache()),
8833 hs.NewHandle(referrer->GetClassLoader()));
8834 if (UNLIKELY(target_method == nullptr)) {
8835 break;
8836 }
8837
8838 if (target_method->IsPrivate()) {
8839 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008840 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8841 method_handle.field_or_method_idx_,
8842 referrer,
8843 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008844 } else {
8845 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008846 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8847 method_handle.field_or_method_idx_,
8848 referrer,
8849 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008850 if (UNLIKELY(target_method == nullptr)) {
8851 break;
8852 }
8853 // Find the method specified in the parent in referring class
8854 // so invoke-super invokes the method in the parent of the
8855 // referrer.
8856 target_method =
8857 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8858 kRuntimePointerSize);
8859 }
8860 break;
8861 }
8862 case DexFile::MethodHandleType::kInvokeInterface: {
8863 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8864 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008865 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8866 method_handle.field_or_method_idx_,
8867 referrer,
8868 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008869 break;
8870 }
Orion Hodson631827d2017-04-10 14:53:47 +01008871 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008872
8873 if (UNLIKELY(target_method == nullptr)) {
8874 DCHECK(Thread::Current()->IsExceptionPending());
8875 return nullptr;
8876 }
8877
8878 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8879 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8880 uint32_t access_flags = target_method->GetAccessFlags();
8881 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8882 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8883 return nullptr;
8884 }
8885
8886 // Calculate the number of parameters from the method shorty. We add the
8887 // receiver count (0 or 1) and deduct one for the return value.
8888 uint32_t shorty_length;
8889 target_method->GetShorty(&shorty_length);
8890 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8891
Orion Hodsonecd58562018-09-24 11:27:33 +01008892 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008893 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008894 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8895 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8896 if (method_params.Get() == nullptr) {
8897 DCHECK(self->IsExceptionPending());
8898 return nullptr;
8899 }
8900
Orion Hodsonecd58562018-09-24 11:27:33 +01008901 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008902 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008903 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008904 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01008905 // Insert receiver. Use the class identified in the method handle rather than the declaring
8906 // class of the resolved method which may be super class or default interface method
8907 // (b/115964401).
8908 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
8909 // receiver_class should have been resolved when resolving the target method.
8910 DCHECK(receiver_class != nullptr);
8911 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008912 }
Orion Hodsonecd58562018-09-24 11:27:33 +01008913
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008914 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01008915 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008916 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008917 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008918 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01008919 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008920 if (nullptr == klass) {
8921 DCHECK(self->IsExceptionPending());
8922 return nullptr;
8923 }
8924 method_params->Set(index++, klass);
8925 it.Next();
8926 }
8927
Orion Hodsonecd58562018-09-24 11:27:33 +01008928 Handle<mirror::Class> return_type =
8929 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008930 if (UNLIKELY(return_type.IsNull())) {
8931 DCHECK(self->IsExceptionPending());
8932 return nullptr;
8933 }
8934
8935 Handle<mirror::MethodType>
8936 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8937 if (UNLIKELY(method_type.IsNull())) {
8938 DCHECK(self->IsExceptionPending());
8939 return nullptr;
8940 }
8941
8942 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8943 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8944 Handle<mirror::MethodHandlesLookup> lookup =
8945 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8946 return lookup->FindConstructor(self, constructor_class, method_type);
8947 }
8948
8949 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8950 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8951}
8952
Vladimir Markoaf940202017-12-08 15:01:18 +00008953ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8954 uint32_t method_handle_idx,
8955 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008956 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008957 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008958 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008959 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8960 case DexFile::MethodHandleType::kStaticPut:
8961 case DexFile::MethodHandleType::kStaticGet:
8962 case DexFile::MethodHandleType::kInstancePut:
8963 case DexFile::MethodHandleType::kInstanceGet:
8964 return ResolveMethodHandleForField(self, method_handle, referrer);
8965 case DexFile::MethodHandleType::kInvokeStatic:
8966 case DexFile::MethodHandleType::kInvokeInstance:
8967 case DexFile::MethodHandleType::kInvokeConstructor:
8968 case DexFile::MethodHandleType::kInvokeDirect:
8969 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008970 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008971 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008972}
8973
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008974bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8975 return (entry_point == GetQuickResolutionStub()) ||
8976 (quick_resolution_trampoline_ == entry_point);
8977}
8978
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008979bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8980 return (entry_point == GetQuickToInterpreterBridge()) ||
8981 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8982}
8983
8984bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8985 return (entry_point == GetQuickGenericJniStub()) ||
8986 (quick_generic_jni_trampoline_ == entry_point);
8987}
8988
David Sehra49e0532017-08-25 08:05:29 -07008989bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8990 return entry_point == GetJniDlsymLookupStub();
8991}
8992
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008993const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8994 return GetQuickGenericJniStub();
8995}
8996
Mathieu Chartiere401d142015-04-22 13:56:20 -07008997void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008998 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008999 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9000 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009001 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009002 }
9003}
9004
Alex Lightdb01a092017-04-03 15:39:55 -07009005void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9006 DCHECK(method->IsObsolete());
9007 // We cannot mess with the entrypoints of native methods because they are used to determine how
9008 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9009 if (!method->IsNative()) {
9010 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9011 }
9012}
9013
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009014void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009015 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009016 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009017 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9018 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009019 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9020 os << "Dumping registered class loaders\n";
9021 size_t class_loader_index = 0;
9022 for (const ClassLoaderData& class_loader : class_loaders_) {
9023 ObjPtr<mirror::ClassLoader> loader =
9024 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9025 if (loader != nullptr) {
9026 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9027 bool saw_one_dex_file = false;
9028 for (const DexCacheData& dex_cache : dex_caches_) {
9029 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9030 if (saw_one_dex_file) {
9031 os << ":";
9032 }
9033 saw_one_dex_file = true;
9034 os << dex_cache.dex_file->GetLocation();
9035 }
9036 }
9037 os << "]";
9038 bool found_parent = false;
9039 if (loader->GetParent() != nullptr) {
9040 size_t parent_index = 0;
9041 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9042 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9043 soa.Self()->DecodeJObject(class_loader2.weak_root));
9044 if (loader2 == loader->GetParent()) {
9045 os << ", parent #" << parent_index;
9046 found_parent = true;
9047 break;
9048 }
9049 parent_index++;
9050 }
9051 if (!found_parent) {
9052 os << ", unregistered parent of type "
9053 << loader->GetParent()->GetClass()->PrettyDescriptor();
9054 }
9055 } else {
9056 os << ", no parent";
9057 }
9058 os << "\n";
9059 }
9060 }
9061 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009062}
9063
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009064class CountClassesVisitor : public ClassLoaderVisitor {
9065 public:
9066 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9067
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009068 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009069 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009070 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009071 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009072 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9073 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009074 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009075 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009076
9077 size_t num_zygote_classes;
9078 size_t num_non_zygote_classes;
9079};
9080
9081size_t ClassLinker::NumZygoteClasses() const {
9082 CountClassesVisitor visitor;
9083 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009084 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009085}
9086
9087size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009088 CountClassesVisitor visitor;
9089 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009090 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009091}
9092
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009093size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009094 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009095 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009096 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009097}
9098
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009099pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009100 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009101}
9102
9103pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009104 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009105}
9106
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009107void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009108 DCHECK(!init_done_);
9109
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009110 DCHECK(klass != nullptr);
9111 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009112
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009113 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009114 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009115 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9116 int32_t index = static_cast<int32_t>(class_root);
9117 DCHECK(class_roots->Get(index) == nullptr);
9118 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009119}
9120
Roland Levillain0e840272018-08-23 19:55:30 +01009121void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9122 ObjPtr<mirror::Class> java_lang_Class,
9123 ClassRoot primitive_array_class_root,
9124 ClassRoot primitive_class_root,
9125 const char* descriptor) {
9126 StackHandleScope<1> hs(self);
9127 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9128 AllocPrimitiveArrayClass(self, java_lang_Class)));
9129 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9130 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9131 CheckSystemClass(self, primitive_array_class, descriptor);
9132}
9133
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009134ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9135 Thread* self,
9136 const std::vector<const DexFile*>& dex_files,
9137 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009138 Handle<mirror::ClassLoader> parent_loader,
9139 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009140
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009141 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009142
Mathieu Chartierc7853442015-03-27 14:35:38 -07009143 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009144 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009145
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009146 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009147 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009148 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009149 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009150 mirror::ObjectArray<mirror::Object>::Alloc(self,
9151 dex_elements_class.Get(),
9152 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009153 Handle<mirror::Class> h_dex_element_class =
9154 hs.NewHandle(dex_elements_class->GetComponentType());
9155
Mathieu Chartierc7853442015-03-27 14:35:38 -07009156 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009157 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009158 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009159
Andreas Gampe08883de2016-11-08 13:20:52 -08009160 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009161 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009162
Andreas Gampe08883de2016-11-08 13:20:52 -08009163 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009164 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009165
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009166 // Fill the elements array.
9167 int32_t index = 0;
9168 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009169 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009170
Calin Juravle7865ac72017-06-28 11:03:12 -07009171 // CreateWellKnownClassLoader is only used by gtests and compiler.
9172 // 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 -07009173 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9174 self,
9175 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009176 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009177 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009178
Mathieu Chartier3738e982017-05-12 16:07:28 -07009179 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9180 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009181 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009182 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009183 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009184 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009185
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009186 Handle<mirror::String> h_file_name = hs2.NewHandle(
9187 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009188 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009189 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9190
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009191 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009192 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009193 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009194
9195 h_dex_elements->Set(index, h_element.Get());
9196 index++;
9197 }
9198 DCHECK_EQ(index, h_dex_elements->GetLength());
9199
9200 // Create DexPathList.
9201 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009202 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009203 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009204 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009205 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009206 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9207 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9208 // elements.
9209 {
9210 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9211 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9212 DCHECK(native_lib_dirs != nullptr);
9213 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9214 DCHECK(list_class != nullptr);
9215 {
9216 StackHandleScope<1> h_list_scope(self);
9217 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9218 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9219 DCHECK(list_init);
9220 list_class = h_list_class.Get();
9221 }
9222 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9223 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9224 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9225 // normally never null), as long as one does not try to add elements, this will still
9226 // work.
9227 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9228 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009229
Calin Juravle7865ac72017-06-28 11:03:12 -07009230 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009231 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9232 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009233 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009234 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009235 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009236 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009237 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009238 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009239
9240 // Make a pretend boot-classpath.
9241 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009242 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009243 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009244 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009245 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009246 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009247 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009248 if (parent_loader.Get() == nullptr) {
9249 ScopedObjectAccessUnchecked soa(self);
9250 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9251 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9252 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9253 } else {
9254 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9255 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009256
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009257 ArtField* shared_libraries_field =
9258 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9259 DCHECK(shared_libraries_field != nullptr);
9260 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9261
9262 return h_class_loader.Get();
9263}
9264
9265jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9266 const std::vector<const DexFile*>& dex_files,
9267 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009268 jobject parent_loader,
9269 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009270 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9271 WellKnownClasses::dalvik_system_PathClassLoader) ||
9272 self->GetJniEnv()->IsSameObject(loader_class,
9273 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
9274
9275 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9276 // We could move the jobject to the callers, but all call-sites do this...
9277 ScopedObjectAccessUnchecked soa(self);
9278
9279 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009280 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009281
9282 Handle<mirror::Class> h_loader_class =
9283 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009284 Handle<mirror::ClassLoader> h_parent =
9285 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9286 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9287 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009288
9289 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9290 self,
9291 dex_files,
9292 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009293 h_parent,
9294 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009295
9296 // Make it a global ref and return.
9297 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009298 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009299 return soa.Env()->NewGlobalRef(local_ref.get());
9300}
9301
Calin Juravle7865ac72017-06-28 11:03:12 -07009302jobject ClassLinker::CreatePathClassLoader(Thread* self,
9303 const std::vector<const DexFile*>& dex_files) {
9304 return CreateWellKnownClassLoader(self,
9305 dex_files,
9306 WellKnownClasses::dalvik_system_PathClassLoader,
9307 nullptr);
9308}
9309
Andreas Gampe8ac75952015-06-02 21:01:45 -07009310void ClassLinker::DropFindArrayClassCache() {
9311 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9312 find_array_class_cache_next_victim_ = 0;
9313}
9314
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009315void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009316 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009317 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009318 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009319 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9320 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009321 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009322 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009323 }
9324 }
9325}
9326
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009327void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9328 for (const ClassLoaderData& data : class_loaders_) {
9329 LinearAlloc* alloc = data.allocator;
9330 if (alloc != nullptr && !visitor->Visit(alloc)) {
9331 break;
9332 }
9333 }
9334}
9335
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009336void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9337 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009338 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009339 Thread* const self = Thread::Current();
9340 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009341 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009342 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009343 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009344 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9345 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009346 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009347 }
9348}
9349
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009350void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009351 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009352 std::vector<ClassLoaderData> to_delete;
9353 // Do the delete outside the lock to avoid lock violation in jit code cache.
9354 {
9355 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9356 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9357 const ClassLoaderData& data = *it;
9358 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009359 ObjPtr<mirror::ClassLoader> class_loader =
9360 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009361 if (class_loader != nullptr) {
9362 ++it;
9363 } else {
9364 VLOG(class_linker) << "Freeing class loader";
9365 to_delete.push_back(data);
9366 it = class_loaders_.erase(it);
9367 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009368 }
9369 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009370 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009371 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009372 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009373 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009374}
9375
Vladimir Marko21300532017-01-24 18:06:55 +00009376class GetResolvedClassesVisitor : public ClassVisitor {
9377 public:
9378 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9379 : result_(result),
9380 ignore_boot_classes_(ignore_boot_classes),
9381 last_resolved_classes_(result->end()),
9382 last_dex_file_(nullptr),
9383 vlog_is_on_(VLOG_IS_ON(class_linker)),
9384 extra_stats_(),
9385 last_extra_stats_(extra_stats_.end()) { }
9386
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009387 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009388 if (!klass->IsProxyClass() &&
9389 !klass->IsArrayClass() &&
9390 klass->IsResolved() &&
9391 !klass->IsErroneousResolved() &&
9392 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9393 const DexFile& dex_file = klass->GetDexFile();
9394 if (&dex_file != last_dex_file_) {
9395 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009396 DexCacheResolvedClasses resolved_classes(
9397 dex_file.GetLocation(),
9398 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9399 dex_file.GetLocationChecksum(),
9400 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009401 last_resolved_classes_ = result_->find(resolved_classes);
9402 if (last_resolved_classes_ == result_->end()) {
9403 last_resolved_classes_ = result_->insert(resolved_classes).first;
9404 }
9405 }
9406 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9407 if (UNLIKELY(vlog_is_on_) && added) {
9408 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9409 if (last_extra_stats_ == extra_stats_.end() ||
9410 last_extra_stats_->first != resolved_classes) {
9411 last_extra_stats_ = extra_stats_.find(resolved_classes);
9412 if (last_extra_stats_ == extra_stats_.end()) {
9413 last_extra_stats_ =
9414 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9415 }
9416 }
9417 }
9418 }
9419 return true;
9420 }
9421
9422 void PrintStatistics() const {
9423 if (vlog_is_on_) {
9424 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9425 auto it = extra_stats_.find(std::addressof(resolved_classes));
9426 DCHECK(it != extra_stats_.end());
9427 const ExtraStats& extra_stats = it->second;
9428 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9429 << " has " << resolved_classes.GetClasses().size() << " / "
9430 << extra_stats.number_of_class_defs_ << " resolved classes";
9431 }
9432 }
9433 }
9434
9435 private:
9436 struct ExtraStats {
9437 explicit ExtraStats(uint32_t number_of_class_defs)
9438 : number_of_class_defs_(number_of_class_defs) {}
9439 uint32_t number_of_class_defs_;
9440 };
9441
9442 std::set<DexCacheResolvedClasses>* result_;
9443 bool ignore_boot_classes_;
9444 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9445 const DexFile* last_dex_file_;
9446
9447 // Statistics.
9448 bool vlog_is_on_;
9449 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9450 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9451};
9452
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009453std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009454 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009455 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009456 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009457 std::set<DexCacheResolvedClasses> ret;
9458 VLOG(class_linker) << "Collecting resolved classes";
9459 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009460 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9461 VisitClasses(&visitor);
9462 if (VLOG_IS_ON(class_linker)) {
9463 visitor.PrintStatistics();
9464 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009465 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009466 return ret;
9467}
9468
Mathieu Chartier65975772016-08-05 10:46:36 -07009469class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9470 public:
9471 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9472 : method_(method),
9473 pointer_size_(pointer_size) {}
9474
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009475 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009476 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9477 holder_ = klass;
9478 }
9479 // Return false to stop searching if holder_ is not null.
9480 return holder_ == nullptr;
9481 }
9482
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009483 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009484 const ArtMethod* const method_;
9485 const PointerSize pointer_size_;
9486};
9487
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009488ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009489 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9490 CHECK(method->IsCopied());
9491 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9492 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009493 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009494}
9495
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009496ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9497 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009498 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009499 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009500 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009501}
9502
Roland Levillain0e840272018-08-23 19:55:30 +01009503// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009504template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009505 uint32_t method_idx,
9506 Handle<mirror::DexCache> dex_cache,
9507 Handle<mirror::ClassLoader> class_loader,
9508 ArtMethod* referrer,
9509 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009510template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009511 uint32_t method_idx,
9512 Handle<mirror::DexCache> dex_cache,
9513 Handle<mirror::ClassLoader> class_loader,
9514 ArtMethod* referrer,
9515 InvokeType type);
9516
Roland Levillain0e840272018-08-23 19:55:30 +01009517// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009518template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009519 Thread* self,
9520 ObjPtr<mirror::Class> java_lang_Class,
9521 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009522template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009523 Thread* self,
9524 ObjPtr<mirror::Class> java_lang_Class,
9525 uint32_t class_size);
9526
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009527} // namespace art