blob: c22a5cbcd636c51075e2312acbb63771a48ff355 [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"
David Sehr0225f8e2018-01-31 08:52:24 +000064#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070065#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070066#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070067#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070068#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080069#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000070#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070071#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070072#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070073#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070074#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000075#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070076#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070077#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070078#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080079#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070080#include "imt_conflict_table.h"
81#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070082#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070083#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000084#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080085#include "jit/jit.h"
86#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010087#include "jni/java_vm_ext.h"
88#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070089#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070090#include "mirror/array-alloc-inl.h"
91#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000092#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070093#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080094#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070095#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070096#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080097#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070098#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070099#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100100#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700101#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800102#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700103#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100104#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000105#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700106#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800107#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000108#include "mirror/object-refvisitor-inl.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700109#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700110#include "mirror/object_array-inl.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700111#include "mirror/object_reference.h"
112#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800113#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700114#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800115#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700116#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100117#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700118#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700119#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700120#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700121#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700122#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700123#include "oat_file_assistant.h"
124#include "oat_file_manager.h"
125#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700126#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700127#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800128#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700129#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700130#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700131#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700132#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100133#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800134#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700135#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700136
137namespace art {
138
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800139using android::base::StringPrintf;
140
Mathieu Chartierc7853442015-03-27 14:35:38 -0700141static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700142static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700143
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700144static void ThrowNoClassDefFoundError(const char* fmt, ...)
145 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700146 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700147static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700148 va_list args;
149 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800150 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000151 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800152 va_end(args);
153}
154
Andreas Gampe99babb62015-11-02 16:20:00 -0800155static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700156 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700157 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700158 StackHandleScope<1> hs(self);
159 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700160 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700161 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700162
163 if (exception_class == nullptr) {
164 // No exc class ~ no <init>-with-string.
165 CHECK(self->IsExceptionPending());
166 self->ClearException();
167 return false;
168 }
169
Vladimir Markoba118822017-06-12 15:41:56 +0100170 ArtMethod* exception_init_method = exception_class->FindConstructor(
171 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700172 return exception_init_method != nullptr;
173}
174
Alex Lightd6251582016-10-31 11:12:30 -0700175static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700176 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700177 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
178 if (ext == nullptr) {
179 return nullptr;
180 } else {
181 return ext->GetVerifyError();
182 }
183}
184
185// Helper for ThrowEarlierClassFailure. Throws the stored error.
186static void HandleEarlierVerifyError(Thread* self,
187 ClassLinker* class_linker,
188 ObjPtr<mirror::Class> c)
189 REQUIRES_SHARED(Locks::mutator_lock_) {
190 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800191 DCHECK(obj != nullptr);
192 self->AssertNoPendingException();
193 if (obj->IsClass()) {
194 // Previous error has been stored as class. Create a new exception of that type.
195
196 // It's possible the exception doesn't have a <init>(String).
197 std::string temp;
198 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
199
200 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700201 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800202 } else {
203 self->ThrowNewException(descriptor, nullptr);
204 }
205 } else {
206 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100207 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700208 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800209 CHECK(throwable_class->IsAssignableFrom(error_class));
210 self->SetException(obj->AsThrowable());
211 }
212 self->AssertPendingException();
213}
214
Andreas Gampe5b20b352018-10-11 19:03:20 -0700215// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
216// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
217// before.
218template <bool kNeedsVerified = false>
219static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
220 REQUIRES_SHARED(Locks::mutator_lock_) {
221 if (kNeedsVerified) {
222 // To not fail access-flags access checks, push a minimal state.
223 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
224 }
225 if (!klass->WasVerificationAttempted()) {
226 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
227 klass->SetVerificationAttempted();
228 }
229}
230
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700231void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700232 // The class failed to initialize on a previous attempt, so we want to throw
233 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
234 // failed in verification, in which case v2 5.4.1 says we need to re-throw
235 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800236 Runtime* const runtime = Runtime::Current();
237 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700238 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700239 if (GetVerifyError(c) != nullptr) {
240 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800241 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700242 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800243 } else {
244 extra = verify_error->AsThrowable()->Dump();
245 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700246 }
David Sehr709b0702016-10-13 09:12:37 -0700247 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
248 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700249 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700250
David Sehr709b0702016-10-13 09:12:37 -0700251 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800252 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800253 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700254 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700255 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000256 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700257 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700258 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800259 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800260 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800261 }
Alex Lightd6251582016-10-31 11:12:30 -0700262 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
263 // might have meant to go down the earlier if statement with the original error but it got
264 // swallowed by the OOM so we end up here.
265 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800266 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
267 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
268 // exception will be a cause.
269 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700270 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700271 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700272 }
273}
274
Brian Carlstromb23eab12014-10-08 17:55:21 -0700275static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700276 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700277 if (VLOG_IS_ON(class_linker)) {
278 std::string temp;
279 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000280 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700281 }
282}
283
284static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700285 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700286 Thread* self = Thread::Current();
287 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700288
289 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700290 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700291
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800292 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
293 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
294 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800295 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800296 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
297 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
298 // could have caused the error.
299 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
300 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
301 << " failed initialization: "
302 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800303 }
304
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700305 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700306 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
307 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700308
Elliott Hughesa4f94742012-05-29 16:28:38 -0700309 // We only wrap non-Error exceptions; an Error can just be used as-is.
310 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000311 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700312 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700313 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700314}
315
Fred Shih381e4ca2014-08-25 17:24:27 -0700316// Gap between two fields in object layout.
317struct FieldGap {
318 uint32_t start_offset; // The offset from the start of the object.
319 uint32_t size; // The gap size of 1, 2, or 4 bytes.
320};
321struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800322 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700323 }
324 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
325 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800326 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700327 // Note that the priority queue returns the largest element, so operator()
328 // should return true if lhs is less than rhs.
329 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700330 }
331};
Andreas Gampec55bb392018-09-21 00:02:02 +0000332using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700333
334// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800335static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700336 DCHECK(gaps != nullptr);
337
338 uint32_t current_offset = gap_start;
339 while (current_offset != gap_end) {
340 size_t remaining = gap_end - current_offset;
341 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
342 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
343 current_offset += sizeof(uint32_t);
344 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
345 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
346 current_offset += sizeof(uint16_t);
347 } else {
348 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
349 current_offset += sizeof(uint8_t);
350 }
351 DCHECK_LE(current_offset, gap_end) << "Overran gap";
352 }
353}
354// Shuffle fields forward, making use of gaps whenever possible.
355template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000356static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700357 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700358 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700359 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700360 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700361 DCHECK(current_field_idx != nullptr);
362 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700363 DCHECK(gaps != nullptr);
364 DCHECK(field_offset != nullptr);
365
366 DCHECK(IsPowerOfTwo(n));
367 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700368 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700369 Primitive::Type type = field->GetTypeAsPrimitiveType();
370 if (Primitive::ComponentSize(type) < n) {
371 break;
372 }
373 if (!IsAligned<n>(field_offset->Uint32Value())) {
374 MemberOffset old_offset = *field_offset;
375 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
376 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
377 }
David Sehr709b0702016-10-13 09:12:37 -0700378 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700379 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700380 if (!gaps->empty() && gaps->top().size >= n) {
381 FieldGap gap = gaps->top();
382 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100383 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700384 field->SetOffset(MemberOffset(gap.start_offset));
385 if (gap.size > n) {
386 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
387 }
388 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100389 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700390 field->SetOffset(*field_offset);
391 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
392 }
393 ++(*current_field_idx);
394 }
395}
396
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800397ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700398 : boot_class_table_(new ClassTable()),
399 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800400 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800401 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700402 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000403 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700404 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800405 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800406 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100407 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800408 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700409 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700410 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
411 // For CHA disabled during Aot, see b/34193647.
412
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700413 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700414 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
415 "Array cache size wrong.");
416 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700417}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700418
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800419void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700420 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800421 if (c2 == nullptr) {
422 LOG(FATAL) << "Could not find class " << descriptor;
423 UNREACHABLE();
424 }
425 if (c1.Get() != c2) {
426 std::ostringstream os1, os2;
427 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
428 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
429 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
430 << ". This is most likely the result of a broken build. Make sure that "
431 << "libcore and art projects match.\n\n"
432 << os1.str() << "\n\n" << os2.str();
433 UNREACHABLE();
434 }
435}
436
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800437bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
438 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800439 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700440
Mathieu Chartiere401d142015-04-22 13:56:20 -0700441 Thread* const self = Thread::Current();
442 Runtime* const runtime = Runtime::Current();
443 gc::Heap* const heap = runtime->GetHeap();
444
Jeff Haodcdc85b2015-12-04 14:06:18 -0800445 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700446 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700447
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 // Use the pointer size from the runtime since we are probably creating the image.
449 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
450
Elliott Hughes30646832011-10-13 16:59:46 -0700451 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700452 // 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 -0800453 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700454 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700455 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700456 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
457 // the incorrect result when comparing to-space vs from-space.
Vladimir Markobcf17522018-06-01 13:14:32 +0100458 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(MakeObjPtr(
459 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800460 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100461 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700462 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700463 if (kUseBakerReadBarrier) {
464 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800465 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700466 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700467 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800468 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700469 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700470
Elliott Hughes418d20f2011-09-22 14:00:39 -0700471 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700472 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700473 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700474 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700475 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700476
Ian Rogers23435d02012-09-24 11:23:12 -0700477 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700478 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700479 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800480 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700481 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000483 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700484
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700485 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800486 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
487 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
488 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
489 java_lang_Object.Get(),
490 java_lang_Object->GetObjectSize(),
491 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700492
Igor Murashkin86083f72017-10-27 10:59:04 -0700493 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000494 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700495 // It might seem the lock here is unnecessary, however all the SubtypeCheck
496 // functions are annotated to require locks all the way down.
497 //
498 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
499 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000500 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
501 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700502 }
503
Ian Rogers23435d02012-09-24 11:23:12 -0700504 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700505 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700506 AllocClass(self, java_lang_Class.Get(),
507 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700509
Roland Levillain0e840272018-08-23 19:55:30 +0100510 // Setup java.lang.String.
511 //
512 // We make this class non-movable for the unlikely case where it were to be
513 // moved by a sticky-bit (minor) collection when using the Generational
514 // Concurrent Copying (CC) collector, potentially creating a stale reference
515 // in the `klass_` field of one of its instances allocated in the Large-Object
516 // Space (LOS) -- see the comment about the dirty card scanning logic in
517 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700518 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700519 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100520 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700521 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000522 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400523
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700524 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700525 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700526 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700527 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000528 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700529
Ian Rogers23435d02012-09-24 11:23:12 -0700530 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700531 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100532 mirror::ObjectArray<mirror::Class>::Alloc(self,
533 object_array_class.Get(),
534 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700535 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100536 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
537 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
538 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
539 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100540 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
541 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542
Mathieu Chartier6beced42016-11-15 15:51:31 -0800543 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
544 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
545
Vladimir Marko02610552018-06-04 14:38:00 +0100546 // Create array interface entries to populate once we can load system classes.
547 object_array_class->SetIfTable(AllocIfTable(self, 2));
548 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
549
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100551 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
552 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100553 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100554 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
555 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
556 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
557 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
558 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
559 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560
Vladimir Markoacb906d2018-05-30 10:23:49 +0100561 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700562 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100563 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100564 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100565 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566
Vladimir Markoacb906d2018-05-30 10:23:49 +0100567 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700568 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100569 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100570 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100571 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700572
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700573 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700574
Ian Rogers52813c92012-10-11 11:50:38 -0700575 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700576 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700577 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100578 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100579 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700580 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000581 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700582
Alex Lightd6251582016-10-31 11:12:30 -0700583
584 // Setup dalvik.system.ClassExt
585 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
586 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100587 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000588 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700589
Mathieu Chartier66f19252012-09-18 08:57:04 -0700590 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700591 Handle<mirror::Class> object_array_string(hs.NewHandle(
592 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700593 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700594 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100595 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700596
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000597 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700598 // Create runtime resolution and imt conflict methods.
599 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000600 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
601 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700602
Ian Rogers23435d02012-09-24 11:23:12 -0700603 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
604 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
605 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800606 if (boot_class_path.empty()) {
607 *error_msg = "Boot classpath is empty.";
608 return false;
609 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800610 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800611 if (dex_file.get() == nullptr) {
612 *error_msg = "Null dex file.";
613 return false;
614 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700615 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800616 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700617 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700618
619 // now we can use FindSystemClass
620
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700621 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
622 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700623 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800624 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700625 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700626 quick_resolution_trampoline_ = GetQuickResolutionStub();
627 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
628 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700629 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700630
Alex Lightd6251582016-10-31 11:12:30 -0700631 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000632 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800633 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700634 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000635 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800636 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000637 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800638 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700639 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000640 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700641 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
642 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700643
Ian Rogers23435d02012-09-24 11:23:12 -0700644 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100645 AllocAndSetPrimitiveArrayClassRoot(self,
646 java_lang_Class.Get(),
647 ClassRoot::kBooleanArrayClass,
648 ClassRoot::kPrimitiveBoolean,
649 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650
Roland Levillain0e840272018-08-23 19:55:30 +0100651 AllocAndSetPrimitiveArrayClassRoot(
652 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700653
Roland Levillain0e840272018-08-23 19:55:30 +0100654 AllocAndSetPrimitiveArrayClassRoot(
655 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656
Roland Levillain0e840272018-08-23 19:55:30 +0100657 AllocAndSetPrimitiveArrayClassRoot(
658 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800660 CheckSystemClass(self, int_array_class, "[I");
661 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700662
Roland Levillain0e840272018-08-23 19:55:30 +0100663 AllocAndSetPrimitiveArrayClassRoot(
664 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665
Roland Levillain0e840272018-08-23 19:55:30 +0100666 AllocAndSetPrimitiveArrayClassRoot(
667 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700668
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800669 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
670 // in class_table_.
671 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700672
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800673 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
674 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700675
Ian Rogers23435d02012-09-24 11:23:12 -0700676 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700677 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800678 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700679 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800680 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700681 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
682 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100683 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
684 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700685
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700686 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
687 // suspension.
688 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000689 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700690 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000691 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700692 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000693 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700694 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000695 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700696
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700697 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100698 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700699
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800700 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700701
Ian Rogers23435d02012-09-24 11:23:12 -0700702 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100703 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
704 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700705
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700706 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100707 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700708 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100709 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700710
711 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700712 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
713 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100714 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700715
716 // Create java.lang.reflect.Constructor.class root and array root.
717 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
718 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100719 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700720 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
721 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100722 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700723
724 // Create java.lang.reflect.Method.class root and array root.
725 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
726 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100727 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700728 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
729 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100730 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700731
Orion Hodson005ac512017-10-24 15:43:43 +0100732 // Create java.lang.invoke.CallSite.class root
733 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
734 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100735 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100736
Narayan Kamathafa48272016-08-03 12:46:58 +0100737 // Create java.lang.invoke.MethodType.class root
738 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
739 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100740 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100741
742 // Create java.lang.invoke.MethodHandleImpl.class root
743 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
744 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100745 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100746 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100747
Orion Hodsonc069a302017-01-18 09:23:12 +0000748 // Create java.lang.invoke.MethodHandles.Lookup.class root
749 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
750 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100751 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000752
Orion Hodson005ac512017-10-24 15:43:43 +0100753 // Create java.lang.invoke.VarHandle.class root
754 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000755 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100756 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100757
758 // Create java.lang.invoke.FieldVarHandle.class root
759 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
760 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100761 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100762
763 // Create java.lang.invoke.ArrayElementVarHandle.class root
764 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
765 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100766 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100767
768 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
769 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
770 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100771 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100772
773 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
774 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
775 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100776 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000777
Narayan Kamath000e1882016-10-24 17:14:25 +0100778 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
779 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100780 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100781
Brian Carlstrom1f870082011-08-23 16:02:11 -0700782 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700783 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000784 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800785 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700786 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700787 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
788 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700789 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700790 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700791 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700792 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700793 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700794 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700795 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700796 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700797 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700798 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700799 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700800 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700801
Ian Rogers23435d02012-09-24 11:23:12 -0700802 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700803 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700804 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700805 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100806 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700807
jeffhao8cd6dda2012-02-22 10:15:34 -0800808 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700809 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100810 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100811 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700812 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100813 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
814 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
815 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700816 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000817 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
818 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700819
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700820 // Create conflict tables that depend on the class linker.
821 runtime->FixupConflictTables();
822
Ian Rogers98379392014-02-24 16:53:16 -0800823 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700824
Brian Carlstroma004aa92012-02-08 18:05:09 -0800825 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800826
827 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700828}
829
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700830static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
831 REQUIRES_SHARED(Locks::mutator_lock_) {
832 // Find String.<init> -> StringFactory bindings.
833 ObjPtr<mirror::Class> string_factory_class =
834 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
835 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100836 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700837 WellKnownClasses::InitStringInit(string_class, string_factory_class);
838 // Update the primordial thread.
839 self->InitStringEntryPoints();
840}
841
Ian Rogers98379392014-02-24 16:53:16 -0800842void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800843 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700844
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700845 CreateStringInitBindings(self, this);
846
Brian Carlstrom16192862011-09-12 17:50:06 -0700847 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700848 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700849 // as the types of the field can't be resolved prior to the runtime being
850 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700851 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100852 Handle<mirror::Class> java_lang_ref_Reference =
853 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700854 Handle<mirror::Class> java_lang_ref_FinalizerReference =
855 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800856
Mathieu Chartierc7853442015-03-27 14:35:38 -0700857 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700858 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
859 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700860
Mathieu Chartierc7853442015-03-27 14:35:38 -0700861 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700862 CHECK_STREQ(queue->GetName(), "queue");
863 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700864
Mathieu Chartierc7853442015-03-27 14:35:38 -0700865 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700866 CHECK_STREQ(queueNext->GetName(), "queueNext");
867 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700868
Mathieu Chartierc7853442015-03-27 14:35:38 -0700869 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700870 CHECK_STREQ(referent->GetName(), "referent");
871 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700872
Mathieu Chartierc7853442015-03-27 14:35:38 -0700873 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700874 CHECK_STREQ(zombie->GetName(), "zombie");
875 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700876
Brian Carlstroma663ea52011-08-19 23:33:41 -0700877 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100878 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700879 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700880 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700881 CHECK(klass != nullptr);
882 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700883 // note SetClassRoot does additional validation.
884 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700885 }
886
Vladimir Marko02610552018-06-04 14:38:00 +0100887 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700888
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700889 // disable the slow paths in FindClass and CreatePrimitiveClass now
890 // that Object, Class, and Object[] are setup
891 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700892
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700893 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
894 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
895 // ensure that the class will be initialized.
896 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
897 verifier::MethodVerifier::Init(); // Need to prepare the verifier.
898
899 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
900 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
901 // Strange, but don't crash.
902 LOG(WARNING) << "Could not prepare StackOverflowError.";
903 self->ClearException();
904 }
905 }
906
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800907 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700908}
909
Vladimir Markodcfcce42018-06-27 10:00:28 +0000910void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100911 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
912 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700913 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700914 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100915 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700916 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700917 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000918 } else {
919 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700920 }
921 }
922}
923
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200924// Set image methods' entry point to interpreter.
925class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
926 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700927 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200928 : image_pointer_size_(image_pointer_size) {}
929
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100930 void Visit(ArtMethod* method) override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200931 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
932 CHECK(method->GetDeclaringClass() != nullptr);
933 }
934 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
935 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
936 image_pointer_size_);
937 }
938 }
939
940 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700941 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200942
943 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
944};
945
Jeff Haodcdc85b2015-12-04 14:06:18 -0800946struct TrampolineCheckData {
947 const void* quick_resolution_trampoline;
948 const void* quick_imt_conflict_trampoline;
949 const void* quick_generic_jni_trampoline;
950 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700951 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952 ArtMethod* m;
953 bool error;
954};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800955
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800956bool ClassLinker::InitFromBootImage(std::string* error_msg) {
957 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700958 CHECK(!init_done_);
959
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700960 Runtime* const runtime = Runtime::Current();
961 Thread* const self = Thread::Current();
962 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800963 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
964 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700965 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
966 if (!ValidPointerSize(pointer_size_unchecked)) {
967 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800968 return false;
969 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700970 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800971 if (!runtime->IsAotCompiler()) {
972 // Only the Aot compiler supports having an image with a different pointer size than the
973 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
974 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700975 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800976 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700977 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800978 sizeof(void*));
979 return false;
980 }
981 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800982 std::vector<const OatFile*> oat_files =
983 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
984 DCHECK(!oat_files.empty());
985 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800986 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
987 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
988 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
989 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
990 if (kIsDebugBuild) {
991 // Check that the other images use the same trampoline.
992 for (size_t i = 1; i < oat_files.size(); ++i) {
993 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
994 const void* ith_quick_resolution_trampoline =
995 ith_oat_header.GetQuickResolutionTrampoline();
996 const void* ith_quick_imt_conflict_trampoline =
997 ith_oat_header.GetQuickImtConflictTrampoline();
998 const void* ith_quick_generic_jni_trampoline =
999 ith_oat_header.GetQuickGenericJniTrampoline();
1000 const void* ith_quick_to_interpreter_bridge_trampoline =
1001 ith_oat_header.GetQuickToInterpreterBridge();
1002 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1003 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1004 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1005 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1006 // Make sure that all methods in this image do not contain those trampolines as
1007 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1008 TrampolineCheckData data;
1009 data.error = false;
1010 data.pointer_size = GetImagePointerSize();
1011 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1012 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1013 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1014 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1015 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001016 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1017 if (obj->IsClass()) {
1018 ObjPtr<mirror::Class> klass = obj->AsClass();
1019 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1020 const void* entrypoint =
1021 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1022 if (entrypoint == data.quick_resolution_trampoline ||
1023 entrypoint == data.quick_imt_conflict_trampoline ||
1024 entrypoint == data.quick_generic_jni_trampoline ||
1025 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1026 data.m = &m;
1027 data.error = true;
1028 return;
1029 }
1030 }
1031 }
1032 };
1033 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001034 if (data.error) {
1035 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001036 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001037 *error_msg = "Found an ArtMethod with a bad entrypoint";
1038 return false;
1039 }
1040 }
1041 }
1042 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001043
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001044 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001045 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1046 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001047 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001048
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001049 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001050 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001051 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1052 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001053 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1054 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001055
Vladimir Marko4433c432018-12-04 14:57:47 +00001056 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1057 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001058 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001059 // Boot class loader, use a null handle.
1060 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001061 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001062 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001063 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001064 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001065 /*out*/&dex_files,
1066 error_msg)) {
1067 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001068 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001069 // Append opened dex files at the end.
1070 boot_dex_files_.insert(boot_dex_files_.end(),
1071 std::make_move_iterator(dex_files.begin()),
1072 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001073 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001074 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1075 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1076 }
Ian Rogers98379392014-02-24 16:53:16 -08001077 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001078
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001079 VLOG(startup) << __FUNCTION__ << " exiting";
1080 return true;
1081}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001082
Vladimir Marko4433c432018-12-04 14:57:47 +00001083void ClassLinker::AddExtraBootDexFiles(
1084 Thread* self,
1085 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1086 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1087 AppendToBootClassPath(self, *dex_file);
1088 boot_dex_files_.push_back(std::move(dex_file));
1089 }
1090}
1091
Jeff Hao5872d7c2016-04-27 11:07:41 -07001092bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001093 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001094 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001095 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1096 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001097}
1098
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001099static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1100 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001101 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001102 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001103 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001104 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001105 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001106 DCHECK(dex_file_field != nullptr);
1107 DCHECK(dex_file_name_field != nullptr);
1108 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001109 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001110 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001111 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001112 // Null dex file means it was probably a jar with no dex files, return a null string.
1113 *out_name = nullptr;
1114 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001115 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001116 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001118 *out_name = name_object->AsString();
1119 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001121 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122}
1123
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001124static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1125 ObjPtr<mirror::ClassLoader> class_loader,
1126 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1127 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001128 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001129 StackHandleScope<1> hs(soa.Self());
1130 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001131 // Get element names. Sets error to true on failure.
1132 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1133 REQUIRES_SHARED(Locks::mutator_lock_) {
1134 if (element == nullptr) {
1135 *error_msg = "Null dex element";
1136 *error = true; // Null element is a critical error.
1137 return false; // Had an error, stop the visit.
1138 }
1139 ObjPtr<mirror::String> name;
1140 if (!GetDexPathListElementName(element, &name)) {
1141 *error_msg = "Invalid dex path list element";
1142 *error = true; // Invalid element, make it a critical error.
1143 return false; // Stop the visit.
1144 }
1145 if (name != nullptr) {
1146 dex_files->push_front(name);
1147 }
1148 return true; // Continue with the next Element.
1149 };
1150 bool error = VisitClassLoaderDexElements(soa,
1151 handle,
1152 add_element_names,
1153 /*defaultReturn=*/ false);
1154 return !error;
1155}
1156
1157static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1158 ObjPtr<mirror::ClassLoader> image_class_loader,
1159 ObjPtr<mirror::ClassLoader> class_loader,
1160 std::string* error_msg)
1161 REQUIRES_SHARED(Locks::mutator_lock_) {
1162 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1163 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1164 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001165 return false;
1166 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001167 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1168 *error_msg = "Hierarchies don't match";
1169 return false;
1170 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1171 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1172 image_class_loader->PrettyTypeOf().c_str(),
1173 class_loader->PrettyTypeOf().c_str());
1174 return false;
1175 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1176 class_loader->GetClass()) {
1177 *error_msg = StringPrintf("Unknown class loader type %s",
1178 class_loader->PrettyTypeOf().c_str());
1179 // Unsupported class loader.
1180 return false;
1181 }
1182 return true;
1183}
1184
1185static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1186 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1187 std::string* error_msg)
1188 REQUIRES_SHARED(Locks::mutator_lock_) {
1189 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1190 std::equal(image_dex_files.begin(),
1191 image_dex_files.end(),
1192 loader_dex_files.begin(),
1193 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1194 REQUIRES_SHARED(Locks::mutator_lock_) {
1195 return lhs->Equals(rhs);
1196 });
1197 if (!equal) {
1198 VLOG(image) << "Image dex files " << image_dex_files.size();
1199 for (ObjPtr<mirror::String> name : image_dex_files) {
1200 VLOG(image) << name->ToModifiedUtf8();
1201 }
1202 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1203 for (ObjPtr<mirror::String> name : loader_dex_files) {
1204 VLOG(image) << name->ToModifiedUtf8();
1205 }
1206 *error_msg = "Mismatch in dex files";
1207 }
1208 return equal;
1209}
1210
1211static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1212 ObjPtr<mirror::ClassLoader> image_class_loader,
1213 ObjPtr<mirror::ClassLoader> class_loader,
1214 bool check_dex_file_names,
1215 std::string* error_msg)
1216 REQUIRES_SHARED(Locks::mutator_lock_) {
1217 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1218 return false;
1219 }
1220
1221 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1222 // No need to check further.
1223 return true;
1224 }
1225
1226 if (check_dex_file_names) {
1227 std::list<ObjPtr<mirror::String>> image_dex_files;
1228 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001229 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001230 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001231
1232 std::list<ObjPtr<mirror::String>> loader_dex_files;
1233 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1234 return false;
1235 }
1236
1237 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1238 return false;
1239 }
1240 }
1241
1242 ArtField* field =
1243 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1244 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1245 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1246 if (shared_libraries_image_loader == nullptr) {
1247 if (shared_libraries_loader != nullptr) {
1248 *error_msg = "Mismatch in shared libraries";
1249 return false;
1250 }
1251 } else if (shared_libraries_loader == nullptr) {
1252 *error_msg = "Mismatch in shared libraries";
1253 return false;
1254 } else {
1255 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1256 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1257 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1258 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1259 if (array1->GetLength() != array2->GetLength()) {
1260 *error_msg = "Mismatch in number of shared libraries";
1261 return false;
1262 }
1263
1264 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1265 // Do a full comparison of the class loaders, including comparing their dex files.
1266 if (!CompareClassLoaders(soa,
1267 array1->Get(i),
1268 array2->Get(i),
1269 /*check_dex_file_names=*/ true,
1270 error_msg)) {
1271 return false;
1272 }
1273 }
1274 }
1275
1276 // Do a full comparison of the class loaders, including comparing their dex files.
1277 if (!CompareClassLoaders(soa,
1278 image_class_loader->GetParent(),
1279 class_loader->GetParent(),
1280 /*check_dex_file_names=*/ true,
1281 error_msg)) {
1282 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001283 }
1284 return true;
1285}
1286
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001287class CHAOnDeleteUpdateClassVisitor {
1288 public:
1289 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1290 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1291 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1292 self_(Thread::Current()) {}
1293
1294 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1295 // This class is going to be unloaded. Tell CHA about it.
1296 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1297 return true;
1298 }
1299 private:
1300 const LinearAlloc* allocator_;
1301 const ClassHierarchyAnalysis* cha_;
1302 const PointerSize pointer_size_;
1303 const Thread* self_;
1304};
1305
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001306class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1307 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001308 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001309 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1310
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001311 void Visit(ArtMethod* method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001312 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001313 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001314 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001315 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001316 }
1317 }
1318
1319 private:
1320 gc::accounting::HeapBitmap* const live_bitmap_;
1321};
1322
Chris Wailes0c61be42018-09-26 17:27:34 -07001323/*
1324 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001325 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001326 */
1327class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001328 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001329 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001330 space_(space),
1331 intern_table_(*Runtime::Current()->GetInternTable()) {}
1332
Chris Wailes0c61be42018-09-26 17:27:34 -07001333 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001334 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001335 if (referred_obj != nullptr &&
1336 space_.HasAddress(referred_obj.Ptr()) &&
1337 referred_obj->IsString()) {
1338 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001339
1340 if (kIsDebugBuild) {
1341 // Saved to temporary variables to aid in debugging.
1342 ObjPtr<mirror::String> strong_lookup_result =
1343 intern_table_.LookupStrong(Thread::Current(), referred_str);
1344 ObjPtr<mirror::String> weak_lookup_result =
1345 intern_table_.LookupWeak(Thread::Current(), referred_str);
1346
1347 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1348 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001349 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001350 }
1351
Chris Wailes0c61be42018-09-26 17:27:34 -07001352 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001353 mirror::CompressedReference<mirror::Object>* root) const
1354 REQUIRES_SHARED(Locks::mutator_lock_) {
1355 if (!root->IsNull()) {
1356 VisitRoot(root);
1357 }
1358 }
1359
Chris Wailes0c61be42018-09-26 17:27:34 -07001360 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001361 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001362 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001363 }
1364
1365 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001366 void operator()(ObjPtr<mirror::Object> obj,
1367 MemberOffset offset,
1368 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001369 REQUIRES_SHARED(Locks::mutator_lock_) {
1370 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1371 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1372 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1373 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001374 ObjPtr<mirror::Object> referred_obj =
1375 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1376
1377 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001378 }
1379 }
1380
1381 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1382 ObjPtr<mirror::Reference> ref) const
1383 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001384 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001385 }
1386
Chris Wailes0c61be42018-09-26 17:27:34 -07001387 const gc::space::ImageSpace& space_;
1388 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001389};
1390
Chris Wailes0c61be42018-09-26 17:27:34 -07001391/*
1392 * This function verifies that string references in the AppImage have been
1393 * properly interned. To be considered properly interned a reference must
1394 * point to the same version of the string that the intern table does.
1395 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001396void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001397 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1398 const ImageHeader& image_header = space.GetImageHeader();
1399 const uint8_t* target_base = space.GetMemMap()->Begin();
1400 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001401
1402 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1403 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001404
1405 VerifyStringInterningVisitor visitor(space);
1406 bitmap->VisitMarkedRange(objects_begin,
1407 objects_end,
1408 [&space, &visitor](mirror::Object* obj)
1409 REQUIRES_SHARED(Locks::mutator_lock_) {
1410 if (space.HasAddress(obj)) {
1411 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001412 obj->VisitReferences</* kVisitNativeRoots= */ true,
1413 kVerifyNone,
1414 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001415 } else {
1416 // Don't visit native roots for non-dex-cache as they can't contain
1417 // native references to strings. This is verified during compilation
1418 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001419 obj->VisitReferences</* kVisitNativeRoots= */ false,
1420 kVerifyNone,
1421 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001422 }
1423 }
1424 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001425}
1426
Andreas Gampe2af99022017-04-25 08:32:59 -07001427// new_class_set is the set of classes that were read from the class table section in the image.
1428// If there was no class table section, it is null.
1429// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001430class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001431 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001432 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001433 ClassLinker* class_linker,
1434 gc::space::ImageSpace* space,
1435 Handle<mirror::ClassLoader> class_loader,
1436 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001437 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001438 REQUIRES(!Locks::dex_lock_)
1439 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001440
Chris Wailesfbeef462018-10-19 14:16:35 -07001441 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001442 REQUIRES_SHARED(Locks::mutator_lock_);
1443
1444 static void UpdateInternStrings(
1445 gc::space::ImageSpace* space,
1446 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1447 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001448};
1449
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001450void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001451 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001452 gc::space::ImageSpace* space,
1453 Handle<mirror::ClassLoader> class_loader,
1454 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001455 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001456 REQUIRES(!Locks::dex_lock_)
1457 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001458 ScopedTrace app_image_timing("AppImage:Updating");
1459
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001460 Thread* const self = Thread::Current();
1461 gc::Heap* const heap = Runtime::Current()->GetHeap();
1462 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001463 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001464 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001465 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001466 const size_t num_dex_caches = dex_caches->GetLength();
1467 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001468 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001469 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001470 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001471 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001472 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1473 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001474 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001475
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001476 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001477 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001478 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001479 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001480 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001481 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001482 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001483
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001484 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001485 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001486 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001487 DCHECK(it != new_class_set->end());
1488 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001489 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001490
Vladimir Marko1a1de672016-10-13 12:53:15 +01001491 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001492 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001493 DCHECK(it2 != new_class_set->end());
1494 DCHECK_EQ(it2->Read(), super_class);
1495 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001496
Vladimir Marko1a1de672016-10-13 12:53:15 +01001497 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1498 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001499 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1500 if (!class_linker->IsQuickResolutionStub(code) &&
1501 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001502 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001503 !m.IsNative()) {
1504 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001505 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001506 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001507
Vladimir Marko1a1de672016-10-13 12:53:15 +01001508 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1509 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001510 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1511 if (!class_linker->IsQuickResolutionStub(code) &&
1512 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001513 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001514 !m.IsNative()) {
1515 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001516 }
1517 }
1518 }
1519 }
1520 }
1521 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001522 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001523
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001524 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001525 HandleAppImageStrings(space);
1526
1527 if (kIsDebugBuild) {
1528 VerifyStringInterning(*space);
1529 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001530 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001531
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001532 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001533 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001534 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1535 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001536 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001537 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001538}
1539
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001540void AppImageLoadingHelper::UpdateInternStrings(
1541 gc::space::ImageSpace* space,
1542 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1543 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001544 const ImageSection& sro_section =
1545 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1546 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001547
1548 VLOG(image)
1549 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1550 << num_string_offsets;
1551
Chris Wailesfbeef462018-10-19 14:16:35 -07001552 const auto* sro_base =
1553 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001554
1555 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001556 uint32_t base_offset = sro_base[offset_index].first;
1557
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001558 if (HasDexCacheStringNativeRefTag(base_offset)) {
1559 base_offset = ClearDexCacheNativeRefTags(base_offset);
1560 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001561
1562 ObjPtr<mirror::DexCache> dex_cache =
1563 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1564 uint32_t string_index = sro_base[offset_index].second;
1565
1566 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1567 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001568 DCHECK(referred_string != nullptr);
1569
Chris Wailesfbeef462018-10-19 14:16:35 -07001570 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001571 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001572 // This doesn't use SetResolvedString to maintain consistency with how
1573 // we load the string. The index from the source string must be
1574 // re-used due to the circular nature of the cache. Because we are not
1575 // using a helper function we need to mark the GC card manually.
1576 WriteBarrier::ForEveryFieldWrite(dex_cache);
1577 dex_cache->GetStrings()[string_index].store(
1578 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001579 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001580 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1581 base_offset = ClearDexCacheNativeRefTags(base_offset);
1582 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001583
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001584 ObjPtr<mirror::DexCache> dex_cache =
1585 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1586 uint32_t string_index = sro_base[offset_index].second;
1587
1588 ObjPtr<mirror::String> referred_string =
1589 dex_cache->GetPreResolvedStrings()[string_index].Read();
1590 DCHECK(referred_string != nullptr);
1591
1592 auto it = intern_remap.find(referred_string.Ptr());
1593 if (it != intern_remap.end()) {
1594 // Because we are not using a helper function we need to mark the GC card manually.
1595 WriteBarrier::ForEveryFieldWrite(dex_cache);
1596 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1597 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001598 } else {
1599 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001600 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001601 DCHECK_ALIGNED(raw_member_offset, 2);
1602
1603 ObjPtr<mirror::Object> obj_ptr =
1604 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1605 MemberOffset member_offset(raw_member_offset);
1606 ObjPtr<mirror::String> referred_string =
1607 obj_ptr->GetFieldObject<mirror::String,
1608 kVerifyNone,
1609 kWithoutReadBarrier,
1610 /* kIsVolatile= */ false>(member_offset);
1611 DCHECK(referred_string != nullptr);
1612
1613 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001614 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001615 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1616 /* kCheckTransaction= */ false,
1617 kVerifyNone,
1618 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001619 }
1620 }
1621 }
1622}
1623
Chris Wailesfbeef462018-10-19 14:16:35 -07001624void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001625 // Iterate over the string reference offsets stored in the image and intern
1626 // the strings they point to.
1627 ScopedTrace timing("AppImage:InternString");
1628
Chris Wailesfbeef462018-10-19 14:16:35 -07001629 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001630
1631 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1632 // for faster lookup.
1633 // TODO: Optimize with a bitmap or bloom filter
1634 SafeMap<mirror::String*, mirror::String*> intern_remap;
1635 intern_table->AddImageStringsToTable(space, [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001636 REQUIRES_SHARED(Locks::mutator_lock_)
1637 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001638 const size_t non_boot_image_strings = intern_table->CountInterns(
1639 /*visit_boot_images=*/false,
1640 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001641 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001642 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1643 // Visit the smaller of the two sets to compute the intersection.
1644 if (interns.size() < non_boot_image_strings) {
1645 for (auto it = interns.begin(); it != interns.end(); ) {
1646 ObjPtr<mirror::String> string = it->Read();
1647 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1648 if (existing == nullptr) {
1649 existing = intern_table->LookupStrongLocked(string);
1650 }
1651 if (existing != nullptr) {
1652 intern_remap.Put(string.Ptr(), existing.Ptr());
1653 it = interns.erase(it);
1654 } else {
1655 ++it;
1656 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001657 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001658 } else {
1659 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1660 REQUIRES_SHARED(Locks::mutator_lock_)
1661 REQUIRES(Locks::intern_table_lock_) {
1662 auto it = interns.find(root);
1663 if (it != interns.end()) {
1664 ObjPtr<mirror::String> existing = root.Read();
1665 intern_remap.Put(it->Read(), existing.Ptr());
1666 it = interns.erase(it);
1667 }
1668 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1669 }
1670 // Sanity check to ensure correctness.
1671 if (kIsDebugBuild) {
1672 for (GcRoot<mirror::String>& root : interns) {
1673 ObjPtr<mirror::String> string = root.Read();
1674 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1675 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001676 }
1677 }
1678 });
1679
Chris Wailesfbeef462018-10-19 14:16:35 -07001680 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001681
1682 // For debug builds, always run the code below to get coverage.
1683 if (kIsDebugBuild || !intern_remap.empty()) {
1684 // Slow path case is when there are conflicting intern strings to fix up.
1685 UpdateInternStrings(space, intern_remap);
1686 }
1687}
1688
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001689static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1690 const char* location,
1691 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001692 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001693 DCHECK(error_msg != nullptr);
1694 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001695 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001696 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001697 return std::unique_ptr<const DexFile>();
1698 }
1699 std::string inner_error_msg;
1700 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1701 if (dex_file == nullptr) {
1702 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1703 location,
1704 oat_file->GetLocation().c_str(),
1705 inner_error_msg.c_str());
1706 return std::unique_ptr<const DexFile>();
1707 }
1708
1709 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1710 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1711 location,
1712 dex_file->GetLocationChecksum(),
1713 oat_dex_file->GetDexFileLocationChecksum());
1714 return std::unique_ptr<const DexFile>();
1715 }
1716 return dex_file;
1717}
1718
1719bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1720 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1721 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001722 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001723 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001724 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001725 DCHECK(dex_caches_object != nullptr);
1726 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1727 dex_caches_object->AsObjectArray<mirror::DexCache>();
1728 const OatFile* oat_file = space->GetOatFile();
1729 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001730 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001731 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1732 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1733 dex_file_location.c_str(),
1734 error_msg);
1735 if (dex_file == nullptr) {
1736 return false;
1737 }
1738 dex_cache->SetDexFile(dex_file.get());
1739 out_dex_files->push_back(std::move(dex_file));
1740 }
1741 return true;
1742}
1743
Andreas Gampe0793bec2016-12-01 11:37:33 -08001744// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1745// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001746class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001747 public:
1748 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1749 REQUIRES_SHARED(Locks::mutator_lock_) {
1750 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001751 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1752 DCHECK(obj != nullptr);
1753 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1754 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1755 if (obj->IsClass()) {
1756 auto klass = obj->AsClass();
1757 for (ArtField& field : klass->GetIFields()) {
1758 CHECK_EQ(field.GetDeclaringClass(), klass);
1759 }
1760 for (ArtField& field : klass->GetSFields()) {
1761 CHECK_EQ(field.GetDeclaringClass(), klass);
1762 }
1763 const auto pointer_size = isc.pointer_size_;
1764 for (auto& m : klass->GetMethods(pointer_size)) {
1765 isc.SanityCheckArtMethod(&m, klass);
1766 }
1767 auto* vtable = klass->GetVTable();
1768 if (vtable != nullptr) {
1769 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1770 }
1771 if (klass->ShouldHaveImt()) {
1772 ImTable* imt = klass->GetImt(pointer_size);
1773 for (size_t i = 0; i < ImTable::kSize; ++i) {
1774 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1775 }
1776 }
1777 if (klass->ShouldHaveEmbeddedVTable()) {
1778 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1779 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1780 }
1781 }
1782 mirror::IfTable* iftable = klass->GetIfTable();
1783 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1784 if (iftable->GetMethodArrayCount(i) > 0) {
1785 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1786 }
1787 }
1788 }
1789 };
1790 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001791 }
1792
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001793 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1794 ClassLinker* class_linker,
1795 mirror::MethodDexCacheType* arr,
1796 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001797 REQUIRES_SHARED(Locks::mutator_lock_) {
1798 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001799 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001800 }
1801
Andreas Gampe0793bec2016-12-01 11:37:33 -08001802 private:
1803 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1804 : spaces_(heap->GetBootImageSpaces()),
1805 pointer_size_(class_linker->GetImagePointerSize()) {
1806 space_begin_.reserve(spaces_.size());
1807 method_sections_.reserve(spaces_.size());
1808 runtime_method_sections_.reserve(spaces_.size());
1809 for (gc::space::ImageSpace* space : spaces_) {
1810 space_begin_.push_back(space->Begin());
1811 auto& header = space->GetImageHeader();
1812 method_sections_.push_back(&header.GetMethodsSection());
1813 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1814 }
1815 }
1816
1817 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1818 REQUIRES_SHARED(Locks::mutator_lock_) {
1819 if (m->IsRuntimeMethod()) {
1820 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1821 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1822 } else if (m->IsCopied()) {
1823 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1824 } else if (expected_class != nullptr) {
1825 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1826 }
1827 if (!spaces_.empty()) {
1828 bool contains = false;
1829 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1830 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1831 contains = method_sections_[i]->Contains(offset) ||
1832 runtime_method_sections_[i]->Contains(offset);
1833 }
1834 CHECK(contains) << m << " not found";
1835 }
1836 }
1837
1838 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1839 ObjPtr<mirror::Class> expected_class)
1840 REQUIRES_SHARED(Locks::mutator_lock_) {
1841 CHECK(arr != nullptr);
1842 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1843 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1844 // expected_class == null means we are a dex cache.
1845 if (expected_class != nullptr) {
1846 CHECK(method != nullptr);
1847 }
1848 if (method != nullptr) {
1849 SanityCheckArtMethod(method, expected_class);
1850 }
1851 }
1852 }
1853
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001854 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001855 REQUIRES_SHARED(Locks::mutator_lock_) {
1856 CHECK_EQ(arr != nullptr, size != 0u);
1857 if (arr != nullptr) {
1858 bool contains = false;
1859 for (auto space : spaces_) {
1860 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001861 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001862 contains = true;
1863 break;
1864 }
1865 }
1866 CHECK(contains);
1867 }
1868 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001869 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1870 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001871 // expected_class == null means we are a dex cache.
1872 if (method != nullptr) {
1873 SanityCheckArtMethod(method, nullptr);
1874 }
1875 }
1876 }
1877
1878 const std::vector<gc::space::ImageSpace*>& spaces_;
1879 const PointerSize pointer_size_;
1880
1881 // Cached sections from the spaces.
1882 std::vector<const uint8_t*> space_begin_;
1883 std::vector<const ImageSection*> method_sections_;
1884 std::vector<const ImageSection*> runtime_method_sections_;
1885};
1886
Andreas Gampebe7af222017-07-25 09:57:28 -07001887static void VerifyAppImage(const ImageHeader& header,
1888 const Handle<mirror::ClassLoader>& class_loader,
1889 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1890 ClassTable* class_table, gc::space::ImageSpace* space)
1891 REQUIRES_SHARED(Locks::mutator_lock_) {
1892 {
1893 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1894 public:
1895 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1896
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001897 void Visit(ArtMethod* method) override
Andreas Gampebe7af222017-07-25 09:57:28 -07001898 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1899 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1900 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1901 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1902 }
1903 }
1904
1905 private:
1906 ClassTable* const table_;
1907 };
1908 VerifyClassInTableArtMethodVisitor visitor(class_table);
1909 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1910 }
1911 {
1912 // Verify that all direct interfaces of classes in the class table are also resolved.
1913 std::vector<ObjPtr<mirror::Class>> classes;
1914 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1915 REQUIRES_SHARED(Locks::mutator_lock_) {
1916 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1917 classes.push_back(klass);
1918 }
1919 return true;
1920 };
1921 class_table->Visit(verify_direct_interfaces_in_table);
1922 Thread* self = Thread::Current();
1923 for (ObjPtr<mirror::Class> klass : classes) {
1924 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1925 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1926 << klass->PrettyDescriptor() << " iface #" << i;
1927 }
1928 }
1929 }
1930 // Check that all non-primitive classes in dex caches are also in the class table.
1931 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1932 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1933 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1934 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1935 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1936 if (klass != nullptr && !klass->IsPrimitive()) {
1937 CHECK(class_table->Contains(klass))
1938 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1939 }
1940 }
1941 }
1942}
1943
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001944bool ClassLinker::AddImageSpace(
1945 gc::space::ImageSpace* space,
1946 Handle<mirror::ClassLoader> class_loader,
1947 jobjectArray dex_elements,
1948 const char* dex_location,
1949 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1950 std::string* error_msg) {
1951 DCHECK(out_dex_files != nullptr);
1952 DCHECK(error_msg != nullptr);
1953 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001954 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001955 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001956 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001957 DCHECK(dex_caches_object != nullptr);
1958 Runtime* const runtime = Runtime::Current();
1959 gc::Heap* const heap = runtime->GetHeap();
1960 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001961 // Check that the image is what we are expecting.
1962 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1963 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1964 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1965 image_pointer_size_);
1966 return false;
1967 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001968 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1969 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1970 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1971 expected_image_roots,
1972 header.GetImageRoots()->GetLength());
1973 return false;
1974 }
1975 StackHandleScope<3> hs(self);
1976 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1977 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1978 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1979 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001980 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001981 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1982 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001983 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001984 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001985 *error_msg = StringPrintf("Expected %d class roots but got %d",
1986 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001987 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001988 return false;
1989 }
1990 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001991 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1992 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1993 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001994 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1995 return false;
1996 }
1997 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001998 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001999 if (oat_file->GetOatHeader().GetDexFileCount() !=
2000 static_cast<uint32_t>(dex_caches->GetLength())) {
2001 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2002 "image";
2003 return false;
2004 }
2005
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002006 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002007 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2008 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002009 // TODO: Only store qualified paths.
2010 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002011 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002012 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2013 dex_file_location.c_str(),
2014 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002016 return false;
2017 }
2018
2019 if (app_image) {
2020 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2021 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002022 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002023 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002024 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002025 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002026 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002027 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002028 }
2029 }
2030 } else {
2031 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002032 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2033 this,
2034 dex_cache->GetResolvedMethods(),
2035 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002036 }
2037 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002038 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002039 }
2040 out_dex_files->push_back(std::move(dex_file));
2041 }
2042
2043 if (app_image) {
2044 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002045 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002046 // Check that the class loader resolves the same way as the ones in the image.
2047 // Image class loader [A][B][C][image dex files]
2048 // Class loader = [???][dex_elements][image dex files]
2049 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002050 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002051 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2052 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2053 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002054 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2055 *error_msg = "Unexpected BootClassLoader in app image";
2056 return false;
2057 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002058 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2059 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2060 // special case the comparison of dex files of the two class loaders, but then do full
2061 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002062 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002063 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002064 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2065 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2066 if (element != nullptr) {
2067 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002068 ObjPtr<mirror::String> name;
2069 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2070 loader_dex_file_names.push_back(name);
2071 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002072 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002073 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002074 std::string temp_error_msg;
2075 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2076 bool success = GetDexFileNames(
2077 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2078 if (success) {
2079 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2080 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2081 static_cast<size_t>(dex_caches->GetLength()));
2082 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2083 image_dex_file_names.resize(image_count);
2084 success = success && CompareDexFiles(image_dex_file_names,
2085 loader_dex_file_names,
2086 &temp_error_msg);
2087 success = success && CompareClassLoaders(soa,
2088 image_class_loader.Get(),
2089 class_loader.Get(),
2090 /*check_dex_file_names=*/ false,
2091 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002092 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002093 if (!success) {
2094 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2095 temp_error_msg.c_str());
2096 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002097 }
2098 }
2099
2100 if (kSanityCheckObjects) {
2101 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2102 auto* dex_cache = dex_caches->Get(i);
2103 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2104 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2105 if (field != nullptr) {
2106 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2107 }
2108 }
2109 }
2110 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002111 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002112 }
2113 }
2114
2115 // Set entry point to interpreter if in InterpretOnly mode.
2116 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002117 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07002118 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002119 }
2120
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002121 ClassTable* class_table = nullptr;
2122 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002123 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002124 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002125 }
2126 // If we have a class table section, read it and use it for verification in
2127 // UpdateAppImageClassLoadersAndDexCaches.
2128 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002129 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002130 const bool added_class_table = class_table_section.Size() > 0u;
2131 if (added_class_table) {
2132 const uint64_t start_time2 = NanoTime();
2133 size_t read_count = 0;
2134 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2135 /*make copy*/false,
2136 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002137 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002138 }
2139 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002140 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002141
2142 {
2143 ScopedTrace trace("AppImage:UpdateClassLoaders");
2144 // Update class loader and resolved strings. If added_class_table is false, the resolved
2145 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002146 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002147 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002148 // Note: We probably don't need the read barrier unless we copy the app image objects into
2149 // the region space.
2150 ObjPtr<mirror::Class> klass(root.Read());
2151 // Do not update class loader for boot image classes where the app image
2152 // class loader is only the initiating loader but not the defining loader.
2153 // Avoid read barrier since we are comparing against null.
2154 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2155 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2156 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002157 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002158 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002159
Vladimir Marko305c38b2018-02-14 11:50:07 +00002160 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002161 // Every class in the app image has initially SubtypeCheckInfo in the
2162 // Uninitialized state.
2163 //
2164 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2165 // after class initialization is complete. The app image ClassStatus as-is
2166 // are almost all ClassStatus::Initialized, and being in the
2167 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2168 //
2169 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2170 //
2171 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002172 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002173 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2174 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002175 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002176 }
2177 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002178 }
2179 if (!oat_file->GetBssGcRoots().empty()) {
2180 // Insert oat file to class table for visiting .bss GC roots.
2181 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002182 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002183
Mathieu Chartier69731002016-03-02 16:08:31 -08002184 if (added_class_table) {
2185 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2186 class_table->AddClassSet(std::move(temp_set));
2187 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002188
Mathieu Chartier69731002016-03-02 16:08:31 -08002189 if (kIsDebugBuild && app_image) {
2190 // This verification needs to happen after the classes have been added to the class loader.
2191 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002192 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002193 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002194 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002195
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002196 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002197 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002198}
2199
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002200bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002201 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2202 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002203}
2204
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002205void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002206 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2207 // enabling tracing requires the mutator lock, there are no race conditions here.
2208 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002209 Thread* const self = Thread::Current();
2210 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002211 if (kUseReadBarrier) {
2212 // We do not track new roots for CC.
2213 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2214 kVisitRootFlagClearRootLog |
2215 kVisitRootFlagStartLoggingNewRoots |
2216 kVisitRootFlagStopLoggingNewRoots));
2217 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002218 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002219 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2220 // There is 3 GC cases to handle:
2221 // Non moving concurrent:
2222 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002223 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002224 //
2225 // Moving non-concurrent:
2226 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2227 // To prevent missing roots, this case needs to ensure that there is no
2228 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2229 // class which is in the class table.
2230 //
2231 // Moving concurrent:
2232 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2233 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002234 //
2235 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2236 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2237 // these objects.
2238 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002239 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002240 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002241 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002242 for (const ClassLoaderData& data : class_loaders_) {
2243 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2244 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2245 }
2246 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002247 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002248 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002249 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002250 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002251 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002252 // Concurrent moving GC marked new roots through the to-space invariant.
2253 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002254 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002255 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2256 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2257 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2258 if (old_ref != nullptr) {
2259 DCHECK(old_ref->IsClass());
2260 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2261 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2262 // Concurrent moving GC marked new roots through the to-space invariant.
2263 CHECK_EQ(new_ref, old_ref);
2264 }
2265 }
2266 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002267 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002268 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002269 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002270 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002271 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002272 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002273 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002274 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002275 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002276 }
2277 // We deliberately ignore the class roots in the image since we
2278 // handle image roots by using the MS/CMS rescanning of dirty cards.
2279}
2280
Brian Carlstroma663ea52011-08-19 23:33:41 -07002281// Keep in sync with InitCallback. Anything we visit, we need to
2282// reinit references to when reinitializing a ClassLinker from a
2283// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002284void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002285 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002286 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002287 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2288 // unloading if we are marking roots.
2289 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002290}
2291
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002292class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2293 public:
2294 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2295 : visitor_(visitor),
2296 done_(false) {}
2297
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002298 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002299 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002300 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002301 if (!done_ && class_table != nullptr) {
2302 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2303 if (!class_table->Visit(visitor)) {
2304 // If the visitor ClassTable returns false it means that we don't need to continue.
2305 done_ = true;
2306 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002307 }
2308 }
2309
2310 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002311 // Class visitor that limits the class visits from a ClassTable to the classes with
2312 // the provided defining class loader. This filter is used to avoid multiple visits
2313 // of the same class which can be recorded for multiple initiating class loaders.
2314 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2315 public:
2316 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2317 ClassVisitor* visitor)
2318 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2319
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002320 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002321 if (klass->GetClassLoader() != defining_class_loader_) {
2322 return true;
2323 }
2324 return (*visitor_)(klass);
2325 }
2326
2327 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2328 ClassVisitor* const visitor_;
2329 };
2330
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002331 ClassVisitor* const visitor_;
2332 // If done is true then we don't need to do any more visiting.
2333 bool done_;
2334};
2335
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002336void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002337 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002338 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2339 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002340 }
2341}
2342
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002343void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002344 Thread* const self = Thread::Current();
2345 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2346 // Not safe to have thread suspension when we are holding a lock.
2347 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002348 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002349 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002350 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002351 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002352 }
2353}
2354
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002355class GetClassesInToVector : public ClassVisitor {
2356 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002357 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002358 classes_.push_back(klass);
2359 return true;
2360 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002361 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002362};
2363
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002364class GetClassInToObjectArray : public ClassVisitor {
2365 public:
2366 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2367 : arr_(arr), index_(0) {}
2368
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002369 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002370 ++index_;
2371 if (index_ <= arr_->GetLength()) {
2372 arr_->Set(index_ - 1, klass);
2373 return true;
2374 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002375 return false;
2376 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002377
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002378 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002379 return index_ <= arr_->GetLength();
2380 }
2381
2382 private:
2383 mirror::ObjectArray<mirror::Class>* const arr_;
2384 int32_t index_;
2385};
2386
2387void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002388 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2389 // is avoiding duplicates.
2390 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002391 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002392 GetClassesInToVector accumulator;
2393 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002394 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002395 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002396 return;
2397 }
2398 }
2399 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002400 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002401 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002402 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002403 // We size the array assuming classes won't be added to the class table during the visit.
2404 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002405 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002406 size_t class_table_size;
2407 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002408 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002409 // Add 100 in case new classes get loaded when we are filling in the object array.
2410 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002411 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002412 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002413 classes.Assign(
2414 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002415 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002416 GetClassInToObjectArray accumulator(classes.Get());
2417 VisitClasses(&accumulator);
2418 if (accumulator.Succeeded()) {
2419 break;
2420 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002421 }
2422 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2423 // If the class table shrank during creation of the clases array we expect null elements. If
2424 // the class table grew then the loop repeats. If classes are created after the loop has
2425 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002426 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002427 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002428 return;
2429 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002430 }
2431 }
2432}
2433
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002434ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002435 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002436 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002437 // CHA unloading analysis is not needed. No negative consequences are expected because
2438 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002439 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002440 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002441 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002442}
2443
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002444void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002445 Runtime* const runtime = Runtime::Current();
2446 JavaVMExt* const vm = runtime->GetJavaVM();
2447 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002448 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002449 if (runtime->GetJit() != nullptr) {
2450 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2451 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002452 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002453 code_cache->RemoveMethodsIn(self, *data.allocator);
2454 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002455 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002456 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002457 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002458 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002459 // Cleanup references to single implementation ArtMethods that will be deleted.
2460 if (cleanup_cha) {
2461 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2462 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2463 }
2464
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002465 delete data.allocator;
2466 delete data.class_table;
2467}
2468
Vladimir Markobcf17522018-06-01 13:14:32 +01002469ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2470 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002471 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002472 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2473 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002474}
2475
Vladimir Markobcf17522018-06-01 13:14:32 +01002476ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2477 Thread* self,
2478 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002479 StackHandleScope<1> hs(self);
2480 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002481 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002482 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002483 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002484 self->AssertPendingOOMException();
2485 return nullptr;
2486 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002487 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002488 if (location == nullptr) {
2489 self->AssertPendingOOMException();
2490 return nullptr;
2491 }
2492 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002493 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002494}
2495
Vladimir Markobcf17522018-06-01 13:14:32 +01002496ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2497 const DexFile& dex_file,
2498 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002499 ObjPtr<mirror::String> location = nullptr;
2500 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002501 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002502 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002503 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002504 mirror::DexCache::InitializeDexCache(self,
2505 dex_cache,
2506 location,
2507 &dex_file,
2508 linear_alloc,
2509 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002510 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002511 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002512}
2513
Roland Levillain0e840272018-08-23 19:55:30 +01002514template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002515ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2516 ObjPtr<mirror::Class> java_lang_Class,
2517 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002518 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002519 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002520 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002521 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002522 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2523 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002524 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002525 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002526 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002527 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002528 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002529}
2530
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002531ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002532 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002533}
2534
Roland Levillain0e840272018-08-23 19:55:30 +01002535ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2536 ObjPtr<mirror::Class> java_lang_Class) {
2537 // We make this class non-movable for the unlikely case where it were to be
2538 // moved by a sticky-bit (minor) collection when using the Generational
2539 // Concurrent Copying (CC) collector, potentially creating a stale reference
2540 // in the `klass_` field of one of its instances allocated in the Large-Object
2541 // Space (LOS) -- see the comment about the dirty card scanning logic in
2542 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002543 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002544 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2545}
2546
Vladimir Markobcf17522018-06-01 13:14:32 +01002547ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002548 Thread* self,
2549 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002550 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002551 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002552}
2553
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002554ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2555 const char* descriptor,
2556 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002557 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002558 if (kIsDebugBuild) {
2559 StackHandleScope<1> hs(self);
2560 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2561 Thread::PoisonObjectPointersIfDebug();
2562 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002563
2564 // For temporary classes we must wait for them to be retired.
2565 if (init_done_ && klass->IsTemp()) {
2566 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002567 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002568 ThrowEarlierClassFailure(klass);
2569 return nullptr;
2570 }
2571 StackHandleScope<1> hs(self);
2572 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2573 ObjectLock<mirror::Class> lock(self, h_class);
2574 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002575 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002576 lock.WaitIgnoringInterrupts();
2577 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002578 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002579 ThrowEarlierClassFailure(h_class.Get());
2580 return nullptr;
2581 }
2582 CHECK(h_class->IsRetired());
2583 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002584 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002585 }
2586
Brian Carlstromaded5f72011-10-07 17:15:04 -07002587 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002588 size_t index = 0;
2589 // Maximum number of yield iterations until we start sleeping.
2590 static const size_t kNumYieldIterations = 1000;
2591 // How long each sleep is in us.
2592 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002593 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002594 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002595 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002596 {
2597 ObjectTryLock<mirror::Class> lock(self, h_class);
2598 // Can not use a monitor wait here since it may block when returning and deadlock if another
2599 // thread has locked klass.
2600 if (lock.Acquired()) {
2601 // Check for circular dependencies between classes, the lock is required for SetStatus.
2602 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2603 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002604 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002605 return nullptr;
2606 }
2607 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002608 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002609 {
2610 // Handle wrapper deals with klass moving.
2611 ScopedThreadSuspension sts(self, kSuspended);
2612 if (index < kNumYieldIterations) {
2613 sched_yield();
2614 } else {
2615 usleep(kSleepDurationUS);
2616 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002618 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002619 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002620
Vladimir Marko72ab6842017-01-20 19:32:50 +00002621 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002622 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002623 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002624 }
2625 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002626 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002627 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002628 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002629}
2630
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002631using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002632
2633// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002634ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002635 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002636 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002637 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002638 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002639 return ClassPathEntry(dex_file, dex_class_def);
2640 }
2641 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002642 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002643}
2644
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002645bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2646 Thread* self,
2647 const char* descriptor,
2648 size_t hash,
2649 Handle<mirror::ClassLoader> class_loader,
2650 /*out*/ ObjPtr<mirror::Class>* result) {
2651 ArtField* field =
2652 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2653 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2654 if (raw_shared_libraries == nullptr) {
2655 return true;
2656 }
2657
2658 StackHandleScope<2> hs(self);
2659 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2660 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2661 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2662 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2663 temp_loader.Assign(shared_libraries->Get(i));
2664 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2665 return false; // One of the shared libraries is not supported.
2666 }
2667 if (*result != nullptr) {
2668 return true; // Found the class up the chain.
2669 }
2670 }
2671 return true;
2672}
2673
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002674bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2675 Thread* self,
2676 const char* descriptor,
2677 size_t hash,
2678 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002679 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002680 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002681 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002682 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002683 return true;
2684 }
2685
David Brazdil05909d82018-12-06 16:25:16 +00002686 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002687 // For regular path or dex class loader the search order is:
2688 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002689 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002690 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002691
Calin Juravlecdd49122017-07-05 20:09:53 -07002692 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2693 StackHandleScope<1> hs(self);
2694 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2695 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2696 return false; // One of the parents is not supported.
2697 }
2698 if (*result != nullptr) {
2699 return true; // Found the class up the chain.
2700 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002701
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002702 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2703 return false; // One of the shared library loader is not supported.
2704 }
2705 if (*result != nullptr) {
2706 return true; // Found the class in a shared library.
2707 }
2708
Calin Juravlecdd49122017-07-05 20:09:53 -07002709 // Search the current class loader classpath.
2710 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002711 return true;
2712 }
2713
Calin Juravlecdd49122017-07-05 20:09:53 -07002714 if (IsDelegateLastClassLoader(soa, class_loader)) {
2715 // For delegate last, the search order is:
2716 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002717 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002718 // - class loader dex files
2719 // - parent
2720 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2721 if (*result != nullptr) {
2722 return true; // The class is part of the boot class path.
2723 }
2724
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002725 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2726 return false; // One of the shared library loader is not supported.
2727 }
2728 if (*result != nullptr) {
2729 return true; // Found the class in a shared library.
2730 }
2731
Calin Juravlecdd49122017-07-05 20:09:53 -07002732 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2733 if (*result != nullptr) {
2734 return true; // Found the class in the current class loader
2735 }
2736
2737 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2738 StackHandleScope<1> hs(self);
2739 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2740 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2741 }
2742
2743 // Unsupported class loader.
2744 *result = nullptr;
2745 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002746}
2747
2748// Finds the class in the boot class loader.
2749// If the class is found the method returns the resolved class. Otherwise it returns null.
2750ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2751 const char* descriptor,
2752 size_t hash) {
2753 ObjPtr<mirror::Class> result = nullptr;
2754 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2755 if (pair.second != nullptr) {
2756 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2757 if (klass != nullptr) {
2758 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002759 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002760 result = DefineClass(self,
2761 descriptor,
2762 hash,
2763 ScopedNullHandle<mirror::ClassLoader>(),
2764 *pair.first,
2765 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002766 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002767 if (result == nullptr) {
2768 CHECK(self->IsExceptionPending()) << descriptor;
2769 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002770 }
2771 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002772 return result;
2773}
Andreas Gampef865ea92015-04-13 22:14:19 -07002774
Calin Juravle415dc3d2017-06-28 11:03:12 -07002775ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2776 ScopedObjectAccessAlreadyRunnable& soa,
2777 const char* descriptor,
2778 size_t hash,
2779 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002780 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2781 IsInMemoryDexClassLoader(soa, class_loader) ||
2782 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002783 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002784
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002785 ObjPtr<mirror::Class> ret;
2786 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002787 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002788 if (dex_class_def != nullptr) {
2789 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2790 descriptor,
2791 hash,
2792 class_loader,
2793 *cp_dex_file,
2794 *dex_class_def);
2795 if (klass == nullptr) {
2796 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2797 soa.Self()->ClearException();
2798 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002799 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002800 ret = klass;
2801 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002802 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002803 return true; // Continue with the next DexFile.
2804 };
2805
2806 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2807 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002808}
2809
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002810ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2811 const char* descriptor,
2812 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002813 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002814 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002815 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002816 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002817 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002818 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2819 // for primitive classes that aren't backed by dex files.
2820 return FindPrimitiveClass(descriptor[0]);
2821 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002822 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002823 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002824 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002825 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002826 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002827 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002828 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002829 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002830 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002831 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002832 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002833 return DefineClass(self,
2834 descriptor,
2835 hash,
2836 ScopedNullHandle<mirror::ClassLoader>(),
2837 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002838 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002839 } else {
2840 // The boot class loader is searched ahead of the application class loader, failures are
2841 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2842 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002843 ObjPtr<mirror::Throwable> pre_allocated =
2844 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002845 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002846 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002847 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002848 }
2849 ObjPtr<mirror::Class> result_ptr;
2850 bool descriptor_equals;
2851 if (descriptor[0] == '[') {
2852 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2853 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2854 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2855 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002856 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002857 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002858 bool known_hierarchy =
2859 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2860 if (result_ptr != nullptr) {
2861 // The chain was understood and we found the class. We still need to add the class to
2862 // the class table to protect from racy programs that can try and redefine the path list
2863 // which would change the Class<?> returned for subsequent evaluation of const-class.
2864 DCHECK(known_hierarchy);
2865 DCHECK(result_ptr->DescriptorEquals(descriptor));
2866 descriptor_equals = true;
2867 } else {
2868 // Either the chain wasn't understood or the class wasn't found.
2869 //
2870 // If the chain was understood but we did not find the class, let the Java-side
2871 // rediscover all this and throw the exception with the right stack trace. Note that
2872 // the Java-side could still succeed for racy programs if another thread is actively
2873 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002874
Alex Light185a4612018-10-04 15:54:25 -07002875 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002876 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002877 // Oops, we can't call into java so we can't run actual class-loader code.
2878 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002879 ObjPtr<mirror::Throwable> pre_allocated =
2880 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2881 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002882 return nullptr;
2883 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002884
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002885 // Inlined DescriptorToDot(descriptor) with extra validation.
2886 //
2887 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2888 // the DescriptorEquals() check below and give a confusing error message. For example,
2889 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2890 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2891 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2892 size_t descriptor_length = strlen(descriptor);
2893 if (UNLIKELY(descriptor[0] != 'L') ||
2894 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2895 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2896 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2897 return nullptr;
2898 }
2899 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2900 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2901
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002902 ScopedLocalRef<jobject> class_loader_object(
2903 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002904 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2905 {
2906 ScopedThreadStateChange tsc(self, kNative);
2907 ScopedLocalRef<jobject> class_name_object(
2908 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2909 if (class_name_object.get() == nullptr) {
2910 DCHECK(self->IsExceptionPending()); // OOME.
2911 return nullptr;
2912 }
2913 CHECK(class_loader_object.get() != nullptr);
2914 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2915 WellKnownClasses::java_lang_ClassLoader_loadClass,
2916 class_name_object.get()));
2917 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002918 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002919 // broken loader - throw NPE to be compatible with Dalvik
2920 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2921 class_name_string.c_str()).c_str());
2922 return nullptr;
2923 }
2924 result_ptr = soa.Decode<mirror::Class>(result.get());
2925 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002926 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002927 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002928 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002929
2930 if (self->IsExceptionPending()) {
2931 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2932 // However, to comply with the RI behavior, first check if another thread succeeded.
2933 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2934 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2935 self->ClearException();
2936 return EnsureResolved(self, descriptor, result_ptr);
2937 }
2938 return nullptr;
2939 }
2940
2941 // Try to insert the class to the class table, checking for mismatch.
2942 ObjPtr<mirror::Class> old;
2943 {
2944 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2945 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2946 old = class_table->Lookup(descriptor, hash);
2947 if (old == nullptr) {
2948 old = result_ptr; // For the comparison below, after releasing the lock.
2949 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002950 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002951 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002952 } // else throw below, after releasing the lock.
2953 }
2954 }
2955 if (UNLIKELY(old != result_ptr)) {
2956 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2957 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2958 mirror::Class* loader_class = class_loader->GetClass();
2959 const char* loader_class_name =
2960 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2961 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2962 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2963 << DescriptorToDot(descriptor) << "\").";
2964 return EnsureResolved(self, descriptor, old);
2965 }
2966 if (UNLIKELY(!descriptor_equals)) {
2967 std::string result_storage;
2968 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2969 std::string loader_storage;
2970 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2971 ThrowNoClassDefFoundError(
2972 "Initiating class loader of type %s returned class %s instead of %s.",
2973 DescriptorToDot(loader_class_name).c_str(),
2974 DescriptorToDot(result_name).c_str(),
2975 DescriptorToDot(descriptor).c_str());
2976 return nullptr;
2977 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002978 // Success.
2979 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002980}
2981
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002982ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
2983 const char* descriptor,
2984 size_t hash,
2985 Handle<mirror::ClassLoader> class_loader,
2986 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002987 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002988 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002989 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002990
Brian Carlstromaded5f72011-10-07 17:15:04 -07002991 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002992 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002993 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002994 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002995 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002996 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002997 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002998 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002999 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003000 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003001 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003002 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003003 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003004 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003005 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003006 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003007 }
3008
Alex Lighte9f61032018-09-24 16:04:51 -07003009 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3010 // code to be executed. We put it up here so we can avoid all the allocations associated with
3011 // creating the class. This can happen with (eg) jit threads.
3012 if (!self->CanLoadClasses()) {
3013 // Make sure we don't try to load anything, potentially causing an infinite loop.
3014 ObjPtr<mirror::Throwable> pre_allocated =
3015 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3016 self->SetException(pre_allocated);
3017 return nullptr;
3018 }
3019
Andreas Gampefa4333d2017-02-14 11:10:34 -08003020 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003021 // Allocate a class with the status of not ready.
3022 // Interface object should get the right size here. Regular class will
3023 // figure out the right size later and be replaced with one of the right
3024 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003025 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003026 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003027 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003028 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003029 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003030 }
Alex Lightb0f11922017-01-23 14:25:17 -08003031 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3032 // nothing.
3033 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003034 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003035 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3036 // will only be called once.
3037 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3038 klass,
3039 class_loader,
3040 dex_file,
3041 dex_class_def,
3042 &new_dex_file,
3043 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003044 // Check to see if an exception happened during runtime callbacks. Return if so.
3045 if (self->IsExceptionPending()) {
3046 return nullptr;
3047 }
Alex Lightb0f11922017-01-23 14:25:17 -08003048 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003049 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003050 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003051 return nullptr;
3052 }
3053 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003054 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003055
Jeff Hao848f70a2014-01-15 13:49:50 -08003056 // Mark the string class by setting its access flag.
3057 if (UNLIKELY(!init_done_)) {
3058 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3059 klass->SetStringClass();
3060 }
3061 }
3062
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003063 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003064 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003065 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003066 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003067
Mathieu Chartier590fee92013-09-13 13:46:47 -07003068 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003069 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003070 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003071 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3072 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003073 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003074 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003075
Mathieu Chartierc7853442015-03-27 14:35:38 -07003076 // Load the fields and other things after we are inserted in the table. This is so that we don't
3077 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3078 // other reason is that the field roots are only visited from the class table. So we need to be
3079 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003080 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003081 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003082 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003083 // An exception occured during load, set status to erroneous while holding klass' lock in case
3084 // notification is necessary.
3085 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003086 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003087 }
3088 return nullptr;
3089 }
3090
Brian Carlstromaded5f72011-10-07 17:15:04 -07003091 // Finish loading (if necessary) by finding parents
3092 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003093 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003094 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003095 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003096 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003097 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003098 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003099 }
3100 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003101
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003102 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003103 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003104 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003105
Brian Carlstromaded5f72011-10-07 17:15:04 -07003106 // Link the class (if necessary)
3107 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003108 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003109 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003110
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003111 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003112 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003113 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003114 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003115 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003116 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003117 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003118 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003119 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003120 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003121 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003122
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003123 // Instrumentation may have updated entrypoints for all methods of all
3124 // classes. However it could not update methods of this class while we
3125 // were loading it. Now the class is resolved, we can update entrypoints
3126 // as required by instrumentation.
3127 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3128 // We must be in the kRunnable state to prevent instrumentation from
3129 // suspending all threads to update entrypoints while we are doing it
3130 // for this class.
3131 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003132 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003133 }
3134
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003135 /*
3136 * We send CLASS_PREPARE events to the debugger from here. The
3137 * definition of "preparation" is creating the static fields for a
3138 * class and initializing them to the standard default values, but not
3139 * executing any code (that comes later, during "initialization").
3140 *
3141 * We did the static preparation in LinkClass.
3142 *
3143 * The class has been prepared and resolved but possibly not yet verified
3144 * at this point.
3145 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003146 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003147
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003148 // Notify native debugger of the new class and its layout.
3149 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3150
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003151 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003152}
3153
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003154uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003155 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003156 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003157 size_t num_8 = 0;
3158 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003159 size_t num_32 = 0;
3160 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003161 ClassAccessor accessor(dex_file, dex_class_def);
3162 // We allow duplicate definitions of the same field in a class_data_item
3163 // but ignore the repeated indexes here, b/21868015.
3164 uint32_t last_field_idx = dex::kDexNoIndex;
3165 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3166 uint32_t field_idx = field.GetIndex();
3167 // Ordering enforced by DexFileVerifier.
3168 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3169 if (UNLIKELY(field_idx == last_field_idx)) {
3170 continue;
3171 }
3172 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003173 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003174 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3175 char c = descriptor[0];
3176 switch (c) {
3177 case 'L':
3178 case '[':
3179 num_ref++;
3180 break;
3181 case 'J':
3182 case 'D':
3183 num_64++;
3184 break;
3185 case 'I':
3186 case 'F':
3187 num_32++;
3188 break;
3189 case 'S':
3190 case 'C':
3191 num_16++;
3192 break;
3193 case 'B':
3194 case 'Z':
3195 num_8++;
3196 break;
3197 default:
3198 LOG(FATAL) << "Unknown descriptor: " << c;
3199 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003200 }
3201 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003202 return mirror::Class::ComputeClassSize(false,
3203 0,
3204 num_8,
3205 num_16,
3206 num_32,
3207 num_64,
3208 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003209 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003210}
3211
Alex Lightfc49fec2018-01-16 22:28:36 +00003212// Special case to get oat code without overwriting a trampoline.
3213const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003214 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003215 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003216 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003217 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003218 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3219 if (code != nullptr) {
3220 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003221 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003222 if (method->IsNative()) {
3223 // No code and native? Use generic trampoline.
3224 return GetQuickGenericJniStub();
3225 }
3226 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003227}
3228
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003229bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003230 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003231 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3232 return false;
3233 }
3234
Elliott Hughes956af0f2014-12-11 14:34:28 -08003235 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003236 return true;
3237 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003238
3239 Runtime* runtime = Runtime::Current();
3240 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3241 if (instr->InterpretOnly()) {
3242 return true;
3243 }
3244
3245 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3246 // Doing this check avoids doing compiled/interpreter transitions.
3247 return true;
3248 }
3249
3250 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
3251 // Force the use of interpreter when it is required by the debugger.
3252 return true;
3253 }
3254
Alex Light8f34aba2017-10-09 13:46:32 -07003255 if (Thread::Current()->IsAsyncExceptionPending()) {
3256 // Force use of interpreter to handle async-exceptions
3257 return true;
3258 }
3259
Alex Light2d441b12018-06-08 15:33:21 -07003260 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3261 const void* instr_target = instr->GetCodeForInvoke(method);
3262 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3263 return ShouldUseInterpreterEntrypoint(method, instr_target);
3264 }
3265
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003266 if (runtime->IsJavaDebuggable()) {
3267 // For simplicity, we ignore precompiled code and go to the interpreter
3268 // assuming we don't already have jitted code.
3269 // We could look at the oat file where `quick_code` is being defined,
3270 // and check whether it's been compiled debuggable, but we decided to
3271 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003272 jit::Jit* jit = Runtime::Current()->GetJit();
3273 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3274 }
3275
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003276 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003277 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003278 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003279 // since we want to JIT it (at first use) with extra stackmaps for native
3280 // debugging. We keep however all AOT code from the boot image,
3281 // since the JIT-at-first-use is blocking and would result in non-negligible
3282 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003283 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003284 }
3285
3286 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003287}
3288
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003289void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003290 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003291 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003292 if (klass->NumDirectMethods() == 0) {
3293 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003294 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003295 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003296 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003297 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003298 return; // OAT file unavailable.
3299 }
Ian Rogers19846512012-02-24 11:42:47 -08003300 }
Alex Light64ad14d2014-08-19 14:23:13 -07003301
Mathieu Chartierf8322842014-05-16 10:59:25 -07003302 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003303 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3304 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3305 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003306 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003307 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003308 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003309 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3310 klass->GetDexClassDefIndex(),
3311 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003312 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003313 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003314 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003315 if (!method->IsStatic()) {
3316 // Only update static methods.
3317 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003318 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003319 const void* quick_code = nullptr;
3320 if (has_oat_class) {
3321 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003322 quick_code = oat_method.GetQuickCode();
3323 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003324 // Check whether the method is native, in which case it's generic JNI.
3325 if (quick_code == nullptr && method->IsNative()) {
3326 quick_code = GetQuickGenericJniStub();
3327 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003328 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003329 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003330 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003331 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003332 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003333 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003334}
3335
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003336// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3337// method. Should only be called on non-invokable methods.
3338inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003339 DCHECK(method != nullptr);
3340 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003341 method->SetEntryPointFromQuickCompiledCodePtrSize(
3342 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3343 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003344}
3345
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003346static void LinkCode(ClassLinker* class_linker,
3347 ArtMethod* method,
3348 const OatFile::OatClass* oat_class,
3349 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003350 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003351 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003352 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003353 // The following code only applies to a non-compiler runtime.
3354 return;
3355 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003356 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003357 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003358 if (oat_class != nullptr) {
3359 // Every kind of method should at least get an invoke stub from the oat_method.
3360 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003361 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003362 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003363 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003364
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003365 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003366 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003367 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003368
Alex Light9139e002015-10-09 15:59:48 -07003369 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003370 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003371 return;
3372 }
Ian Rogers19846512012-02-24 11:42:47 -08003373
3374 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003375 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003376 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3377 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003378 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003379 } else if (quick_code == nullptr && method->IsNative()) {
3380 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003381 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003382 // Set entry point from compiled code if there's no code or in interpreter only mode.
3383 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003384 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003385
Ian Rogers62d6c772013-02-27 08:32:07 -08003386 if (method->IsNative()) {
3387 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003388 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003389
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003390 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003391 // We have a native method here without code. Then it should have either the generic JNI
3392 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3393 // TODO: this doesn't handle all the cases where trampolines may be installed.
3394 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003395 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3396 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003397 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003398 }
3399}
3400
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003401void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003402 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003403 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003404 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003405 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003406 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003407 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003408 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003409 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003410
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003411 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003412 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003413 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003414 klass->SetAccessFlags(access_flags);
3415 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003416 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003417 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003418
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003419 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003420 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003421}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003422
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003423LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3424 LinearAlloc* allocator,
3425 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003426 if (length == 0) {
3427 return nullptr;
3428 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003429 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3430 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3431 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003432 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003433 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003434 CHECK(ret != nullptr);
3435 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3436 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003437}
3438
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003439LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3440 LinearAlloc* allocator,
3441 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003442 if (length == 0) {
3443 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003444 }
Vladimir Marko14632852015-08-17 12:07:23 +01003445 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3446 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003447 const size_t storage_size =
3448 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003449 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003450 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003451 CHECK(ret != nullptr);
3452 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003453 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003454 }
3455 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003456}
3457
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003458LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003459 if (class_loader == nullptr) {
3460 return Runtime::Current()->GetLinearAlloc();
3461 }
3462 LinearAlloc* allocator = class_loader->GetAllocator();
3463 DCHECK(allocator != nullptr);
3464 return allocator;
3465}
3466
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003467LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003468 if (class_loader == nullptr) {
3469 return Runtime::Current()->GetLinearAlloc();
3470 }
3471 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3472 LinearAlloc* allocator = class_loader->GetAllocator();
3473 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003474 RegisterClassLoader(class_loader);
3475 allocator = class_loader->GetAllocator();
3476 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003477 }
3478 return allocator;
3479}
3480
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003481void ClassLinker::LoadClass(Thread* self,
3482 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003483 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003484 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003485 ClassAccessor accessor(dex_file,
3486 dex_class_def,
3487 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003488 if (!accessor.HasClassData()) {
3489 return;
3490 }
3491 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003492 {
3493 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3494 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003495 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003496 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003497 // We allow duplicate definitions of the same field in a class_data_item
3498 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003499 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003500 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3501 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003502 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003503 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3504 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003505 accessor.NumInstanceFields());
3506 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003507 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003508 uint32_t last_static_field_idx = 0u;
3509 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003510
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003511 // Methods
3512 bool has_oat_class = false;
3513 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3514 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3515 : OatFile::OatClass::Invalid();
3516 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3517 klass->SetMethodsPtr(
3518 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3519 accessor.NumDirectMethods(),
3520 accessor.NumVirtualMethods());
3521 size_t class_def_method_index = 0;
3522 uint32_t last_dex_method_index = dex::kDexNoIndex;
3523 size_t last_class_def_method_index = 0;
3524
3525 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3526 // methods needs to decode all of the fields.
3527 accessor.VisitFieldsAndMethods([&](
3528 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3529 uint32_t field_idx = field.GetIndex();
3530 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3531 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3532 LoadField(field, klass, &sfields->At(num_sfields));
3533 ++num_sfields;
3534 last_static_field_idx = field_idx;
3535 }
3536 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3537 uint32_t field_idx = field.GetIndex();
3538 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3539 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3540 LoadField(field, klass, &ifields->At(num_ifields));
3541 ++num_ifields;
3542 last_instance_field_idx = field_idx;
3543 }
3544 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3545 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3546 image_pointer_size_);
3547 LoadMethod(dex_file, method, klass, art_method);
3548 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3549 uint32_t it_method_index = method.GetIndex();
3550 if (last_dex_method_index == it_method_index) {
3551 // duplicate case
3552 art_method->SetMethodIndex(last_class_def_method_index);
3553 } else {
3554 art_method->SetMethodIndex(class_def_method_index);
3555 last_dex_method_index = it_method_index;
3556 last_class_def_method_index = class_def_method_index;
3557 }
3558 ++class_def_method_index;
3559 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3560 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3561 class_def_method_index - accessor.NumDirectMethods(),
3562 image_pointer_size_);
3563 LoadMethod(dex_file, method, klass, art_method);
3564 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3565 ++class_def_method_index;
3566 });
3567
3568 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003569 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003570 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3571 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3572 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003573 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3574 if (sfields != nullptr) {
3575 sfields->SetSize(num_sfields);
3576 }
3577 if (ifields != nullptr) {
3578 ifields->SetSize(num_ifields);
3579 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003580 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003581 // Set the field arrays.
3582 klass->SetSFieldsPtr(sfields);
3583 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003584 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003585 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003586 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003587 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003588 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003589 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003590}
3591
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003592void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003593 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003594 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003595 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003596 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003597 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003598
David Brazdil85865692018-10-30 17:26:20 +00003599 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3600 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003601}
3602
Mathieu Chartier268764d2016-09-13 12:09:38 -07003603void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003604 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003605 Handle<mirror::Class> klass,
3606 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003607 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003608 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003609 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003610
Mathieu Chartier268764d2016-09-13 12:09:38 -07003611 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003612 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003613 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003614 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003615
David Brazdil85865692018-10-30 17:26:20 +00003616 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3617 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003618
Ian Rogersdfb325e2013-10-30 01:00:44 -07003619 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003620 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003621 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3622 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003623 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003624 klass->SetFinalizable();
3625 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003626 std::string temp;
3627 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003628 // The Enum class declares a "final" finalize() method to prevent subclasses from
3629 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3630 // subclasses, so we exclude it here.
3631 // We also want to avoid setting the flag on Object, where we know that finalize() is
3632 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003633 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3634 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003635 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003636 }
3637 }
3638 }
3639 } else if (method_name[0] == '<') {
3640 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003641 bool is_init = (strcmp("<init>", method_name) == 0);
3642 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003643 if (UNLIKELY(!is_init && !is_clinit)) {
3644 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3645 } else {
3646 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3647 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003648 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003649 access_flags |= kAccConstructor;
3650 }
3651 }
3652 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003653 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3654 // Check if the native method is annotated with @FastNative or @CriticalNative.
3655 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3656 dex_file, dst->GetClassDef(), dex_method_idx);
3657 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003658 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003659 // Must be done after SetAccessFlags since IsAbstract depends on it.
3660 if (klass->IsInterface() && dst->IsAbstract()) {
3661 dst->CalculateAndSetImtIndex();
3662 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003663}
3664
Ian Rogers7b078e82014-09-10 14:44:24 -07003665void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003666 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003667 self,
3668 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003669 Runtime::Current()->GetLinearAlloc());
3670 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003671 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003672}
3673
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003674void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003675 ObjPtr<mirror::DexCache> dex_cache) {
3676 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003677 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003678 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003679 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003680}
3681
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003682void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003683 ObjPtr<mirror::DexCache> dex_cache,
3684 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003685 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003686 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003687 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003688 // For app images, the dex cache location may be a suffix of the dex file location since the
3689 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003690 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3691 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003692 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3693 std::string dex_file_location = dex_file.GetLocation();
3694 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003695 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003696 // Take suffix.
3697 const std::string dex_file_suffix = dex_file_location.substr(
3698 dex_file_location.length() - dex_cache_length,
3699 dex_cache_length);
3700 // Example dex_cache location is SettingsProvider.apk and
3701 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003702 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003703 const OatFile* oat_file =
3704 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003705 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3706 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3707 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3708 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003709 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003710 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3711 DexCacheData data = *it;
3712 if (self->IsJWeakCleared(data.weak_root)) {
3713 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003714 it = dex_caches_.erase(it);
3715 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003716 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003717 it->dex_file->GetOatDexFile() != nullptr &&
3718 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003719 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003720 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003721 ++it;
3722 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003723 }
Vladimir Markob066d432018-01-03 13:14:37 +00003724 if (initialize_oat_file_data) {
3725 // Initialize the .data.bimg.rel.ro section.
3726 if (!oat_file->GetBootImageRelocations().empty()) {
3727 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3728 CheckedCall(mprotect,
3729 "un-protect boot image relocations",
3730 reloc_begin,
3731 oat_file->DataBimgRelRoSize(),
3732 PROT_READ | PROT_WRITE);
3733 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3734 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3735 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3736 const_cast<uint32_t&>(relocation) += boot_image_begin;
3737 }
3738 CheckedCall(mprotect,
3739 "protect boot image relocations",
3740 reloc_begin,
3741 oat_file->DataBimgRelRoSize(),
3742 PROT_READ);
3743 }
3744
3745 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003746 // TODO: Pre-initialize from boot/app image?
3747 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3748 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3749 entry = resolution_method;
3750 }
3751 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003752 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003753 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003754 DexCacheData data;
3755 data.weak_root = dex_cache_jweak;
3756 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003757 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003758 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003759 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003760 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3761 // path dex caches without an image.
3762 data.class_table->InsertStrongRoot(dex_cache);
3763 if (class_loader != nullptr) {
3764 // Since we added a strong root to the class table, do the write barrier as required for
3765 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003766 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003767 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003768 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003769}
3770
Vladimir Markocd556b02017-02-03 11:47:34 +00003771ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3772 return data.IsValid()
3773 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3774 : nullptr;
3775}
3776
3777ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3778 Thread* self,
3779 ObjPtr<mirror::DexCache> dex_cache,
3780 const DexCacheData& data,
3781 ObjPtr<mirror::ClassLoader> class_loader) {
3782 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3783 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3784 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3785 "Attempt to register dex file %s with multiple class loaders",
3786 data.dex_file->GetLocation().c_str());
3787 return nullptr;
3788 }
3789 return dex_cache;
3790}
3791
Alex Light07f06212017-06-01 14:01:43 -07003792void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3793 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003794 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003795 Thread* self = Thread::Current();
3796 StackHandleScope<2> hs(self);
3797 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3798 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3799 const DexFile* dex_file = dex_cache->GetDexFile();
3800 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3801 if (kIsDebugBuild) {
3802 DexCacheData old_data;
3803 {
3804 ReaderMutexLock mu(self, *Locks::dex_lock_);
3805 old_data = FindDexCacheDataLocked(*dex_file);
3806 }
3807 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3808 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3809 << "been registered on dex file " << dex_file->GetLocation();
3810 }
3811 ClassTable* table;
3812 {
3813 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3814 table = InsertClassTableForClassLoader(h_class_loader.Get());
3815 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003816 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3817 // a thread holding the dex lock and blocking on a condition variable regarding
3818 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003819 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003820 WriterMutexLock mu(self, *Locks::dex_lock_);
3821 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3822 table->InsertStrongRoot(h_dex_cache.Get());
3823 if (h_class_loader.Get() != nullptr) {
3824 // Since we added a strong root to the class table, do the write barrier as required for
3825 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003826 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003827 }
3828}
3829
Vladimir Markocd556b02017-02-03 11:47:34 +00003830ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3831 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003832 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003833 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003834 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003835 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003836 old_data = FindDexCacheDataLocked(dex_file);
3837 }
3838 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3839 if (old_dex_cache != nullptr) {
3840 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003841 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003842 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003843 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3844 DCHECK(linear_alloc != nullptr);
3845 ClassTable* table;
3846 {
3847 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3848 table = InsertClassTableForClassLoader(class_loader);
3849 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003850 // Don't alloc while holding the lock, since allocation may need to
3851 // suspend all threads and another thread may need the dex_lock_ to
3852 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003853 StackHandleScope<3> hs(self);
3854 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003855 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003856 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3857 self,
3858 dex_file)));
3859 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003860 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003861 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3862 // a thread holding the dex lock and blocking on a condition variable regarding
3863 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003864 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003865 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003866 old_data = FindDexCacheDataLocked(dex_file);
3867 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003868 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003869 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3870 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3871 // that the arrays are null.
3872 mirror::DexCache::InitializeDexCache(self,
3873 h_dex_cache.Get(),
3874 h_location.Get(),
3875 &dex_file,
3876 linear_alloc,
3877 image_pointer_size_);
3878 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003879 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003880 }
3881 if (old_dex_cache != nullptr) {
3882 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3883 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003884 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003885 self->ClearException();
3886 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3887 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3888 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003889 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003890 self->AssertPendingOOMException();
3891 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003892 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003893 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003894 if (h_class_loader.Get() != nullptr) {
3895 // Since we added a strong root to the class table, do the write barrier as required for
3896 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003897 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003898 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003899 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003900}
3901
Vladimir Markocd556b02017-02-03 11:47:34 +00003902bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003903 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003904 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003905}
3906
Vladimir Markocd556b02017-02-03 11:47:34 +00003907ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3908 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003909 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3910 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003911 if (dex_cache != nullptr) {
3912 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003913 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003914 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003915 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003916 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003917 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003918 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003919 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003920 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3921 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003922 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003923}
3924
Vladimir Markocd556b02017-02-03 11:47:34 +00003925ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3926 const DexFile* dex_file = dex_cache->GetDexFile();
3927 DCHECK(dex_file != nullptr);
3928 ReaderMutexLock mu(self, *Locks::dex_lock_);
3929 // Search assuming unique-ness of dex file.
3930 for (const DexCacheData& data : dex_caches_) {
3931 // Avoid decoding (and read barriers) other unrelated dex caches.
3932 if (data.dex_file == dex_file) {
3933 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3934 if (registered_dex_cache != nullptr) {
3935 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3936 return data.class_table;
3937 }
3938 }
3939 }
3940 return nullptr;
3941}
3942
3943ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3944 // Search assuming unique-ness of dex file.
3945 for (const DexCacheData& data : dex_caches_) {
3946 // Avoid decoding (and read barriers) other unrelated dex caches.
3947 if (data.dex_file == &dex_file) {
3948 return data;
3949 }
3950 }
3951 return DexCacheData();
3952}
3953
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003954ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003955 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003956 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003957 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003958 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003959 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003960 }
Ian Rogers1f539342012-10-03 21:09:42 -07003961 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003962 StackHandleScope<1> hs(self);
3963 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003964 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003965 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3966 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003967 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003968 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003969 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003970 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003971 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3972 h_class.Get(),
3973 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003974 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003975 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003976}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003977
Vladimir Marko02610552018-06-04 14:38:00 +01003978inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
3979 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
3980}
3981
Brian Carlstrombe977852011-07-19 14:54:54 -07003982// Create an array class (i.e. the class object for the array, not the
3983// array itself). "descriptor" looks like "[C" or "[[[[B" or
3984// "[Ljava/lang/String;".
3985//
3986// If "descriptor" refers to an array of primitives, look up the
3987// primitive type's internally-generated class object.
3988//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003989// "class_loader" is the class loader of the class that's referring to
3990// us. It's used to ensure that we're looking for the element type in
3991// the right context. It does NOT become the class loader for the
3992// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003993//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003994// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003995ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
3996 const char* descriptor,
3997 size_t hash,
3998 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003999 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004000 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004001 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004002
4003 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4004 // code to be executed. We put it up here so we can avoid all the allocations associated with
4005 // creating the class. This can happen with (eg) jit threads.
4006 if (!self->CanLoadClasses()) {
4007 // Make sure we don't try to load anything, potentially causing an infinite loop.
4008 ObjPtr<mirror::Throwable> pre_allocated =
4009 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4010 self->SetException(pre_allocated);
4011 return nullptr;
4012 }
4013
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004014 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4015 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004016 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004017 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004018 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004019 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4020 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004021 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004022 DCHECK(self->IsExceptionPending());
4023 return nullptr;
4024 } else {
4025 self->ClearException();
4026 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004027 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004028 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4029 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4030 return nullptr;
4031 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004032 // See if the component type is already loaded. Array classes are
4033 // always associated with the class loader of their underlying
4034 // element type -- an array of Strings goes with the loader for
4035 // java/lang/String -- so we need to look for it there. (The
4036 // caller should have checked for the existence of the class
4037 // before calling here, but they did so with *their* class loader,
4038 // not the component type's loader.)
4039 //
4040 // If we find it, the caller adds "loader" to the class' initiating
4041 // loader list, which should prevent us from going through this again.
4042 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004043 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004044 // are the same, because our caller (FindClass) just did the
4045 // lookup. (Even if we get this wrong we still have correct behavior,
4046 // because we effectively do this lookup again when we add the new
4047 // class to the hash table --- necessary because of possible races with
4048 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004049 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004050 ObjPtr<mirror::Class> new_class =
4051 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004052 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004053 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004054 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004055 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004056
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004057 // Fill out the fields in the Class.
4058 //
4059 // It is possible to execute some methods against arrays, because
4060 // all arrays are subclasses of java_lang_Object_, so we need to set
4061 // up a vtable. We can just point at the one in java_lang_Object_.
4062 //
4063 // Array classes are simple enough that we don't need to do a full
4064 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004065 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004066 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004067 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004068 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004069 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004070 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004071 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4072 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4073 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004074 } else if (strcmp(descriptor, "[Z") == 0) {
4075 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4076 } else if (strcmp(descriptor, "[B") == 0) {
4077 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4078 } else if (strcmp(descriptor, "[C") == 0) {
4079 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4080 } else if (strcmp(descriptor, "[S") == 0) {
4081 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004082 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004083 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004084 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004085 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004086 } else if (strcmp(descriptor, "[F") == 0) {
4087 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4088 } else if (strcmp(descriptor, "[D") == 0) {
4089 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004090 }
4091 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004092 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004093 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004094 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004095 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004096 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004097 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004098 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004099 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004100 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004101 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004102 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004103 new_class->SetSuperClass(java_lang_Object);
4104 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004105 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004106 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004107 if (component_type->IsPrimitive()) {
4108 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4109 } else {
4110 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4111 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004112 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004113 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4114 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4115 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004116 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004117 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004118 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004119 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004120
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004121 // All arrays have java/lang/Cloneable and java/io/Serializable as
4122 // interfaces. We need to set that up here, so that stuff like
4123 // "instanceof" works right.
4124 //
4125 // Note: The GC could run during the call to FindSystemClass,
4126 // so we need to make sure the class object is GC-valid while we're in
4127 // there. Do this by clearing the interface list so the GC will just
4128 // think that the entries are null.
4129
4130
4131 // Use the single, global copies of "interfaces" and "iftable"
4132 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004133 {
Vladimir Marko02610552018-06-04 14:38:00 +01004134 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004135 CHECK(array_iftable != nullptr);
4136 new_class->SetIfTable(array_iftable);
4137 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004138
Elliott Hughes00626c22013-06-14 15:04:14 -07004139 // Inherit access flags from the component type.
4140 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4141 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4142 access_flags &= kAccJavaFlagsMask;
4143 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004144 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004145 access_flags |= kAccAbstract | kAccFinal;
4146 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004147 // Arrays are access-checks-clean and preverified.
4148 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004149
4150 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004151
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004152 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004153 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004154 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4155 // duplicate events in case of races. Array classes don't really follow dedicated
4156 // load and prepare, anyways.
4157 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4158 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4159
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004160 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004161 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004162 }
4163 // Another thread must have loaded the class after we
4164 // started but before we finished. Abandon what we've
4165 // done.
4166 //
4167 // (Yes, this happens.)
4168
Vladimir Markobcf17522018-06-01 13:14:32 +01004169 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004170}
4171
Vladimir Marko9186b182018-11-06 14:55:54 +00004172ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4173 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004174 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004175 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4176 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4177 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4178 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4179 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4180 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4181 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4182 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4183 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004184 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004185 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004186 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004187 return GetClassRoot(class_root, this);
4188}
4189
4190ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4191 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4192 if (UNLIKELY(result == nullptr)) {
4193 std::string printable_type(PrintableChar(type));
4194 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4195 }
4196 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004197}
4198
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004199ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4200 ObjPtr<mirror::Class> klass,
4201 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004202 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004203 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004204 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004205 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004206 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004207 source += " from ";
4208 source += dex_cache->GetLocation()->ToModifiedUtf8();
4209 }
4210 LOG(INFO) << "Loaded class " << descriptor << source;
4211 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004212 {
4213 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004214 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004215 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004216 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004217 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004218 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004219 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004220 VerifyObject(klass);
4221 class_table->InsertWithHash(klass, hash);
4222 if (class_loader != nullptr) {
4223 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004224 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004225 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004226 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004227 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004228 }
4229 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004230 if (kIsDebugBuild) {
4231 // Test that copied methods correctly can find their holder.
4232 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4233 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4234 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004235 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004236 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004237}
4238
Vladimir Marko1998cd02017-01-13 13:02:58 +00004239void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004240 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4241 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4242 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4243 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004244 }
4245}
4246
Alex Lighte64300b2015-12-15 15:02:47 -08004247// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004248void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004249 LengthPrefixedArray<ArtMethod>* new_methods) {
4250 klass->SetMethodsPtrUnchecked(new_methods,
4251 klass->NumDirectMethods(),
4252 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004253 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004254 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004255}
4256
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004257ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4258 const char* descriptor,
4259 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004260 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4261}
4262
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004263ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4264 const char* descriptor,
4265 size_t hash,
4266 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004267 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4268 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4269 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004270 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004271 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004272 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004273 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004274 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004275 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004276}
4277
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004278class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4279 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004280 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004281
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004282 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004283 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004284 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004285 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004286 if (class_table != nullptr) {
4287 class_table->FreezeSnapshot();
4288 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004289 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004290};
4291
4292void ClassLinker::MoveClassTableToPreZygote() {
4293 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004294 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004295 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004296 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004297}
4298
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004299// Look up classes by hash and descriptor and put all matching ones in the result array.
4300class LookupClassesVisitor : public ClassLoaderVisitor {
4301 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004302 LookupClassesVisitor(const char* descriptor,
4303 size_t hash,
4304 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004305 : descriptor_(descriptor),
4306 hash_(hash),
4307 result_(result) {}
4308
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004309 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004310 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004311 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004312 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004313 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4314 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004315 result_->push_back(klass);
4316 }
4317 }
4318
4319 private:
4320 const char* const descriptor_;
4321 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004322 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004323};
4324
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004325void ClassLinker::LookupClasses(const char* descriptor,
4326 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004327 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004328 Thread* const self = Thread::Current();
4329 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004330 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004331 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004332 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004333 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004334 result.push_back(klass);
4335 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004336 LookupClassesVisitor visitor(descriptor, hash, &result);
4337 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004338}
4339
Alex Lightf1f10492015-10-07 16:08:36 -07004340bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4341 Handle<mirror::Class> klass,
4342 Handle<mirror::Class> supertype) {
4343 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004344 DCHECK(klass != nullptr);
4345 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004346
Alex Lightf1f10492015-10-07 16:08:36 -07004347 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4348 VerifyClass(self, supertype);
4349 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004350
4351 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4352 // The supertype is either verified, or we soft failed at AOT time.
4353 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004354 return true;
4355 }
4356 // If we got this far then we have a hard failure.
4357 std::string error_msg =
4358 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004359 klass->PrettyDescriptor().c_str(),
4360 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004361 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004362 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004363 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004364 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004365 // Set during VerifyClass call (if at all).
4366 self->ClearException();
4367 }
4368 // Change into a verify error.
4369 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004370 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004371 self->GetException()->SetCause(cause.Get());
4372 }
4373 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4374 if (Runtime::Current()->IsAotCompiler()) {
4375 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4376 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004377 // Need to grab the lock to change status.
4378 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004379 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004380 return false;
4381}
4382
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004383verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004384 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004385 {
4386 // TODO: assert that the monitor on the Class is held
4387 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004388
Andreas Gampe884f3b82016-03-30 19:52:58 -07004389 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004390 ClassStatus old_status = klass->GetStatus();
4391 while (old_status == ClassStatus::kVerifying ||
4392 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004393 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004394 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4395 // case we may see the same status again. b/62912904. This is why the check is
4396 // greater or equal.
4397 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004398 << "Class '" << klass->PrettyClass()
4399 << "' performed an illegal verification state transition from " << old_status
4400 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004401 old_status = klass->GetStatus();
4402 }
jeffhao98eacac2011-09-14 16:11:53 -07004403
Andreas Gampe884f3b82016-03-30 19:52:58 -07004404 // The class might already be erroneous, for example at compile time if we attempted to verify
4405 // this class as a parent to another.
4406 if (klass->IsErroneous()) {
4407 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004408 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004409 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004410
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004411 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004412 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004413 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004414 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004415 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004416
4417 // For AOT, don't attempt to re-verify if we have already found we should
4418 // verify at runtime.
4419 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004420 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004421 }
jeffhao98eacac2011-09-14 16:11:53 -07004422
Vladimir Marko2c64a832018-01-04 11:31:56 +00004423 if (klass->GetStatus() == ClassStatus::kResolved) {
4424 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004425 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004426 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004427 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004428 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004429 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004430 }
4431
4432 // Skip verification if disabled.
4433 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004434 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004435 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004436 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004437 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004438 }
4439
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004440 VLOG(class_linker) << "Beginning verification for class: "
4441 << klass->PrettyDescriptor()
4442 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4443
Ian Rogers9ffb0392012-09-10 11:56:50 -07004444 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004445 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004446 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4447 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004448 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004449 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004450 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004451 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004452
Alex Lightf1f10492015-10-07 16:08:36 -07004453 // Verify all default super-interfaces.
4454 //
4455 // (1) Don't bother if the superclass has already had a soft verification failure.
4456 //
4457 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4458 // recursive initialization by themselves. This is because when an interface is initialized
4459 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4460 // but choose not to for an optimization. If the interfaces is being verified due to a class
4461 // initialization (which would need all the default interfaces to be verified) the class code
4462 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004463 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004464 && !klass->IsInterface()) { // See (2)
4465 int32_t iftable_count = klass->GetIfTableCount();
4466 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4467 // Loop through all interfaces this class has defined. It doesn't matter the order.
4468 for (int32_t i = 0; i < iftable_count; i++) {
4469 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004470 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004471 // We only care if we have default interfaces and can skip if we are already verified...
4472 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4473 continue;
4474 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4475 // We had a hard failure while verifying this interface. Just return immediately.
4476 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004477 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004478 } else if (UNLIKELY(!iface->IsVerified())) {
4479 // We softly failed to verify the iface. Stop checking and clean up.
4480 // Put the iface into the supertype handle so we know what caused us to fail.
4481 supertype.Assign(iface.Get());
4482 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004483 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004484 }
4485 }
4486
Alex Lightf1f10492015-10-07 16:08:36 -07004487 // At this point if verification failed, then supertype is the "first" supertype that failed
4488 // verification (without a specific order). If verification succeeded, then supertype is either
4489 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004490 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004491 supertype.Get() == klass->GetSuperClass() ||
4492 !supertype->IsVerified());
4493
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004494 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004495 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004496 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004497 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004498
4499 VLOG(class_linker) << "Class preverified status for class "
4500 << klass->PrettyDescriptor()
4501 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4502 << ": "
4503 << preverified;
4504
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004505 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4506 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004507 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4508 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004509
Ian Rogers62d6c772013-02-27 08:32:07 -08004510 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004511 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004512 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004513 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004514 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004515
4516 // Verification is done, grab the lock again.
4517 ObjectLock<mirror::Class> lock(self, klass);
4518
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004519 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4520 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004521 VLOG(class_linker) << "Soft verification failure in class "
4522 << klass->PrettyDescriptor()
4523 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4524 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004525 }
Ian Rogers1f539342012-10-03 21:09:42 -07004526 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004527 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004528 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004529 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004530 // Even though there were no verifier failures we need to respect whether the super-class and
4531 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004532 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004533 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004534 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004535 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4536 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004537 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004538 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004539 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004540 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004541 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004542 // Soft failures at compile time should be retried at runtime. Soft
4543 // failures at runtime will be handled by slow paths in the generated
4544 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004545 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004546 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004547 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004548 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004549 // As this is a fake verified status, make sure the methods are _not_ marked
4550 // kAccSkipAccessChecks later.
4551 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004552 }
4553 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004554 } else {
David Sehr709b0702016-10-13 09:12:37 -07004555 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004556 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4557 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004558 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004559 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004560 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004561 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004562 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004563 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004564 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004565 // method.
4566 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004567 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004568 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004569
4570 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4571 // Never skip access checks if the verification soft fail is forced.
4572 // Mark the class as having a verification attempt to avoid re-running the verifier.
4573 klass->SetVerificationAttempted();
4574 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004575 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004576 }
Andreas Gampe48498592014-09-10 19:48:05 -07004577 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004578 // Done verifying. Notify the compiler about the verification status, in case the class
4579 // was verified implicitly (eg super class of a compiled class).
4580 if (Runtime::Current()->IsAotCompiler()) {
4581 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4582 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4583 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004584 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004585}
4586
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004587verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4588 Handle<mirror::Class> klass,
4589 verifier::HardFailLogMode log_level,
4590 std::string* error_msg) {
4591 Runtime* const runtime = Runtime::Current();
4592 return verifier::MethodVerifier::VerifyClass(self,
4593 klass.Get(),
4594 runtime->GetCompilerCallbacks(),
4595 runtime->IsAotCompiler(),
4596 log_level,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07004597 Runtime::Current()->GetTargetSdkVersion(),
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004598 error_msg);
4599}
4600
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004601bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004602 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004603 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004604 // If we're compiling, we can only verify the class using the oat file if
4605 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004606 // the compilation unit (app - dependencies). We will let the compiler callback
4607 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004608 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004609 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004610 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004611 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004612 return false;
4613 }
4614 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004615 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004616 return false;
4617 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004618 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004619
Andreas Gampeb40d3612018-06-26 15:49:42 -07004620 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004621 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004622 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004623 return false;
4624 }
4625
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004626 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004627 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004628 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004629 return true;
4630 }
4631 // If we only verified a subset of the classes at compile time, we can end up with classes that
4632 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004633 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004634 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004635 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004636 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004637 // Compile time verification failed with a soft error. Compile time verification can fail
4638 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004639 // class ... {
4640 // Foo x;
4641 // .... () {
4642 // if (...) {
4643 // v1 gets assigned a type of resolved class Foo
4644 // } else {
4645 // v1 gets assigned a type of unresolved class Bar
4646 // }
4647 // iput x = v1
4648 // } }
4649 // when we merge v1 following the if-the-else it results in Conflict
4650 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4651 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4652 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4653 // at compile time).
4654 return false;
4655 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004656 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004657 // Compile time verification failed with a hard error. This is caused by invalid instructions
4658 // in the class. These errors are unrecoverable.
4659 return false;
4660 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004661 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004662 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4663 // not loading the class.
4664 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4665 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004666 return false;
4667 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004668 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004669 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004670 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004671 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004672 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004673}
4674
Alex Light5a559862016-01-29 12:24:48 -08004675void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004676 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004677 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004678 }
4679}
4680
Alex Light5a559862016-01-29 12:24:48 -08004681void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004682 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004683 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004684 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004685 return; // native or abstract method
4686 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004687 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004688 return; // nothing to process
4689 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004690 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004691 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004692 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4693 CatchHandlerIterator iterator(handlers_ptr);
4694 for (; iterator.HasNext(); iterator.Next()) {
4695 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4696 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004697 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004698 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004699 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004700 DCHECK(Thread::Current()->IsExceptionPending());
4701 Thread::Current()->ClearException();
4702 }
4703 }
4704 }
4705 handlers_ptr = iterator.EndDataPointer();
4706 }
4707}
4708
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004709ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4710 jstring name,
4711 jobjectArray interfaces,
4712 jobject loader,
4713 jobjectArray methods,
4714 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004715 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004716
4717 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4718 // code to be executed. We put it up here so we can avoid all the allocations associated with
4719 // creating the class. This can happen with (eg) jit-threads.
4720 if (!self->CanLoadClasses()) {
4721 // Make sure we don't try to load anything, potentially causing an infinite loop.
4722 ObjPtr<mirror::Throwable> pre_allocated =
4723 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4724 self->SetException(pre_allocated);
4725 return nullptr;
4726 }
4727
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004728 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004729 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004730 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004731 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004732 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004733 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004734 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004735 DCHECK(temp_klass->GetClass() != nullptr);
4736 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004737 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4738 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004739 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4740 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4741 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4742 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004743 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004744 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004745 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004746 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004747 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004748 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004749
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004750 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004751 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004752
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004753 // Insert the class before loading the fields as the field roots
4754 // (ArtField::declaring_class_) are only visited from the class
4755 // table. There can't be any suspend points between inserting the
4756 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004757 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004758 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004759
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004760 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004761 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004762 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004763 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004764
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004765 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4766 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004767 ArtField& interfaces_sfield = sfields->At(0);
4768 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004769 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004770 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004771
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004772 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004773 ArtField& throws_sfield = sfields->At(1);
4774 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004775 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004776 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004777
Ian Rogers466bb252011-10-14 03:29:56 -07004778 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004779 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004780
Alex Lighte64300b2015-12-15 15:02:47 -08004781 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004782 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004783 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004784 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004785 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004786
4787 // Create the methods array.
4788 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4789 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004790 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4791 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004792 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004793 self->AssertPendingOOMException();
4794 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004795 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004796 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004797
4798 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004799 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004800
4801 // Create virtual method using specified prototypes.
4802 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004803 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004804 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004805 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004806 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004807 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4808 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004809 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004810
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004811 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004812 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004813 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004814 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004815 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004816
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004817 // At this point the class is loaded. Publish a ClassLoad event.
4818 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4819 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4820
4821 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004822 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004823 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004824 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004825 // Link the fields and virtual methods, creating vtable and iftables.
4826 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004827 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004828 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004829 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004830 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004831 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004832 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004833 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004834 CHECK(temp_klass->IsRetired());
4835 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004836
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004837 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004838 interfaces_sfield.SetObject<false>(
4839 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004840 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004841 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4842 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004843 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004844 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004845
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004846 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4847
Vladimir Marko305c38b2018-02-14 11:50:07 +00004848 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4849 // See also ClassLinker::EnsureInitialized().
4850 if (kBitstringSubtypeCheckEnabled) {
4851 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4852 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4853 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4854 }
4855
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004856 {
4857 // Lock on klass is released. Lock new class object.
4858 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004859 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004860 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004861 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004862
4863 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004864 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004865 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004866 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4867
Ian Rogersc2b44472011-12-14 21:17:17 -08004868 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004869 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4870 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004871 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004872 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004873
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004874 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004875 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004876 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004877 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004878 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004879
4880 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004881 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004882 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004883
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004884 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004885 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004886 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004887 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004888 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004889 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004890}
4891
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004892std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004893 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004894 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004895 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004896 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4897}
4898
Mathieu Chartiere401d142015-04-22 13:56:20 -07004899void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4900 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004901 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4902 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004903
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004904 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4905 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004906 ArtMethod* proxy_constructor =
4907 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004908 DCHECK(proxy_constructor != nullptr)
4909 << "Could not find <init> method in java.lang.reflect.Proxy";
4910
Jeff Haodb8a6642014-08-14 17:18:52 -07004911 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4912 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004913 DCHECK(out != nullptr);
4914 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004915 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004916 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004917 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004918 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4919 kAccPublic |
4920 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004921 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004922
4923 // Set the original constructor method.
4924 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004925}
4926
Mathieu Chartiere401d142015-04-22 13:56:20 -07004927void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004928 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004929 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4930 CHECK_STREQ(np->GetName(), "<init>");
4931 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004932 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004933}
4934
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004935void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004936 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004937 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004938 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004939 DCHECK(out != nullptr);
4940 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004941
Alex Lighte9dd04f2016-03-16 16:09:45 -07004942 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004943 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004944 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4945 // preference to the invocation handler.
4946 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4947 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004948 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4949 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004950 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4951
4952 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4953 // method they copy might (if it's a default method).
4954 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004955
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004956 // Set the original interface method.
4957 out->SetDataPtrSize(prototype, image_pointer_size_);
4958
Ian Rogers466bb252011-10-14 03:29:56 -07004959 // At runtime the method looks like a reference and argument saving method, clone the code
4960 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004961 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004962}
Jesse Wilson95caa792011-10-12 18:14:17 -04004963
Mathieu Chartiere401d142015-04-22 13:56:20 -07004964void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004965 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004966 CHECK(!prototype->IsFinal());
4967 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004968 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004969
4970 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4971 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004972 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004973 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004974}
4975
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004976bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004977 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004978 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004979 return true;
4980 }
4981 if (!can_init_statics) {
4982 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004983 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004984 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004985 return false;
4986 }
4987 // Check if there are encoded static values needing initialization.
4988 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004989 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004990 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004991 if (dex_class_def->static_values_off_ != 0) {
4992 return false;
4993 }
4994 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004995 // If we are a class we need to initialize all interfaces with default methods when we are
4996 // initialized. Check all of them.
4997 if (!klass->IsInterface()) {
4998 size_t num_interfaces = klass->GetIfTableCount();
4999 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005000 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005001 if (iface->HasDefaultMethods() &&
5002 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5003 return false;
5004 }
5005 }
5006 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005007 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005008 if (klass->IsInterface() || !klass->HasSuperClass()) {
5009 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005010 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005011 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005012 if (!can_init_parents && !super_class->IsInitialized()) {
5013 return false;
5014 }
5015 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005016}
5017
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005018bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5019 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005020 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5021
5022 // Are we already initialized and therefore done?
5023 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5024 // an initialized class will never change its state.
5025 if (klass->IsInitialized()) {
5026 return true;
5027 }
5028
5029 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005030 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005031 return false;
5032 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005033
Ian Rogers7b078e82014-09-10 14:44:24 -07005034 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005035 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005036 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005037 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005038
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005039 // Re-check under the lock in case another thread initialized ahead of us.
5040 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005041 return true;
5042 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005043
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005044 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005045 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08005046 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005047 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005048 return false;
5049 }
5050
Vladimir Marko72ab6842017-01-20 19:32:50 +00005051 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5052 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005053
5054 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005055 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005056 if (!klass->IsVerified()) {
5057 // We failed to verify, expect either the klass to be erroneous or verification failed at
5058 // compile time.
5059 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005060 // The class is erroneous. This may be a verifier error, or another thread attempted
5061 // verification and/or initialization and failed. We can distinguish those cases by
5062 // whether an exception is already pending.
5063 if (self->IsExceptionPending()) {
5064 // Check that it's a VerifyError.
5065 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005066 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005067 } else {
5068 // Check that another thread attempted initialization.
5069 DCHECK_NE(0, klass->GetClinitThreadId());
5070 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5071 // Need to rethrow the previous failure now.
5072 ThrowEarlierClassFailure(klass.Get(), true);
5073 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005074 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005075 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005076 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005077 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005078 self->AssertNoPendingException();
5079 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005080 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005081 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005082 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005083 } else {
5084 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005085 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005086
5087 // A separate thread could have moved us all the way to initialized. A "simple" example
5088 // involves a subclass of the current class being initialized at the same time (which
5089 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005090 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005091 if (klass->IsInitialized()) {
5092 return true;
5093 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005094 }
5095
Vladimir Marko2c64a832018-01-04 11:31:56 +00005096 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005097 // initializing higher up the stack or another thread has beat us
5098 // to initializing and we need to wait. Either way, this
5099 // invocation of InitializeClass will not be responsible for
5100 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005101 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005102 // Could have got an exception during verification.
5103 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005104 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005105 return false;
5106 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005107 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005108 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005109 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005110 return true;
5111 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005112 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005113 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005114 }
5115
Jeff Haoe2e40342017-07-19 10:45:18 -07005116 // Try to get the oat class's status for this class if the oat file is present. The compiler
5117 // tries to validate superclass descriptors, and writes the result into the oat file.
5118 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5119 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5120 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005121 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005122 const Runtime* runtime = Runtime::Current();
5123 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5124 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5125 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005126 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005127 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005128 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005129 return false;
5130 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005131 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005132
Vladimir Marko2c64a832018-01-04 11:31:56 +00005133 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005134 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005135
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005136 // From here out other threads may observe that we're initializing and so changes of state
5137 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005138 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005139 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005140
5141 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005142 }
5143
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005144 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005145 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005146 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005147 if (!super_class->IsInitialized()) {
5148 CHECK(!super_class->IsInterface());
5149 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005150 StackHandleScope<1> hs(self);
5151 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005152 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005153 if (!super_initialized) {
5154 // The super class was verified ahead of entering initializing, we should only be here if
5155 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005156 // For the case of aot compiler, the super class might also be initializing but we don't
5157 // want to process circular dependencies in pre-compile.
5158 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005159 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005160 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005161 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005162 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005163 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005164 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005165 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005166 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005167 return false;
5168 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005169 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005170 }
5171
Alex Lighteb7c1442015-08-31 13:17:42 -07005172 if (!klass->IsInterface()) {
5173 // Initialize interfaces with default methods for the JLS.
5174 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005175 // Only setup the (expensive) handle scope if we actually need to.
5176 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005177 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005178 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5179 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005180 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005181 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005182 CHECK(handle_scope_iface->IsInterface());
5183 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5184 // We have already done this for this interface. Skip it.
5185 continue;
5186 }
5187 // We cannot just call initialize class directly because we need to ensure that ALL
5188 // interfaces with default methods are initialized. Non-default interface initialization
5189 // will not affect other non-default super-interfaces.
5190 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5191 handle_scope_iface,
5192 can_init_statics,
5193 can_init_parents);
5194 if (!iface_initialized) {
5195 ObjectLock<mirror::Class> lock(self, klass);
5196 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005197 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005198 return false;
5199 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005200 }
5201 }
5202 }
5203
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005204 const size_t num_static_fields = klass->NumStaticFields();
5205 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005206 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005207 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005208 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005209 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005210 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005211
5212 // Eagerly fill in static fields so that the we don't have to do as many expensive
5213 // Class::FindStaticField in ResolveField.
5214 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005215 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005216 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005217 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005218 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005219 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005220 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5221 field,
5222 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5223 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005224 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005225 } else {
5226 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005227 }
5228 }
5229
Vladimir Markoe11dd502017-12-08 14:09:45 +00005230 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5231 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005232 this,
5233 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005234 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005235
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005236 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005237 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005238 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005239 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5240 if (!value_it.HasNext()) {
5241 break;
5242 }
5243 ArtField* art_field = ResolveField(field.GetIndex(),
5244 dex_cache,
5245 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005246 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005247 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005248 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005249 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005250 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005251 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005252 if (self->IsExceptionPending()) {
5253 break;
5254 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005255 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005256 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005257 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005258 }
5259 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005260
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005261
Mathieu Chartierda595be2016-08-10 13:57:39 -07005262 if (!self->IsExceptionPending()) {
5263 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5264 if (clinit != nullptr) {
5265 CHECK(can_init_statics);
5266 JValue result;
5267 clinit->Invoke(self, nullptr, 0, &result, "V");
5268 }
5269 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005270 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005271 uint64_t t1 = NanoTime();
5272
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005273 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005274 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005275 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005276
5277 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005278 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005279 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005280 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005281 } else if (Runtime::Current()->IsTransactionAborted()) {
5282 // The exception thrown when the transaction aborted has been caught and cleared
5283 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005284 VLOG(compiler) << "Return from class initializer of "
5285 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005286 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005287 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005288 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005289 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005290 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005291 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5292 RuntimeStats* thread_stats = self->GetStats();
5293 ++global_stats->class_init_count;
5294 ++thread_stats->class_init_count;
5295 global_stats->class_init_time_ns += (t1 - t0);
5296 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005297 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005298 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005299 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005300 std::string temp;
5301 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005302 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005303 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005304 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005305 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005306 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005307 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005308 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005309}
5310
Alex Lighteb7c1442015-08-31 13:17:42 -07005311// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5312// and perform the initialization only on those interfaces that contain default methods.
5313bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5314 Handle<mirror::Class> iface,
5315 bool can_init_statics,
5316 bool can_init_parents) {
5317 CHECK(iface->IsInterface());
5318 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005319 // Only create the (expensive) handle scope if we need it.
5320 if (UNLIKELY(num_direct_ifaces > 0)) {
5321 StackHandleScope<1> hs(self);
5322 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5323 // First we initialize all of iface's super-interfaces recursively.
5324 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005325 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005326 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005327 if (!super_iface->HasBeenRecursivelyInitialized()) {
5328 // Recursive step
5329 handle_super_iface.Assign(super_iface);
5330 if (!InitializeDefaultInterfaceRecursive(self,
5331 handle_super_iface,
5332 can_init_statics,
5333 can_init_parents)) {
5334 return false;
5335 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005336 }
5337 }
5338 }
5339
5340 bool result = true;
5341 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5342 // initialize if we don't have default methods.
5343 if (iface->HasDefaultMethods()) {
5344 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5345 }
5346
5347 // Mark that this interface has undergone recursive default interface initialization so we know we
5348 // can skip it on any later class initializations. We do this even if we are not a default
5349 // interface since we can still avoid the traversal. This is purely a performance optimization.
5350 if (result) {
5351 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005352 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5353 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5354 // initialization is a performance optimization (to avoid another idempotent visit
5355 // for other implementing classes/interfaces), and can be revisited later.
5356 ObjectTryLock<mirror::Class> lock(self, iface);
5357 if (lock.Acquired()) {
5358 iface->SetRecursivelyInitialized();
5359 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005360 }
5361 return result;
5362}
5363
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005364bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5365 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005366 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005367 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005368 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005369 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005370 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005371 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005372
5373 // When we wake up, repeat the test for init-in-progress. If
5374 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005375 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005376 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005377 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005378 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005379 return false;
5380 }
5381 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005382 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005383 continue;
5384 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005385 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005386 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005387 // Compile time initialization failed.
5388 return false;
5389 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005390 if (klass->IsErroneous()) {
5391 // The caller wants an exception, but it was thrown in a
5392 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005393 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005394 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005395 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005396 return false;
5397 }
5398 if (klass->IsInitialized()) {
5399 return true;
5400 }
David Sehr709b0702016-10-13 09:12:37 -07005401 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005402 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005403 }
Ian Rogers07140832014-09-30 15:43:59 -07005404 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005405}
5406
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005407static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5408 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005409 ArtMethod* method,
5410 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005411 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005412 DCHECK(Thread::Current()->IsExceptionPending());
5413 DCHECK(!m->IsProxyMethod());
5414 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005415 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5416 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005417 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005418 std::string return_type = dex_file->PrettyType(return_type_idx);
5419 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005420 ThrowWrappedLinkageError(klass.Get(),
5421 "While checking class %s method %s signature against %s %s: "
5422 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005423 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5424 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005425 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005426 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005427 return_type.c_str(), class_loader.c_str());
5428}
5429
5430static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5431 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005432 ArtMethod* method,
5433 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005434 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005435 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005436 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005437 DCHECK(Thread::Current()->IsExceptionPending());
5438 DCHECK(!m->IsProxyMethod());
5439 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005440 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5441 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005442 ThrowWrappedLinkageError(klass.Get(),
5443 "While checking class %s method %s signature against %s %s: "
5444 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005445 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5446 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005447 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005448 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005449 index, arg_type.c_str(), class_loader.c_str());
5450}
5451
5452static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5453 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005454 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005455 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005456 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005457 ThrowLinkageError(klass.Get(),
5458 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005459 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5460 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005461 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005462 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005463 error_msg.c_str());
5464}
5465
Ian Rogersb5fb2072014-12-02 17:22:02 -08005466static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005467 Handle<mirror::Class> klass,
5468 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005469 ArtMethod* method1,
5470 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005471 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005472 {
5473 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005474 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005475 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005476 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005477 return false;
5478 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005479 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005480 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005481 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005482 return false;
5483 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005484 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005485 ThrowSignatureMismatch(klass, super_klass, method1,
5486 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005487 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005488 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005489 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005490 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005491 return false;
5492 }
5493 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005494 const dex::TypeList* types1 = method1->GetParameterTypeList();
5495 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005496 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005497 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005498 ThrowSignatureMismatch(klass, super_klass, method1,
5499 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005500 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005501 return false;
5502 }
5503 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005504 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005505 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005506 ThrowSignatureMismatch(klass, super_klass, method1,
5507 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005508 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005509 return false;
5510 }
5511 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005512 }
5513 uint32_t num_types = types1->Size();
5514 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005515 ThrowSignatureMismatch(klass, super_klass, method1,
5516 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005517 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005518 return false;
5519 }
5520 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005521 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005522 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005523 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005524 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005525 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005526 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005527 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005528 return false;
5529 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005530 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005531 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005532 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005533 if (UNLIKELY(other_param_type == nullptr)) {
5534 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005535 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005536 return false;
5537 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005538 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005539 ThrowSignatureMismatch(klass, super_klass, method1,
5540 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5541 i,
David Sehr709b0702016-10-13 09:12:37 -07005542 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005543 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005544 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005545 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005546 return false;
5547 }
5548 }
5549 return true;
5550}
5551
5552
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005553bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005554 if (klass->IsInterface()) {
5555 return true;
5556 }
Ian Rogers151f2212014-05-06 11:27:27 -07005557 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005558 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005559 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005560 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005561 if (klass->HasSuperClass() &&
5562 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005563 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005564 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005565 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5566 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5567 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005568 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5569 klass,
5570 super_klass,
5571 m,
5572 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005573 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005574 return false;
5575 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005576 }
5577 }
5578 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005579 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005580 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5581 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5582 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005583 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005584 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5585 j, image_pointer_size_);
5586 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5587 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005588 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5589 klass,
5590 super_klass,
5591 m,
5592 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005593 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005594 return false;
5595 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005596 }
5597 }
5598 }
5599 }
5600 return true;
5601}
5602
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005603bool ClassLinker::EnsureInitialized(Thread* self,
5604 Handle<mirror::Class> c,
5605 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005606 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005607 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005608
Mathieu Chartier524507a2014-08-27 15:28:28 -07005609 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005610 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005611 return true;
5612 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005613 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5614 //
5615 // Ensure the bitstring is initialized before any of the class initialization
5616 // logic occurs. Once a class initializer starts running, objects can
5617 // escape into the heap and use the subtype checking code.
5618 //
5619 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5620 // can be used as a source for the IsSubClass check, and that all ancestors
5621 // of the class are Assigned (can be used as a target for IsSubClass check)
5622 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005623 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005624 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005625 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005626 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5627 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005628 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005629 if (!success) {
5630 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005631 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005632 }
5633 } else {
5634 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005635 }
5636 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005637}
5638
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005639void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5640 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005641 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005642 for (ArtField& field : new_class->GetIFields()) {
5643 if (field.GetDeclaringClass() == temp_class) {
5644 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005645 }
5646 }
5647
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005648 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005649 for (ArtField& field : new_class->GetSFields()) {
5650 if (field.GetDeclaringClass() == temp_class) {
5651 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005652 }
5653 }
5654
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005655 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005656 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005657 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005658 if (method.GetDeclaringClass() == temp_class) {
5659 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005660 }
5661 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005662
5663 // Make sure the remembered set and mod-union tables know that we updated some of the native
5664 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005665 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005666}
5667
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005668void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005669 CHECK(class_loader->GetAllocator() == nullptr);
5670 CHECK(class_loader->GetClassTable() == nullptr);
5671 Thread* const self = Thread::Current();
5672 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005673 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005674 // Create and set the class table.
5675 data.class_table = new ClassTable;
5676 class_loader->SetClassTable(data.class_table);
5677 // Create and set the linear allocator.
5678 data.allocator = Runtime::Current()->CreateLinearAlloc();
5679 class_loader->SetAllocator(data.allocator);
5680 // Add to the list so that we know to free the data later.
5681 class_loaders_.push_back(data);
5682}
5683
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005684ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005685 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005686 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005687 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005688 ClassTable* class_table = class_loader->GetClassTable();
5689 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005690 RegisterClassLoader(class_loader);
5691 class_table = class_loader->GetClassTable();
5692 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005693 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005694 return class_table;
5695}
5696
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005697ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005698 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005699}
5700
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005701static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005702 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005703 while (klass->HasSuperClass()) {
5704 klass = klass->GetSuperClass();
5705 if (klass->ShouldHaveImt()) {
5706 return klass->GetImt(pointer_size);
5707 }
5708 }
5709 return nullptr;
5710}
5711
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005712bool ClassLinker::LinkClass(Thread* self,
5713 const char* descriptor,
5714 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005715 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005716 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005717 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005718
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005719 if (!LinkSuperClass(klass)) {
5720 return false;
5721 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005722 ArtMethod* imt_data[ImTable::kSize];
5723 // If there are any new conflicts compared to super class.
5724 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005725 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005726 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005727 return false;
5728 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005729 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005730 return false;
5731 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005732 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005733 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005734 return false;
5735 }
5736 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005737 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005738
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005739 ImTable* imt = nullptr;
5740 if (klass->ShouldHaveImt()) {
5741 // If there are any new conflicts compared to the super class we can not make a copy. There
5742 // can be cases where both will have a conflict method at the same slot without having the same
5743 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5744 // will possibly create a table that is incorrect for either of the classes.
5745 // Same IMT with new_conflict does not happen very often.
5746 if (!new_conflict) {
5747 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5748 if (super_imt != nullptr) {
5749 bool imt_equals = true;
5750 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5751 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5752 }
5753 if (imt_equals) {
5754 imt = super_imt;
5755 }
5756 }
5757 }
5758 if (imt == nullptr) {
5759 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5760 imt = reinterpret_cast<ImTable*>(
5761 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5762 if (imt == nullptr) {
5763 return false;
5764 }
5765 imt->Populate(imt_data, image_pointer_size_);
5766 }
5767 }
5768
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005769 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5770 // We don't need to retire this class as it has no embedded tables or it was created the
5771 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005772 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005773
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005774 if (klass->ShouldHaveEmbeddedVTable()) {
5775 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005776 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005777 if (klass->ShouldHaveImt()) {
5778 klass->SetImt(imt, image_pointer_size_);
5779 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005780
5781 // Update CHA info based on whether we override methods.
5782 // Have to do this before setting the class as resolved which allows
5783 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005784 if (cha_ != nullptr) {
5785 cha_->UpdateAfterLoadingOf(klass);
5786 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005787
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005788 // This will notify waiters on klass that saw the not yet resolved
5789 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005790 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005791 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005792 } else {
5793 CHECK(!klass->IsResolved());
5794 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005795 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005796 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005797 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5798 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5799 // may not see any references to the target space and clean the card for a class if another
5800 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005801 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005802 klass->SetSFieldsPtrUnchecked(nullptr);
5803 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005804 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005805 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005806 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005807 return false;
5808 }
5809
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005810 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5811 ObjectLock<mirror::Class> lock(self, h_new_class);
5812 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005813
5814 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005815 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005816 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005817 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005818 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005819 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005820 if (class_loader != nullptr) {
5821 // We updated the class in the class table, perform the write barrier so that the GC knows
5822 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005823 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005824 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005825 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005826 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005827 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5828 }
5829 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005830
Mingyao Yang063fc772016-08-02 11:02:54 -07005831 // Update CHA info based on whether we override methods.
5832 // Have to do this before setting the class as resolved which allows
5833 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005834 if (cha_ != nullptr) {
5835 cha_->UpdateAfterLoadingOf(h_new_class);
5836 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005837
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005838 // This will notify waiters on temp class that saw the not yet resolved class in the
5839 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005840 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005841
Vladimir Marko2c64a832018-01-04 11:31:56 +00005842 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005843 // This will notify waiters on new_class that saw the not yet resolved
5844 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005845 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005846 // Return the new class.
5847 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005848 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005849 return true;
5850}
5851
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005852bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005853 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005854 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005855 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5856 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005857 // Check that a class does not inherit from itself directly.
5858 //
5859 // TODO: This is a cheap check to detect the straightforward case
5860 // of a class extending itself (b/28685551), but we should do a
5861 // proper cycle detection on loaded classes, to detect all cases
5862 // of class circularity errors (b/28830038).
5863 if (super_class_idx == class_def.class_idx_) {
5864 ThrowClassCircularityError(klass.Get(),
5865 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005866 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005867 return false;
5868 }
5869
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005870 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005871 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005872 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005873 return false;
5874 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005875 // Verify
5876 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005877 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005878 super_class->PrettyDescriptor().c_str(),
5879 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005880 return false;
5881 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005882 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005883 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005884 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005885 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005886 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005887 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005888 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005889 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005890 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005891 DCHECK(Thread::Current()->IsExceptionPending());
5892 return false;
5893 }
5894 // Verify
5895 if (!klass->CanAccess(interface)) {
5896 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005897 ThrowIllegalAccessError(klass.Get(),
5898 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005899 interface->PrettyDescriptor().c_str(),
5900 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005901 return false;
5902 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005903 }
5904 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005905 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005906 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005907 return true;
5908}
5909
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005910bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005911 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005912 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005913 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5914 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005915 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005916 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005917 return false;
5918 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005919 return true;
5920 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005921 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005922 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005923 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005924 return false;
5925 }
5926 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005927 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005928 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5929 return false;
5930 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005931 if (super->IsFinal()) {
5932 ThrowVerifyError(klass.Get(),
5933 "Superclass %s of %s is declared final",
5934 super->PrettyDescriptor().c_str(),
5935 klass->PrettyDescriptor().c_str());
5936 return false;
5937 }
5938 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005939 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005940 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005941 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005942 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005943 return false;
5944 }
5945 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005946 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005947 super->PrettyDescriptor().c_str(),
5948 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005949 return false;
5950 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005951
Brian Carlstromf3632832014-05-20 15:36:53 -07005952 // Inherit kAccClassIsFinalizable from the superclass in case this
5953 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005954 if (super->IsFinalizable()) {
5955 klass->SetFinalizable();
5956 }
5957
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005958 // Inherit class loader flag form super class.
5959 if (super->IsClassLoaderClass()) {
5960 klass->SetClassLoaderClass();
5961 }
5962
Elliott Hughes2da50362011-10-10 16:57:08 -07005963 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005964 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005965 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005966 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005967 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005968 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005969 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005970 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005971 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005972 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005973 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005974 return false;
5975 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005976
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005977 if (kIsDebugBuild) {
5978 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005979 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005980 CHECK(super->IsResolved());
5981 super = super->GetSuperClass();
5982 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005983 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005984 return true;
5985}
5986
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005987// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005988bool ClassLinker::LinkMethods(Thread* self,
5989 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005990 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005991 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005992 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005993 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005994 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5995 // need to have default methods be in the virtuals array of each class but we don't set that up
5996 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005997 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005998 // Link virtual methods then interface methods.
5999 // We set up the interface lookup table first because we need it to determine if we need to update
6000 // any vtable entries with new default method implementations.
6001 return SetupInterfaceLookupTable(self, klass, interfaces)
6002 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006003 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006004}
6005
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006006// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6007// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6008// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006009class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006010 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006011 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006012 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006013 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6014 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006015 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006016 }
6017
6018 const char* GetName() {
6019 if (name_ == nullptr) {
6020 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6021 }
6022 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006023 }
6024
Mathieu Chartiere401d142015-04-22 13:56:20 -07006025 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006026 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006027 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006028 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006029 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006030 if (dex_file_ == other_dex_file) {
6031 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6032 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006033 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006034 uint32_t other_name_len;
6035 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6036 &other_name_len);
6037 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6038 return false;
6039 }
6040 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6041 }
6042
6043 private:
6044 // Dex file for the method to compare against.
6045 const DexFile* const dex_file_;
6046 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006047 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006048 // Lazily computed name from the dex file's strings.
6049 const char* name_;
6050 // Lazily computed name length.
6051 uint32_t name_len_;
6052};
6053
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006054class LinkVirtualHashTable {
6055 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006056 LinkVirtualHashTable(Handle<mirror::Class> klass,
6057 size_t hash_size,
6058 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006059 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006060 : klass_(klass),
6061 hash_size_(hash_size),
6062 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006063 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006064 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6065 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006066
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006067 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006068 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6069 virtual_method_index, image_pointer_size_);
6070 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006071 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006072 uint32_t index = hash % hash_size_;
6073 // Linear probe until we have an empty slot.
6074 while (hash_table_[index] != invalid_index_) {
6075 if (++index == hash_size_) {
6076 index = 0;
6077 }
6078 }
6079 hash_table_[index] = virtual_method_index;
6080 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006081
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006082 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006083 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006084 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006085 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006086 size_t index = hash % hash_size_;
6087 while (true) {
6088 const uint32_t value = hash_table_[index];
6089 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6090 // the block and can safely assume not found.
6091 if (value == invalid_index_) {
6092 break;
6093 }
6094 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006095 ArtMethod* virtual_method =
6096 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6097 if (comparator->HasSameNameAndSignature(
6098 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006099 hash_table_[index] = removed_index_;
6100 return value;
6101 }
6102 }
6103 if (++index == hash_size_) {
6104 index = 0;
6105 }
6106 }
6107 return GetNotFoundIndex();
6108 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006109
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006110 static uint32_t GetNotFoundIndex() {
6111 return invalid_index_;
6112 }
6113
6114 private:
6115 static const uint32_t invalid_index_;
6116 static const uint32_t removed_index_;
6117
6118 Handle<mirror::Class> klass_;
6119 const size_t hash_size_;
6120 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006121 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006122};
6123
6124const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6125const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6126
Stephen Hines1ddd9132017-02-08 01:51:18 -08006127bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006128 Thread* self,
6129 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006130 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006131 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006132 if (klass->IsInterface()) {
6133 // No vtable.
6134 if (!IsUint<16>(num_virtual_methods)) {
6135 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6136 return false;
6137 }
6138 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006139 // Assign each method an IMT index and set the default flag.
6140 for (size_t i = 0; i < num_virtual_methods; ++i) {
6141 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6142 m->SetMethodIndex(i);
6143 if (!m->IsAbstract()) {
6144 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6145 has_defaults = true;
6146 }
6147 }
6148 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6149 // during initialization. This is a performance optimization. We could simply traverse the
6150 // virtual_methods_ array again during initialization.
6151 if (has_defaults) {
6152 klass->SetHasDefaultMethods();
6153 }
6154 return true;
6155 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006156 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6157 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006158 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006159 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006160 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006161 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006162 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006163 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006164 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006165 return false;
6166 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006167 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006168 vtable->SetElementPtrSize(
6169 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006170 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006171 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6172 // might give us new default methods). If no new interfaces then we can skip the rest since
6173 // the class cannot override any of the super-class's methods. This is required for
6174 // correctness since without it we might not update overridden default method vtable entries
6175 // correctly.
6176 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006177 klass->SetVTable(vtable.Get());
6178 return true;
6179 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006180 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006181 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006182 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006183 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006184 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6185 // might give us new default methods). See comment above.
6186 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006187 klass->SetVTable(super_vtable);
6188 return true;
6189 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006190 vtable = hs.NewHandle(
6191 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006192 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006193 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006194 return false;
6195 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006196 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006197 // How the algorithm works:
6198 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6199 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6200 // method which has not been matched to a vtable method, and j if the virtual method at the
6201 // index overrode the super virtual method at index j.
6202 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6203 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6204 // the need for the initial vtable which we later shrink back down).
6205 // 3. Add non overridden methods to the end of the vtable.
6206 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006207 // + 1 so that even if we only have new default methods we will still be able to use this hash
6208 // table (i.e. it will never have 0 size).
6209 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006210 uint32_t* hash_table_ptr;
6211 std::unique_ptr<uint32_t[]> hash_heap_storage;
6212 if (hash_table_size <= kMaxStackHash) {
6213 hash_table_ptr = reinterpret_cast<uint32_t*>(
6214 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6215 } else {
6216 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6217 hash_table_ptr = hash_heap_storage.get();
6218 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006219 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006220 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006221 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006222 DCHECK(klass->GetVirtualMethodDuringLinking(
6223 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006224 hash_table.Add(i);
6225 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006226 // 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 -07006227 // the hash table.
6228 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006229 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006230 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006231 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6232 super_method->GetAccessFlags())) {
6233 // Continue on to the next method since this one is package private and canot be overridden.
6234 // Before Android 4.1, the package-private method super_method might have been incorrectly
6235 // overridden.
6236 continue;
6237 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006238 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006239 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006240 // We remove the method so that subsequent lookups will be faster by making the hash-map
6241 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006242 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6243 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006244 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6245 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006246 if (super_method->IsFinal()) {
6247 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6248 virtual_method->PrettyMethod().c_str(),
6249 super_method->GetDeclaringClassDescriptor());
6250 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006251 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006252 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6253 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006254 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006255 // We didn't directly override this method but we might through default methods...
6256 // Check for default method update.
6257 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006258 switch (FindDefaultMethodImplementation(self,
6259 super_method,
6260 klass,
6261 /*out*/&default_method)) {
6262 case DefaultMethodSearchResult::kDefaultConflict: {
6263 // A conflict was found looking for default methods. Note this (assuming it wasn't
6264 // pre-existing) in the translations map.
6265 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6266 // Don't generate another conflict method to reduce memory use as an optimization.
6267 default_translations->insert(
6268 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6269 }
6270 break;
6271 }
6272 case DefaultMethodSearchResult::kAbstractFound: {
6273 // No conflict but method is abstract.
6274 // We note that this vtable entry must be made abstract.
6275 if (UNLIKELY(!super_method->IsAbstract())) {
6276 default_translations->insert(
6277 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6278 }
6279 break;
6280 }
6281 case DefaultMethodSearchResult::kDefaultFound: {
6282 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6283 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6284 // Found a default method implementation that is new.
6285 // TODO Refactor this add default methods to virtuals here and not in
6286 // LinkInterfaceMethods maybe.
6287 // The problem is default methods might override previously present
6288 // default-method or miranda-method vtable entries from the superclass.
6289 // Unfortunately we need these to be entries in this class's virtuals. We do not
6290 // give these entries there until LinkInterfaceMethods so we pass this map around
6291 // to let it know which vtable entries need to be updated.
6292 // Make a note that vtable entry j must be updated, store what it needs to be updated
6293 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6294 // then.
6295 default_translations->insert(
6296 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006297 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6298 << " overridden by default "
6299 << default_method->PrettyMethod()
6300 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006301 }
6302 break;
6303 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006304 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006305 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006306 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006307 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006308 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006309 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006310 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006311 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6312 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006313 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006314 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006315 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006316 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006317 local_method->SetMethodIndex(actual_count);
6318 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006319 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006320 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006321 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006322 return false;
6323 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006324 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006325 CHECK_LE(actual_count, max_count);
6326 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006327 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006328 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006329 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006330 return false;
6331 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006332 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006333 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006334 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006335 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006336 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006337 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6338 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006339 return false;
6340 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006341 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006342 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006343 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006344 return false;
6345 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006346 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006347 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6348 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006349 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006350 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006351 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006352 }
6353 return true;
6354}
6355
Alex Light9139e002015-10-09 15:59:48 -07006356// Determine if the given iface has any subinterface in the given list that declares the method
6357// specified by 'target'.
6358//
6359// Arguments
6360// - self: The thread we are running on
6361// - target: A comparator that will match any method that overrides the method we are checking for
6362// - iftable: The iftable we are searching for an overriding method on.
6363// - ifstart: The index of the interface we are checking to see if anything overrides
6364// - iface: The interface we are checking to see if anything overrides.
6365// - image_pointer_size:
6366// The image pointer size.
6367//
6368// Returns
6369// - True: There is some method that matches the target comparator defined in an interface that
6370// is a subtype of iface.
6371// - False: There is no method that matches the target comparator in any interface that is a subtype
6372// of iface.
6373static bool ContainsOverridingMethodOf(Thread* self,
6374 MethodNameAndSignatureComparator& target,
6375 Handle<mirror::IfTable> iftable,
6376 size_t ifstart,
6377 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006378 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006379 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006380 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006381 DCHECK(iface != nullptr);
6382 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006383 DCHECK_GE(ifstart, 0u);
6384 DCHECK_LT(ifstart, iftable->Count());
6385 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6386 DCHECK(iface->IsInterface());
6387
6388 size_t iftable_count = iftable->Count();
6389 StackHandleScope<1> hs(self);
6390 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6391 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6392 // Skip ifstart since our current interface obviously cannot override itself.
6393 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006394 // Iterate through every method on this interface. The order does not matter.
6395 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006396 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006397 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006398 // Check if the i'th interface is a subtype of this one.
6399 if (iface->IsAssignableFrom(current_iface.Get())) {
6400 return true;
6401 }
6402 break;
6403 }
6404 }
6405 }
6406 return false;
6407}
6408
Alex Lighteb7c1442015-08-31 13:17:42 -07006409// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006410// out_default_method and returns kDefaultFound on success. If no default method was found return
6411// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6412// default_method conflict) it will return kDefaultConflict.
6413ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6414 Thread* self,
6415 ArtMethod* target_method,
6416 Handle<mirror::Class> klass,
6417 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006418 DCHECK(self != nullptr);
6419 DCHECK(target_method != nullptr);
6420 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006421
6422 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006423
6424 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6425 // table. This lets us walk the table backwards when searching for default methods. The first one
6426 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6427 // track of it and then continue checking all other interfaces, since we need to throw an error if
6428 // we encounter conflicting default method implementations (one is not a subtype of the other).
6429 //
6430 // The order of unrelated interfaces does not matter and is not defined.
6431 size_t iftable_count = klass->GetIfTableCount();
6432 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006433 // No interfaces. We have already reset out to null so just return kAbstractFound.
6434 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006435 }
6436
Alex Light9139e002015-10-09 15:59:48 -07006437 StackHandleScope<3> hs(self);
6438 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006439 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006440 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006441 MethodNameAndSignatureComparator target_name_comparator(
6442 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6443 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006444 for (size_t k = iftable_count; k != 0; ) {
6445 --k;
6446
Alex Lighteb7c1442015-08-31 13:17:42 -07006447 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006448
6449 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006450 // Iterate through every declared method on this interface. The order does not matter.
6451 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6452 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 // Skip abstract methods and methods with different names.
6454 if (current_method->IsAbstract() ||
6455 !target_name_comparator.HasSameNameAndSignature(
6456 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6457 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006458 } else if (!current_method->IsPublic()) {
6459 // The verifier should have caught the non-public method for dex version 37. Just warn and
6460 // skip it since this is from before default-methods so we don't really need to care that it
6461 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006462 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6463 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006464 << "This will be a fatal error in subsequent versions of android. "
6465 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006466 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006467 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006468 // We have multiple default impls of the same method. This is a potential default conflict.
6469 // We need to check if this possibly conflicting method is either a superclass of the chosen
6470 // default implementation or is overridden by a non-default interface method. In either case
6471 // there is no conflict.
6472 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6473 !ContainsOverridingMethodOf(self,
6474 target_name_comparator,
6475 iftable,
6476 k,
6477 iface,
6478 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006479 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006480 << current_method->PrettyMethod() << " and "
6481 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6482 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006483 *out_default_method = nullptr;
6484 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006485 } else {
6486 break; // Continue checking at the next interface.
6487 }
6488 } else {
Alex Light9139e002015-10-09 15:59:48 -07006489 // chosen_iface == null
6490 if (!ContainsOverridingMethodOf(self,
6491 target_name_comparator,
6492 iftable,
6493 k,
6494 iface,
6495 image_pointer_size_)) {
6496 // Don't set this as the chosen interface if something else is overriding it (because that
6497 // other interface would be potentially chosen instead if it was default). If the other
6498 // interface was abstract then we wouldn't select this interface as chosen anyway since
6499 // the abstract method masks it.
6500 *out_default_method = current_method;
6501 chosen_iface.Assign(iface.Get());
6502 // We should now finish traversing the graph to find if we have default methods that
6503 // conflict.
6504 } else {
David Sehr709b0702016-10-13 09:12:37 -07006505 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6506 << "' was "
6507 << "skipped because it was overridden by an abstract method in a "
6508 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006509 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006510 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006511 break;
6512 }
6513 }
Alex Light9139e002015-10-09 15:59:48 -07006514 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006515 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6516 << "' selected "
6517 << "as the implementation for '" << target_method->PrettyMethod()
6518 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006519 return DefaultMethodSearchResult::kDefaultFound;
6520 } else {
6521 return DefaultMethodSearchResult::kAbstractFound;
6522 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006523}
6524
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006525ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006526 ArtMethod* conflict_method,
6527 ArtMethod* interface_method,
6528 ArtMethod* method,
6529 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006530 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006531 Runtime* const runtime = Runtime::Current();
6532 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6533 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6534
6535 // Create a new entry if the existing one is the shared conflict method.
6536 ArtMethod* new_conflict_method = new_entry
6537 ? runtime->CreateImtConflictMethod(linear_alloc)
6538 : conflict_method;
6539
6540 // Allocate a new table. Note that we will leak this table at the next conflict,
6541 // but that's a tradeoff compared to making the table fixed size.
6542 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006543 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6544 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006545 if (data == nullptr) {
6546 LOG(ERROR) << "Failed to allocate conflict table";
6547 return conflict_method;
6548 }
6549 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6550 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006551 method,
6552 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006553
6554 // Do a fence to ensure threads see the data in the table before it is assigned
6555 // to the conflict method.
6556 // Note that there is a race in the presence of multiple threads and we may leak
6557 // memory from the LinearAlloc, but that's a tradeoff compared to using
6558 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006559 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006560 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006561 return new_conflict_method;
6562}
6563
Vladimir Marko921094a2017-01-12 18:37:06 +00006564bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6565 Handle<mirror::Class> klass,
6566 Handle<mirror::IfTable> iftable) {
6567 DCHECK(!klass->IsInterface());
6568 const bool has_superclass = klass->HasSuperClass();
6569 const bool extend_super_iftable = has_superclass;
6570 const size_t ifcount = klass->GetIfTableCount();
6571 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6572 for (size_t i = 0; i < ifcount; ++i) {
6573 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6574 if (num_methods > 0) {
6575 const bool is_super = i < super_ifcount;
6576 // This is an interface implemented by a super-class. Therefore we can just copy the method
6577 // array from the superclass.
6578 const bool super_interface = is_super && extend_super_iftable;
6579 ObjPtr<mirror::PointerArray> method_array;
6580 if (super_interface) {
6581 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6582 DCHECK(if_table != nullptr);
6583 DCHECK(if_table->GetMethodArray(i) != nullptr);
6584 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006585 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6586 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006587 } else {
6588 method_array = AllocPointerArray(self, num_methods);
6589 }
6590 if (UNLIKELY(method_array == nullptr)) {
6591 self->AssertPendingOOMException();
6592 return false;
6593 }
6594 iftable->SetMethodArray(i, method_array);
6595 }
6596 }
6597 return true;
6598}
6599
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006600void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6601 ArtMethod* imt_conflict_method,
6602 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006603 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006604 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006605 // Place method in imt if entry is empty, place conflict otherwise.
6606 if (*imt_ref == unimplemented_method) {
6607 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006608 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006609 // If we are not a conflict and we have the same signature and name as the imt
6610 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006611 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6612 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006613 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006614 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006615 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006616 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006617 *imt_ref = current_method;
6618 } else {
Alex Light9139e002015-10-09 15:59:48 -07006619 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006620 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006621 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006622 } else {
6623 // Place the default conflict method. Note that there may be an existing conflict
6624 // method in the IMT, but it could be one tailored to the super class, with a
6625 // specific ImtConflictTable.
6626 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006627 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006628 }
6629}
6630
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006631void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006632 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6633 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006634 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006635 Runtime* const runtime = Runtime::Current();
6636 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6637 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006638 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006639 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006640 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006641 FillIMTFromIfTable(klass->GetIfTable(),
6642 unimplemented_method,
6643 conflict_method,
6644 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006645 /*create_conflict_tables=*/true,
6646 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006647 &new_conflict,
6648 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006649 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006650 if (!klass->ShouldHaveImt()) {
6651 return;
6652 }
6653 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6654 // we can just use the same pointer.
6655 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006656 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006657 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6658 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6659 bool same = true;
6660 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6661 ArtMethod* method = imt_data[i];
6662 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6663 if (method != super_method) {
6664 bool is_conflict_table = method->IsRuntimeMethod() &&
6665 method != unimplemented_method &&
6666 method != conflict_method;
6667 // Verify conflict contents.
6668 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6669 super_method != unimplemented_method &&
6670 super_method != conflict_method;
6671 if (!is_conflict_table || !super_conflict_table) {
6672 same = false;
6673 } else {
6674 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6675 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6676 same = same && table1->Equals(table2, image_pointer_size_);
6677 }
6678 }
6679 }
6680 if (same) {
6681 imt = super_imt;
6682 }
6683 }
6684 if (imt == nullptr) {
6685 imt = klass->GetImt(image_pointer_size_);
6686 DCHECK(imt != nullptr);
6687 imt->Populate(imt_data, image_pointer_size_);
6688 } else {
6689 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006690 }
6691}
6692
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006693ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6694 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006695 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006696 void* data = linear_alloc->Alloc(Thread::Current(),
6697 ImtConflictTable::ComputeSize(count,
6698 image_pointer_size));
6699 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6700}
6701
6702ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6703 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6704}
6705
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006706void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006707 ArtMethod* unimplemented_method,
6708 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006709 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006710 bool create_conflict_tables,
6711 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006712 /*out*/bool* new_conflict,
6713 /*out*/ArtMethod** imt) {
6714 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006715 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006716 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006717 const size_t num_virtuals = interface->NumVirtualMethods();
6718 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6719 // Virtual methods can be larger than the if table methods if there are default methods.
6720 DCHECK_GE(num_virtuals, method_array_count);
6721 if (kIsDebugBuild) {
6722 if (klass->IsInterface()) {
6723 DCHECK_EQ(method_array_count, 0u);
6724 } else {
6725 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6726 }
6727 }
6728 if (method_array_count == 0) {
6729 continue;
6730 }
6731 auto* method_array = if_table->GetMethodArray(i);
6732 for (size_t j = 0; j < method_array_count; ++j) {
6733 ArtMethod* implementation_method =
6734 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6735 if (ignore_copied_methods && implementation_method->IsCopied()) {
6736 continue;
6737 }
6738 DCHECK(implementation_method != nullptr);
6739 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6740 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6741 // or interface methods in the IMT here they will not create extra conflicts since we compare
6742 // names and signatures in SetIMTRef.
6743 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006744 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006745
6746 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6747 // the same implementation method, keep track of this to avoid creating a conflict table in
6748 // this case.
6749
6750 // Conflict table size for each IMT slot.
6751 ++conflict_counts[imt_index];
6752
6753 SetIMTRef(unimplemented_method,
6754 imt_conflict_method,
6755 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006756 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006757 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006758 }
6759 }
6760
6761 if (create_conflict_tables) {
6762 // Create the conflict tables.
6763 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006764 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006765 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006766 if (imt[i] == imt_conflict_method) {
6767 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6768 if (new_table != nullptr) {
6769 ArtMethod* new_conflict_method =
6770 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6771 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6772 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006773 } else {
6774 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006775 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006776 }
6777 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006778 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006779 }
6780 }
6781
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006782 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006783 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006784 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6785 // Virtual methods can be larger than the if table methods if there are default methods.
6786 if (method_array_count == 0) {
6787 continue;
6788 }
6789 auto* method_array = if_table->GetMethodArray(i);
6790 for (size_t j = 0; j < method_array_count; ++j) {
6791 ArtMethod* implementation_method =
6792 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6793 if (ignore_copied_methods && implementation_method->IsCopied()) {
6794 continue;
6795 }
6796 DCHECK(implementation_method != nullptr);
6797 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006798 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006799 if (!imt[imt_index]->IsRuntimeMethod() ||
6800 imt[imt_index] == unimplemented_method ||
6801 imt[imt_index] == imt_conflict_method) {
6802 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006803 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006804 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6805 const size_t num_entries = table->NumEntries(image_pointer_size_);
6806 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6807 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006808 }
6809 }
6810 }
6811}
6812
Alex Lighteb7c1442015-08-31 13:17:42 -07006813// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6814// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006815static bool NotSubinterfaceOfAny(
6816 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6817 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006818 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006819 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006820 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006821 for (ObjPtr<mirror::Class> c : classes) {
6822 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006823 return false;
6824 }
6825 }
6826 return true;
6827}
6828
6829// Fills in and flattens the interface inheritance hierarchy.
6830//
6831// By the end of this function all interfaces in the transitive closure of to_process are added to
6832// the iftable and every interface precedes all of its sub-interfaces in this list.
6833//
6834// all I, J: Interface | I <: J implies J precedes I
6835//
6836// (note A <: B means that A is a subtype of B)
6837//
6838// This returns the total number of items in the iftable. The iftable might be resized down after
6839// this call.
6840//
6841// We order this backwards so that we do not need to reorder superclass interfaces when new
6842// interfaces are added in subclass's interface tables.
6843//
6844// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6845// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6846// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6847// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006848static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006849 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006850 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006851 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006852 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006853 // This is the set of all class's already in the iftable. Used to make checking if a class has
6854 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006855 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006856 // The first super_ifcount elements are from the superclass. We note that they are already added.
6857 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006858 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006859 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6860 classes_in_iftable.insert(iface);
6861 }
6862 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006863 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006864 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6865 // At this point in the loop current-iface-list has the invariant that:
6866 // for every pair of interfaces I,J within it:
6867 // if index_of(I) < index_of(J) then I is not a subtype of J
6868
6869 // If we have already seen this element then all of its super-interfaces must already be in the
6870 // current-iface-list so we can skip adding it.
6871 if (!ContainsElement(classes_in_iftable, interface)) {
6872 // We haven't seen this interface so add all of its super-interfaces onto the
6873 // current-iface-list, skipping those already on it.
6874 int32_t ifcount = interface->GetIfTableCount();
6875 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006876 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006877 if (!ContainsElement(classes_in_iftable, super_interface)) {
6878 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6879 classes_in_iftable.insert(super_interface);
6880 iftable->SetInterface(filled_ifcount, super_interface);
6881 filled_ifcount++;
6882 }
6883 }
6884 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6885 // Place this interface onto the current-iface-list after all of its super-interfaces.
6886 classes_in_iftable.insert(interface);
6887 iftable->SetInterface(filled_ifcount, interface);
6888 filled_ifcount++;
6889 } else if (kIsDebugBuild) {
6890 // Check all super-interfaces are already in the list.
6891 int32_t ifcount = interface->GetIfTableCount();
6892 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006893 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006894 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006895 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6896 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006897 }
6898 }
6899 }
6900 if (kIsDebugBuild) {
6901 // Check that the iftable is ordered correctly.
6902 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006903 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006904 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006905 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006906 // !(if_a <: if_b)
6907 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006908 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6909 << ") extends "
6910 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006911 << "interface list.";
6912 }
6913 }
6914 }
6915 return filled_ifcount;
6916}
6917
6918bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6919 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6920 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006921 const bool has_superclass = klass->HasSuperClass();
6922 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006923 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006924 const size_t num_interfaces =
6925 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006926 if (num_interfaces == 0) {
6927 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006928 if (LIKELY(has_superclass)) {
6929 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6930 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006931 // Class implements no interfaces.
6932 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006933 return true;
6934 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006935 // Class implements same interfaces as parent, are any of these not marker interfaces?
6936 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006937 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006938 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006939 if (super_iftable->GetMethodArrayCount(i) > 0) {
6940 has_non_marker_interface = true;
6941 break;
6942 }
6943 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006944 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006945 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006946 klass->SetIfTable(super_iftable);
6947 return true;
6948 }
6949 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006950 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006951 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006952 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006953 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006954 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006955 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006956 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006957 if (UNLIKELY(!interface->IsInterface())) {
6958 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006959 ThrowIncompatibleClassChangeError(klass.Get(),
6960 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006961 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006962 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6963 return false;
6964 }
6965 ifcount += interface->GetIfTableCount();
6966 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006967 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006968 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006969 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006970 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006971 return false;
6972 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006973 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006974 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006975 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006976 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006977 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006978 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006979 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006980 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006981
6982 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6983 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6984 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006985 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006986
6987 size_t new_ifcount;
6988 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006989 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01006990 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07006991 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006992 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006993 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01006994 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006995 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006996
6997 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006998 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006999
Ian Rogers7b078e82014-09-10 14:44:24 -07007000 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007001
Ian Rogersb52b01a2012-01-12 17:01:38 -08007002 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007003 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007004 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007005 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007006 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007007 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007008 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007009 return false;
7010 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007011 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007012 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007013 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007014 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007015 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007016 return true;
7017}
7018
Alex Light1f3925d2016-09-07 12:04:20 -07007019// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7020// of methods must be unique.
7021static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7022 return nullptr;
7023}
7024
7025template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007026static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007027 const ScopedArenaVector<ArtMethod*>& list,
7028 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007029 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007030 for (ArtMethod* method : list) {
7031 if (cmp.HasSameNameAndSignature(method)) {
7032 return method;
7033 }
7034 }
Alex Light1f3925d2016-09-07 12:04:20 -07007035 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007036}
7037
Alex Light1f3925d2016-09-07 12:04:20 -07007038// Check that all vtable entries are present in this class's virtuals or are the same as a
7039// superclasses vtable entry.
7040static void CheckClassOwnsVTableEntries(Thread* self,
7041 Handle<mirror::Class> klass,
7042 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007043 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007044 StackHandleScope<2> hs(self);
7045 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007046 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007047 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007048 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007049 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7050 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7051 CHECK(m != nullptr);
7052
Alex Lighta41a30782017-03-29 11:33:19 -07007053 if (m->GetMethodIndexDuringLinking() != i) {
7054 LOG(WARNING) << m->PrettyMethod()
7055 << " has an unexpected method index for its spot in the vtable for class"
7056 << klass->PrettyClass();
7057 }
Alex Lighte64300b2015-12-15 15:02:47 -08007058 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7059 auto is_same_method = [m] (const ArtMethod& meth) {
7060 return &meth == m;
7061 };
Alex Light3f980532017-03-17 15:10:32 -07007062 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7063 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7064 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7065 << klass->PrettyClass() << " or any of its superclasses!";
7066 }
Alex Lighte64300b2015-12-15 15:02:47 -08007067 }
7068}
7069
Alex Light1f3925d2016-09-07 12:04:20 -07007070// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7071// method is overridden in a subclass.
7072static void CheckVTableHasNoDuplicates(Thread* self,
7073 Handle<mirror::Class> klass,
7074 PointerSize pointer_size)
7075 REQUIRES_SHARED(Locks::mutator_lock_) {
7076 StackHandleScope<1> hs(self);
7077 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7078 int32_t num_entries = vtable->GetLength();
7079 for (int32_t i = 0; i < num_entries; i++) {
7080 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7081 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
7082 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7083 vtable_entry->GetAccessFlags())) {
7084 continue;
7085 }
7086 MethodNameAndSignatureComparator name_comparator(
7087 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07007088 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07007089 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07007090 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
7091 other_entry->GetAccessFlags())) {
7092 continue;
7093 }
Alex Light3f980532017-03-17 15:10:32 -07007094 if (vtable_entry == other_entry ||
7095 name_comparator.HasSameNameAndSignature(
7096 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
7097 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7098 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
7099 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
7100 << other_entry->PrettyMethod() << " (0x" << std::hex
7101 << reinterpret_cast<uintptr_t>(other_entry) << ")";
7102 }
Alex Light1f3925d2016-09-07 12:04:20 -07007103 }
7104 }
7105}
7106
7107static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7108 REQUIRES_SHARED(Locks::mutator_lock_) {
7109 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7110 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7111}
7112
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007113void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7114 ArtMethod* unimplemented_method,
7115 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007116 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007117 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007118 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007119 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007120 if (super_class->ShouldHaveImt()) {
7121 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7122 for (size_t i = 0; i < ImTable::kSize; ++i) {
7123 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007124 }
7125 } else {
7126 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007127 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007128 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007129 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007130 FillIMTFromIfTable(if_table,
7131 unimplemented_method,
7132 imt_conflict_method,
7133 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007134 /*create_conflict_tables=*/false,
7135 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007136 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007137 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007138 }
7139 }
7140}
7141
Vladimir Marko921094a2017-01-12 18:37:06 +00007142class ClassLinker::LinkInterfaceMethodsHelper {
7143 public:
7144 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7145 Handle<mirror::Class> klass,
7146 Thread* self,
7147 Runtime* runtime)
7148 : class_linker_(class_linker),
7149 klass_(klass),
7150 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7151 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7152 self_(self),
7153 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7154 allocator_(&stack_),
7155 default_conflict_methods_(allocator_.Adapter()),
7156 overriding_default_conflict_methods_(allocator_.Adapter()),
7157 miranda_methods_(allocator_.Adapter()),
7158 default_methods_(allocator_.Adapter()),
7159 overriding_default_methods_(allocator_.Adapter()),
7160 move_table_(allocator_.Adapter()) {
7161 }
7162
7163 ArtMethod* FindMethod(ArtMethod* interface_method,
7164 MethodNameAndSignatureComparator& interface_name_comparator,
7165 ArtMethod* vtable_impl)
7166 REQUIRES_SHARED(Locks::mutator_lock_);
7167
7168 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7169 MethodNameAndSignatureComparator& interface_name_comparator)
7170 REQUIRES_SHARED(Locks::mutator_lock_);
7171
7172 bool HasNewVirtuals() const {
7173 return !(miranda_methods_.empty() &&
7174 default_methods_.empty() &&
7175 overriding_default_methods_.empty() &&
7176 overriding_default_conflict_methods_.empty() &&
7177 default_conflict_methods_.empty());
7178 }
7179
7180 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7181
7182 ObjPtr<mirror::PointerArray> UpdateVtable(
7183 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7184 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7185
7186 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7187
7188 void UpdateIMT(ArtMethod** out_imt);
7189
7190 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7191 if (kIsDebugBuild) {
7192 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7193 // Check that there are no stale methods are in the dex cache array.
7194 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7195 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007196 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7197 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007198 CHECK(move_table_.find(m) == move_table_.end() ||
7199 // The original versions of copied methods will still be present so allow those too.
7200 // Note that if the first check passes this might fail to GetDeclaringClass().
7201 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7202 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7203 [m] (ArtMethod& meth) {
7204 return &meth == m;
7205 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7206 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7207 }
7208 }
7209 }
7210
7211 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7212 LengthPrefixedArray<ArtMethod>* methods) {
7213 if (kIsDebugBuild) {
7214 CHECK(methods != nullptr);
7215 // Put some random garbage in old methods to help find stale pointers.
7216 if (methods != old_methods && old_methods != nullptr) {
7217 // Need to make sure the GC is not running since it could be scanning the methods we are
7218 // about to overwrite.
7219 ScopedThreadStateChange tsc(self_, kSuspended);
7220 gc::ScopedGCCriticalSection gcs(self_,
7221 gc::kGcCauseClassLinker,
7222 gc::kCollectorTypeClassLinker);
7223 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7224 method_size_,
7225 method_alignment_);
7226 memset(old_methods, 0xFEu, old_size);
7227 }
7228 }
7229 }
7230
7231 private:
7232 size_t NumberOfNewVirtuals() const {
7233 return miranda_methods_.size() +
7234 default_methods_.size() +
7235 overriding_default_conflict_methods_.size() +
7236 overriding_default_methods_.size() +
7237 default_conflict_methods_.size();
7238 }
7239
7240 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7241 return !klass_->IsInterface();
7242 }
7243
7244 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7245 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7246 << "Interfaces should only have default-conflict methods appended to them.";
7247 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7248 << miranda_methods_.size()
7249 << " default_methods=" << default_methods_.size()
7250 << " overriding_default_methods=" << overriding_default_methods_.size()
7251 << " default_conflict_methods=" << default_conflict_methods_.size()
7252 << " overriding_default_conflict_methods="
7253 << overriding_default_conflict_methods_.size();
7254 }
7255
7256 ClassLinker* class_linker_;
7257 Handle<mirror::Class> klass_;
7258 size_t method_alignment_;
7259 size_t method_size_;
7260 Thread* const self_;
7261
7262 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7263 // the virtual methods array.
7264 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7265 // during cross compilation.
7266 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7267 ArenaStack stack_;
7268 ScopedArenaAllocator allocator_;
7269
7270 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7271 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7272 ScopedArenaVector<ArtMethod*> miranda_methods_;
7273 ScopedArenaVector<ArtMethod*> default_methods_;
7274 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7275
7276 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7277};
7278
7279ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7280 ArtMethod* interface_method,
7281 MethodNameAndSignatureComparator& interface_name_comparator,
7282 ArtMethod* vtable_impl) {
7283 ArtMethod* current_method = nullptr;
7284 switch (class_linker_->FindDefaultMethodImplementation(self_,
7285 interface_method,
7286 klass_,
7287 /*out*/&current_method)) {
7288 case DefaultMethodSearchResult::kDefaultConflict: {
7289 // Default method conflict.
7290 DCHECK(current_method == nullptr);
7291 ArtMethod* default_conflict_method = nullptr;
7292 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7293 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7294 default_conflict_method = vtable_impl;
7295 } else {
7296 // See if we already have a conflict method for this method.
7297 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7298 interface_name_comparator,
7299 default_conflict_methods_,
7300 overriding_default_conflict_methods_);
7301 if (LIKELY(preexisting_conflict != nullptr)) {
7302 // We already have another conflict we can reuse.
7303 default_conflict_method = preexisting_conflict;
7304 } else {
7305 // Note that we do this even if we are an interface since we need to create this and
7306 // cannot reuse another classes.
7307 // Create a new conflict method for this to use.
7308 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7309 new(default_conflict_method) ArtMethod(interface_method,
7310 class_linker_->GetImagePointerSize());
7311 if (vtable_impl == nullptr) {
7312 // Save the conflict method. We need to add it to the vtable.
7313 default_conflict_methods_.push_back(default_conflict_method);
7314 } else {
7315 // Save the conflict method but it is already in the vtable.
7316 overriding_default_conflict_methods_.push_back(default_conflict_method);
7317 }
7318 }
7319 }
7320 current_method = default_conflict_method;
7321 break;
7322 } // case kDefaultConflict
7323 case DefaultMethodSearchResult::kDefaultFound: {
7324 DCHECK(current_method != nullptr);
7325 // Found a default method.
7326 if (vtable_impl != nullptr &&
7327 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7328 // We found a default method but it was the same one we already have from our
7329 // superclass. Don't bother adding it to our vtable again.
7330 current_method = vtable_impl;
7331 } else if (LIKELY(FillTables())) {
7332 // Interfaces don't need to copy default methods since they don't have vtables.
7333 // Only record this default method if it is new to save space.
7334 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7335 // would make lookup for interface super much faster. (We would only need to scan
7336 // the iftable to find if there is a NSME or AME.)
7337 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7338 default_methods_,
7339 overriding_default_methods_);
7340 if (old == nullptr) {
7341 // We found a default method implementation and there were no conflicts.
7342 if (vtable_impl == nullptr) {
7343 // Save the default method. We need to add it to the vtable.
7344 default_methods_.push_back(current_method);
7345 } else {
7346 // Save the default method but it is already in the vtable.
7347 overriding_default_methods_.push_back(current_method);
7348 }
7349 } else {
7350 CHECK(old == current_method) << "Multiple default implementations selected!";
7351 }
7352 }
7353 break;
7354 } // case kDefaultFound
7355 case DefaultMethodSearchResult::kAbstractFound: {
7356 DCHECK(current_method == nullptr);
7357 // Abstract method masks all defaults.
7358 if (vtable_impl != nullptr &&
7359 vtable_impl->IsAbstract() &&
7360 !vtable_impl->IsDefaultConflicting()) {
7361 // We need to make this an abstract method but the version in the vtable already is so
7362 // don't do anything.
7363 current_method = vtable_impl;
7364 }
7365 break;
7366 } // case kAbstractFound
7367 }
7368 return current_method;
7369}
7370
7371ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7372 ArtMethod* interface_method,
7373 MethodNameAndSignatureComparator& interface_name_comparator) {
7374 // Find out if there is already a miranda method we can use.
7375 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7376 miranda_methods_);
7377 if (miranda_method == nullptr) {
7378 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7379 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7380 CHECK(miranda_method != nullptr);
7381 // Point the interface table at a phantom slot.
7382 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7383 miranda_methods_.push_back(miranda_method);
7384 }
7385 return miranda_method;
7386}
7387
7388void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7389 LogNewVirtuals();
7390
7391 const size_t old_method_count = klass_->NumMethods();
7392 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7393 DCHECK_NE(old_method_count, new_method_count);
7394
7395 // Attempt to realloc to save RAM if possible.
7396 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7397 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7398 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7399 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7400 // CopyFrom has internal read barriers.
7401 //
7402 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7403 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7404 method_size_,
7405 method_alignment_);
7406 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7407 method_size_,
7408 method_alignment_);
7409 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7410 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007411 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007412 self_, old_methods, old_methods_ptr_size, new_size));
7413 CHECK(methods != nullptr); // Native allocation failure aborts.
7414
7415 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7416 if (methods != old_methods) {
7417 // Maps from heap allocated miranda method to linear alloc miranda method.
7418 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7419 // Copy over the old methods.
7420 for (auto& m : klass_->GetMethods(pointer_size)) {
7421 move_table_.emplace(&m, &*out);
7422 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7423 // barriers when it copies.
7424 out->CopyFrom(&m, pointer_size);
7425 ++out;
7426 }
7427 }
7428 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7429 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7430 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007431 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7432 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007433 ArtMethod& new_method = *out;
7434 new_method.CopyFrom(mir_method, pointer_size);
7435 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7436 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7437 << "Miranda method should be abstract!";
7438 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007439 // Update the entry in the method array, as the array will be used for future lookups,
7440 // where thread suspension is allowed.
7441 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7442 // would not see them.
7443 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007444 ++out;
7445 }
7446 // We need to copy the default methods into our own method table since the runtime requires that
7447 // every method on a class's vtable be in that respective class's virtual method table.
7448 // NOTE This means that two classes might have the same implementation of a method from the same
7449 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7450 // default method found on a class with one found on the declaring interface directly and must
7451 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007452 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7453 &overriding_default_methods_}) {
7454 for (size_t i = 0; i < methods_vec->size(); ++i) {
7455 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007456 ArtMethod& new_method = *out;
7457 new_method.CopyFrom(def_method, pointer_size);
7458 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7459 // verified yet it shouldn't have methods that are skipping access checks.
7460 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7461 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007462 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007463 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7464 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7465 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7466 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007467 // Update the entry in the method array, as the array will be used for future lookups,
7468 // where thread suspension is allowed.
7469 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7470 // would not see them.
7471 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007472 ++out;
7473 }
7474 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007475 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7476 &overriding_default_conflict_methods_}) {
7477 for (size_t i = 0; i < methods_vec->size(); ++i) {
7478 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007479 ArtMethod& new_method = *out;
7480 new_method.CopyFrom(conf_method, pointer_size);
7481 // This is a type of default method (there are default method impls, just a conflict) so
7482 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7483 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7484 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007485 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7486 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007487 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007488 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007489 constexpr uint32_t kMaskFlags =
7490 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007491 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7492 DCHECK(new_method.IsDefaultConflicting());
7493 // The actual method might or might not be marked abstract since we just copied it from a
7494 // (possibly default) interface method. We need to set it entry point to be the bridge so
7495 // that the compiler will not invoke the implementation of whatever method we copied from.
7496 EnsureThrowsInvocationError(class_linker_, &new_method);
7497 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007498 // Update the entry in the method array, as the array will be used for future lookups,
7499 // where thread suspension is allowed.
7500 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7501 // would not see them.
7502 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007503 ++out;
7504 }
7505 }
7506 methods->SetSize(new_method_count);
7507 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7508}
7509
7510ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7511 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7512 ObjPtr<mirror::PointerArray> old_vtable) {
7513 // Update the vtable to the new method structures. We can skip this for interfaces since they
7514 // do not have vtables.
7515 const size_t old_vtable_count = old_vtable->GetLength();
7516 const size_t new_vtable_count = old_vtable_count +
7517 miranda_methods_.size() +
7518 default_methods_.size() +
7519 default_conflict_methods_.size();
7520
7521 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007522 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007523 if (UNLIKELY(vtable == nullptr)) {
7524 self_->AssertPendingOOMException();
7525 return nullptr;
7526 }
7527
7528 size_t vtable_pos = old_vtable_count;
7529 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7530 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7531 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7532 default_conflict_methods_,
7533 miranda_methods_}) {
7534 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007535 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007536 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7537 // fields are references into the dex file the method was defined in. Since the ArtMethod
7538 // does not store that information it uses declaring_class_->dex_cache_.
7539 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7540 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7541 ++vtable_pos;
7542 }
7543 }
7544 DCHECK_EQ(vtable_pos, new_vtable_count);
7545
7546 // Update old vtable methods. We use the default_translations map to figure out what each
7547 // vtable entry should be updated to, if they need to be at all.
7548 for (size_t i = 0; i < old_vtable_count; ++i) {
7549 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7550 // Try and find what we need to change this method to.
7551 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007552 if (translation_it != default_translations.end()) {
7553 if (translation_it->second.IsInConflict()) {
7554 // Find which conflict method we are to use for this method.
7555 MethodNameAndSignatureComparator old_method_comparator(
7556 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7557 // We only need to look through overriding_default_conflict_methods since this is an
7558 // overridden method we are fixing up here.
7559 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7560 old_method_comparator, overriding_default_conflict_methods_);
7561 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7562 translated_method = new_conflict_method;
7563 } else if (translation_it->second.IsAbstract()) {
7564 // Find which miranda method we are to use for this method.
7565 MethodNameAndSignatureComparator old_method_comparator(
7566 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7567 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7568 miranda_methods_);
7569 DCHECK(miranda_method != nullptr);
7570 translated_method = miranda_method;
7571 } else {
7572 // Normal default method (changed from an older default or abstract interface method).
7573 DCHECK(translation_it->second.IsTranslation());
7574 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007575 auto it = move_table_.find(translated_method);
7576 DCHECK(it != move_table_.end());
7577 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007578 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007579 } else {
7580 auto it = move_table_.find(translated_method);
7581 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007582 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007583
7584 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007585 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007586 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007587 if (kIsDebugBuild) {
7588 auto* methods = klass_->GetMethodsPtr();
7589 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007590 reinterpret_cast<uintptr_t>(translated_method));
7591 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007592 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7593 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007594 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007595 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007596 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007597 }
7598 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007599 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007600 return vtable;
7601}
7602
7603void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7604 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7605 const size_t ifcount = klass_->GetIfTableCount();
7606 // Go fix up all the stale iftable pointers.
7607 for (size_t i = 0; i < ifcount; ++i) {
7608 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7609 auto* method_array = iftable->GetMethodArray(i);
7610 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7611 DCHECK(m != nullptr) << klass_->PrettyClass();
7612 auto it = move_table_.find(m);
7613 if (it != move_table_.end()) {
7614 auto* new_m = it->second;
7615 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7616 method_array->SetElementPtrSize(j, new_m, pointer_size);
7617 }
7618 }
7619 }
7620}
7621
7622void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7623 // Fix up IMT next.
7624 for (size_t i = 0; i < ImTable::kSize; ++i) {
7625 auto it = move_table_.find(out_imt[i]);
7626 if (it != move_table_.end()) {
7627 out_imt[i] = it->second;
7628 }
7629 }
7630}
7631
Alex Light705ad492015-09-21 11:36:30 -07007632// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007633bool ClassLinker::LinkInterfaceMethods(
7634 Thread* self,
7635 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007636 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007637 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007638 ArtMethod** out_imt) {
7639 StackHandleScope<3> hs(self);
7640 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007641
7642 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007643 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007644 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007645 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007646 const size_t ifcount = klass->GetIfTableCount();
7647
Vladimir Marko921094a2017-01-12 18:37:06 +00007648 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007649
7650 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7651 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007652 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007653 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007654 const bool extend_super_iftable = has_superclass;
7655 if (has_superclass && fill_tables) {
7656 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007657 unimplemented_method,
7658 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007659 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007660 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007661 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007662 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7663 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007664 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007665 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7666 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007667 }
7668 }
7669
Vladimir Marko921094a2017-01-12 18:37:06 +00007670 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7671
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007672 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007673 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007674 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7675 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7676 // they will already be null. This has the additional benefit that the declarer of a miranda
7677 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007678 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007679 --i;
Alex Light9139e002015-10-09 15:59:48 -07007680 DCHECK_LT(i, ifcount);
7681
Alex Light705ad492015-09-21 11:36:30 -07007682 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007683 if (num_methods > 0) {
7684 StackHandleScope<2> hs2(self);
7685 const bool is_super = i < super_ifcount;
7686 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007687 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7688 // conflict methods. Just set this as nullptr in those cases.
7689 Handle<mirror::PointerArray> method_array(fill_tables
7690 ? hs2.NewHandle(iftable->GetMethodArray(i))
7691 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007692
Alex Lighte64300b2015-12-15 15:02:47 -08007693 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007694 ScopedNullHandle<mirror::PointerArray> null_handle;
7695 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007696 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007697
Alex Light9139e002015-10-09 15:59:48 -07007698 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7699 // and confusing. Default methods should always look through all the superclasses
7700 // because they are the last choice of an implementation. We get around this by looking
7701 // at the super-classes iftable methods (copied into method_array previously) when we are
7702 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007703 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007704 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007705 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007706 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007707 using_virtuals = true;
7708 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7709 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007710 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007711 // For a new interface, however, we need the whole vtable in case a new
7712 // interface method is implemented in the whole superclass.
7713 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007714 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007715 input_vtable_array = vtable;
7716 input_array_length = input_vtable_array->GetLength();
7717 }
Alex Lighte64300b2015-12-15 15:02:47 -08007718
Alex Lighteb7c1442015-08-31 13:17:42 -07007719 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007720 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007721 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007722 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007723 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007724 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007725 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007726 // For each method listed in the interface's method list, find the
7727 // matching method in our class's method list. We want to favor the
7728 // subclass over the superclass, which just requires walking
7729 // back from the end of the vtable. (This only matters if the
7730 // superclass defines a private method and this class redefines
7731 // it -- otherwise it would use the same vtable slot. In .dex files
7732 // those don't end up in the virtual method table, so it shouldn't
7733 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007734 //
7735 // To find defaults we need to do the same but also go over interfaces.
7736 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007737 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007738 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007739 ArtMethod* vtable_method = using_virtuals ?
7740 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007741 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7742 ArtMethod* vtable_method_for_name_comparison =
7743 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007744 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007745 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007746 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007747 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7748 // allocations.
7749 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007750 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007751 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007752 vtable_method->PrettyMethod().c_str(),
7753 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007754 return false;
Alex Light9139e002015-10-09 15:59:48 -07007755 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007756 // We might have a newer, better, default method for this, so we just skip it. If we
7757 // are still using this we will select it again when scanning for default methods. To
7758 // obviate the need to copy the method again we will make a note that we already found
7759 // a default here.
7760 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007761 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007762 break;
7763 } else {
7764 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007765 if (LIKELY(fill_tables)) {
7766 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7767 // Place method in imt if entry is empty, place conflict otherwise.
7768 SetIMTRef(unimplemented_method,
7769 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007770 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007771 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007772 /*out*/imt_ptr);
7773 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007774 break;
7775 }
7776 }
Alex Light9139e002015-10-09 15:59:48 -07007777 }
7778 // Continue on to the next method if we are done.
7779 if (LIKELY(found_impl)) {
7780 continue;
7781 } else if (LIKELY(super_interface)) {
7782 // Don't look for a default implementation when the super-method is implemented directly
7783 // by the class.
7784 //
7785 // See if we can use the superclasses method and skip searching everything else.
7786 // Note: !found_impl && super_interface
7787 CHECK(extend_super_iftable);
7788 // If this is a super_interface method it is possible we shouldn't override it because a
7789 // superclass could have implemented it directly. We get the method the superclass used
7790 // to implement this to know if we can override it with a default method. Doing this is
7791 // safe since we know that the super_iftable is filled in so we can simply pull it from
7792 // there. We don't bother if this is not a super-classes interface since in that case we
7793 // have scanned the entire vtable anyway and would have found it.
7794 // TODO This is rather dirty but it is faster than searching through the entire vtable
7795 // every time.
7796 ArtMethod* supers_method =
7797 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7798 DCHECK(supers_method != nullptr);
7799 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007800 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007801 // The method is not overridable by a default method (i.e. it is directly implemented
7802 // in some class). Therefore move onto the next interface method.
7803 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007804 } else {
7805 // If the super-classes method is override-able by a default method we need to keep
7806 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7807 // 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 -07007808 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7809 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7810 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007811 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007812 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7813 << " and not 'nullptr' or "
7814 << supers_method->PrettyMethod()
7815 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007816 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007817 }
7818 }
7819 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007820 ArtMethod* current_method = helper.FindMethod(interface_method,
7821 interface_name_comparator,
7822 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007823 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007824 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007825 // We could not find an implementation for this method and since it is a brand new
7826 // interface we searched the entire vtable (and all default methods) for an
7827 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007828 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7829 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007830 }
7831
7832 if (current_method != nullptr) {
7833 // We found a default method implementation. Record it in the iftable and IMT.
7834 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7835 SetIMTRef(unimplemented_method,
7836 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007837 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007838 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007839 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007840 }
7841 }
Alex Light705ad492015-09-21 11:36:30 -07007842 } // For each method in interface end.
7843 } // if (num_methods > 0)
7844 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007845 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007846 if (helper.HasNewVirtuals()) {
7847 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7848 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7849 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7850
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007851 // 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 -07007852 // suspension assert.
7853 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007854
Alex Light705ad492015-09-21 11:36:30 -07007855 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007856 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007857 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007858 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007859 return false;
7860 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007861 helper.UpdateIfTable(iftable);
7862 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007863 }
Alex Light705ad492015-09-21 11:36:30 -07007864
Vladimir Marko921094a2017-01-12 18:37:06 +00007865 helper.CheckNoStaleMethodsInDexCache();
7866 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007867 } else {
7868 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007869 }
Alex Light705ad492015-09-21 11:36:30 -07007870 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007871 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007872 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007873 return true;
7874}
7875
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007876bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007877 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007878 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007879}
7880
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007881bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007882 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007883 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007884}
7885
Brian Carlstromdbc05252011-09-09 01:59:59 -07007886struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007887 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007888 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007889 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007890 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007891 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007892 // 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 -07007893 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7894 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007895 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007896 if (type1 == Primitive::kPrimNot) {
7897 // Reference always goes first.
7898 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007899 }
Vladimir Markod5777482014-11-12 17:02:02 +00007900 if (type2 == Primitive::kPrimNot) {
7901 // Reference always goes first.
7902 return false;
7903 }
7904 size_t size1 = Primitive::ComponentSize(type1);
7905 size_t size2 = Primitive::ComponentSize(type2);
7906 if (size1 != size2) {
7907 // Larger primitive types go first.
7908 return size1 > size2;
7909 }
7910 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7911 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007912 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007913 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7914 // by name and for equal names by type id index.
7915 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7916 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007917 }
7918};
7919
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007920bool ClassLinker::LinkFields(Thread* self,
7921 Handle<mirror::Class> klass,
7922 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007923 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007924 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007925 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007926 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7927 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007928
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007929 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007930 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007931 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007932 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007933 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007934 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007935 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007936 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007937 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007938 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007939 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007940 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007941
David Sehr709b0702016-10-13 09:12:37 -07007942 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007943
Brian Carlstromdbc05252011-09-09 01:59:59 -07007944 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007945 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007946 //
7947 // The overall sort order order is:
7948 // 1) All object reference fields, sorted alphabetically.
7949 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7950 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7951 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7952 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7953 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7954 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7955 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7956 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7957 //
7958 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7959 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007960 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007961 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007962 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007963 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007964 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007965 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007966 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7967 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007968
Fred Shih381e4ca2014-08-25 17:24:27 -07007969 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007970 size_t current_field = 0;
7971 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007972 FieldGaps gaps;
7973
Brian Carlstromdbc05252011-09-09 01:59:59 -07007974 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007975 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007976 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007977 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007978 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007979 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007980 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007981 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7982 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007983 MemberOffset old_offset = field_offset;
7984 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7985 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7986 }
Roland Levillain14d90572015-07-16 10:52:26 +01007987 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007988 grouped_and_sorted_fields.pop_front();
7989 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007990 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007991 field_offset = MemberOffset(field_offset.Uint32Value() +
7992 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007993 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007994 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7995 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007996 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7997 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7998 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7999 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008000 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8001 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008002 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008003
Elliott Hughesadb460d2011-10-05 17:02:34 -07008004 // 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 -07008005 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008006 // We know there are no non-reference fields in the Reference classes, and we know
8007 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008008 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008009 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008010 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008011 --num_reference_fields;
8012 }
8013
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008014 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008015 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008016 if (is_static) {
8017 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008018 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008019 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008020 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008021 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008022 if (num_reference_fields == 0 || super_class == nullptr) {
8023 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008024 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008025 if (super_class == nullptr ||
8026 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8027 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008028 }
8029 }
8030 if (kIsDebugBuild) {
8031 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8032 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008033 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008034 while (cur_super != nullptr) {
8035 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8036 cur_super = cur_super->GetSuperClass();
8037 }
8038 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008039 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008040 } else {
8041 // Check that there is at least num_reference_fields other than Object.class.
8042 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008043 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008044 }
8045 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008046 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008047 std::string temp;
8048 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8049 size_t previous_size = klass->GetObjectSize();
8050 if (previous_size != 0) {
8051 // Make sure that we didn't originally have an incorrect size.
8052 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008053 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008054 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008055 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008056 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008057
8058 if (kIsDebugBuild) {
8059 // Make sure that the fields array is ordered by name but all reference
8060 // offsets are at the beginning as far as alignment allows.
8061 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008062 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008063 : klass->GetFirstReferenceInstanceFieldOffset();
8064 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8065 num_reference_fields *
8066 sizeof(mirror::HeapReference<mirror::Object>));
8067 MemberOffset current_ref_offset = start_ref_offset;
8068 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008069 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008070 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008071 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8072 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008073 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008074 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008075 // NOTE: The field names can be the same. This is not possible in the Java language
8076 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008077 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008078 }
8079 Primitive::Type type = field->GetTypeAsPrimitiveType();
8080 bool is_primitive = type != Primitive::kPrimNot;
8081 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8082 strcmp("referent", field->GetName()) == 0) {
8083 is_primitive = true; // We lied above, so we have to expect a lie here.
8084 }
8085 MemberOffset offset = field->GetOffsetDuringLinking();
8086 if (is_primitive) {
8087 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8088 // Shuffled before references.
8089 size_t type_size = Primitive::ComponentSize(type);
8090 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8091 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8092 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8093 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8094 }
8095 } else {
8096 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8097 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8098 sizeof(mirror::HeapReference<mirror::Object>));
8099 }
8100 }
8101 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8102 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008103 return true;
8104}
8105
Vladimir Marko76649e82014-11-10 18:32:59 +00008106// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008107void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008108 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008109 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008110 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008111 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008112 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008113 // Compute reference offsets unless our superclass overflowed.
8114 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8115 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008116 if (num_reference_fields != 0u) {
8117 // All of the fields that contain object references are guaranteed be grouped in memory
8118 // starting at an appropriately aligned address after super class object data.
8119 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8120 sizeof(mirror::HeapReference<mirror::Object>));
8121 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008122 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008123 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008124 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008125 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008126 reference_offsets |= (0xffffffffu << start_bit) &
8127 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008128 }
8129 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008130 }
8131 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008132 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008133}
8134
Vladimir Marko18090d12018-06-01 16:53:12 +01008135ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8136 ObjPtr<mirror::DexCache> dex_cache) {
8137 StackHandleScope<1> hs(Thread::Current());
8138 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8139 return DoResolveString(string_idx, h_dex_cache);
8140}
8141
8142ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8143 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008144 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008145 uint32_t utf16_length;
8146 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008147 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008148 if (string != nullptr) {
8149 dex_cache->SetResolvedString(string_idx, string);
8150 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008151 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008152}
8153
Vladimir Marko18090d12018-06-01 16:53:12 +01008154ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8155 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008156 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008157 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008158 uint32_t utf16_length;
8159 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008160 ObjPtr<mirror::String> string =
8161 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008162 if (string != nullptr) {
8163 dex_cache->SetResolvedString(string_idx, string);
8164 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008165 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008166}
8167
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008168ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008169 ObjPtr<mirror::Class> referrer) {
8170 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8171}
8172
8173ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008174 ObjPtr<mirror::DexCache> dex_cache,
8175 ObjPtr<mirror::ClassLoader> class_loader) {
8176 const DexFile& dex_file = *dex_cache->GetDexFile();
8177 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8178 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8179 ObjPtr<mirror::Class> type = nullptr;
8180 if (descriptor[1] == '\0') {
8181 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8182 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008183 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008184 } else {
8185 Thread* const self = Thread::Current();
8186 DCHECK(self != nullptr);
8187 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8188 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008189 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008190 }
8191 if (type != nullptr) {
8192 if (type->IsResolved()) {
8193 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008194 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008195 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008196 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008197 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008198 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008199}
8200
Andreas Gampe4835d212018-11-21 14:55:10 -08008201template <typename T>
8202ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008203 StackHandleScope<2> hs(Thread::Current());
8204 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8205 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8206 return DoResolveType(type_idx, dex_cache, class_loader);
8207}
8208
Andreas Gampe4835d212018-11-21 14:55:10 -08008209// Instantiate the above.
8210template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8211 ArtField* referrer);
8212template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8213 ArtMethod* referrer);
8214template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8215 ObjPtr<mirror::Class> referrer);
8216
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008217ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008218 Handle<mirror::DexCache> dex_cache,
8219 Handle<mirror::ClassLoader> class_loader) {
8220 Thread* self = Thread::Current();
8221 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8222 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8223 if (resolved != nullptr) {
8224 // TODO: we used to throw here if resolved's class loader was not the
8225 // boot class loader. This was to permit different classes with the
8226 // same name to be loaded simultaneously by different loaders
8227 dex_cache->SetResolvedType(type_idx, resolved);
8228 } else {
8229 CHECK(self->IsExceptionPending())
8230 << "Expected pending exception for failed resolution of: " << descriptor;
8231 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8232 StackHandleScope<1> hs(self);
8233 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008234 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008235 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8236 self->ClearException();
8237 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8238 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008239 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008240 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008241 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008242 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008243 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008244}
8245
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008246ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8247 ObjPtr<mirror::DexCache> dex_cache,
8248 ObjPtr<mirror::ClassLoader> class_loader,
8249 uint32_t method_idx) {
8250 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8251 // functions can optimize the search if the dex_cache is the same as the DexCache
8252 // of the class, with fall-back to name and signature search otherwise.
8253 ArtMethod* resolved = nullptr;
8254 if (klass->IsInterface()) {
8255 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8256 } else {
8257 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8258 }
8259 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008260 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008261 hiddenapi::ShouldDenyAccessToMember(resolved,
8262 hiddenapi::AccessContext(class_loader, dex_cache),
8263 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008264 resolved = nullptr;
8265 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008266 if (resolved != nullptr) {
8267 // In case of jmvti, the dex file gets verified before being registered, so first
8268 // check if it's registered before checking class tables.
8269 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008270 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8271 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008272 << "DexFile referrer: " << dex_file.GetLocation()
8273 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8274 // Be a good citizen and update the dex cache to speed subsequent calls.
8275 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008276 // Disable the following invariant check as the verifier breaks it. b/73760543
8277 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8278 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8279 // << "Method: " << resolved->PrettyMethod() << ", "
8280 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8281 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008282 }
8283 return resolved;
8284}
8285
David Brazdil4525e0b2018-04-05 16:57:32 +01008286// Returns true if `method` is either null or hidden.
8287// Does not print any warnings if it is hidden.
8288static bool CheckNoSuchMethod(ArtMethod* method,
8289 ObjPtr<mirror::DexCache> dex_cache,
8290 ObjPtr<mirror::ClassLoader> class_loader)
8291 REQUIRES_SHARED(Locks::mutator_lock_) {
8292 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008293 hiddenapi::ShouldDenyAccessToMember(method,
8294 hiddenapi::AccessContext(class_loader, dex_cache),
8295 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008296}
8297
8298ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8299 ObjPtr<mirror::DexCache> dex_cache,
8300 ObjPtr<mirror::ClassLoader> class_loader,
8301 uint32_t method_idx) {
8302 if (klass->IsInterface()) {
8303 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8304 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8305 } else {
8306 // If there was an interface method with the same signature, we would have
8307 // found it in the "copied" methods. Only DCHECK that the interface method
8308 // really does not exist.
8309 if (kIsDebugBuild) {
8310 ArtMethod* method =
8311 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8312 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8313 }
8314 return nullptr;
8315 }
8316}
8317
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008318template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008319ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008320 Handle<mirror::DexCache> dex_cache,
8321 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008322 ArtMethod* referrer,
8323 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008324 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008325 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008326 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008327 PointerSize pointer_size = image_pointer_size_;
8328 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008329 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008330 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8331 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008332 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8333 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008334 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008335 return resolved;
8336 }
Vladimir Marko89011192017-12-11 13:45:05 +00008337 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008338 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008339 ObjPtr<mirror::Class> klass = nullptr;
8340 if (valid_dex_cache_method) {
8341 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8342 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008343 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008344 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008345 // We normaly should not end up here. However the verifier currently doesn't guarantee
8346 // the invariant of having the klass in the class table. b/73760543
8347 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008348 }
Vladimir Markoba118822017-06-12 15:41:56 +01008349 } else {
8350 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008351 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008352 if (klass == nullptr) {
8353 DCHECK(Thread::Current()->IsExceptionPending());
8354 return nullptr;
8355 }
8356 }
8357
8358 // Check if the invoke type matches the class type.
8359 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008360 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008361 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008362 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008363 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008364 }
Vladimir Markoba118822017-06-12 15:41:56 +01008365
8366 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008367 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008368 }
Vladimir Markoba118822017-06-12 15:41:56 +01008369
8370 // Note: We can check for IllegalAccessError only if we have a referrer.
8371 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8372 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8373 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8374 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8375 resolved,
8376 dex_cache.Get(),
8377 method_idx,
8378 type)) {
8379 DCHECK(Thread::Current()->IsExceptionPending());
8380 return nullptr;
8381 }
8382 }
8383
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008384 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008385 if (LIKELY(resolved != nullptr) &&
8386 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8387 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008388 return resolved;
8389 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008390 // If we had a method, or if we can find one with another lookup type,
8391 // it's an incompatible-class-change error.
8392 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008393 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008394 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008395 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008396 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008397 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008398 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008399 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8400 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008401 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008402 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008403 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008404 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008405 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008406}
8407
Vladimir Marko89011192017-12-11 13:45:05 +00008408ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008409 Handle<mirror::DexCache> dex_cache,
8410 Handle<mirror::ClassLoader> class_loader) {
8411 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008412 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008413 if (resolved != nullptr) {
8414 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008415 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8416 return resolved;
8417 }
8418 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008419 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008420 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008421 if (klass == nullptr) {
8422 Thread::Current()->AssertPendingException();
8423 return nullptr;
8424 }
8425 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008426 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8427 } else {
8428 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008429 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008430 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008431 hiddenapi::ShouldDenyAccessToMember(
8432 resolved,
8433 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8434 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008435 resolved = nullptr;
8436 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008437 return resolved;
8438}
8439
Vladimir Markof44d36c2017-03-14 14:18:46 +00008440ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8441 ObjPtr<mirror::DexCache> dex_cache,
8442 ObjPtr<mirror::ClassLoader> class_loader,
8443 bool is_static) {
8444 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008445 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008446 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8447 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008448 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008449 }
8450 if (klass == nullptr) {
8451 // The class has not been resolved yet, so the field is also unresolved.
8452 return nullptr;
8453 }
8454 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008455
David Brazdil1ab0fa82018-05-04 11:28:03 +01008456 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008457}
8458
Vladimir Markoe11dd502017-12-08 14:09:45 +00008459ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008460 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008461 Handle<mirror::ClassLoader> class_loader,
8462 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008463 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008464 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008465 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008466 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008467 return resolved;
8468 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008469 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008470 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008471 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008472 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008473 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008474 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008475 }
8476
David Brazdil1ab0fa82018-05-04 11:28:03 +01008477 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008478 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008479 const char* name = dex_file.GetFieldName(field_id);
8480 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008481 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008482 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008483 return resolved;
8484}
8485
Vladimir Markoe11dd502017-12-08 14:09:45 +00008486ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008487 Handle<mirror::DexCache> dex_cache,
8488 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008489 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008490 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008491 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008492 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008493 return resolved;
8494 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008495 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008496 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008497 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008498 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008499 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008500 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008501 }
8502
David Brazdil1ab0fa82018-05-04 11:28:03 +01008503 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8504 if (resolved == nullptr) {
8505 const char* name = dex_file.GetFieldName(field_id);
8506 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008507 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008508 }
8509 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008510}
8511
David Brazdil1ab0fa82018-05-04 11:28:03 +01008512ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8513 ObjPtr<mirror::DexCache> dex_cache,
8514 ObjPtr<mirror::ClassLoader> class_loader,
8515 uint32_t field_idx,
8516 bool is_static) {
8517 ArtField* resolved = nullptr;
8518 Thread* self = is_static ? Thread::Current() : nullptr;
8519 const DexFile& dex_file = *dex_cache->GetDexFile();
8520
8521 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8522 : klass->FindInstanceField(dex_cache, field_idx);
8523
8524 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008525 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008526 const char* name = dex_file.GetFieldName(field_id);
8527 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8528 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8529 : klass->FindInstanceField(name, type);
8530 }
8531
8532 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008533 hiddenapi::ShouldDenyAccessToMember(resolved,
8534 hiddenapi::AccessContext(class_loader, dex_cache),
8535 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008536 resolved = nullptr;
8537 }
8538
8539 if (resolved != nullptr) {
8540 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8541 }
8542
8543 return resolved;
8544}
8545
8546ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8547 ObjPtr<mirror::DexCache> dex_cache,
8548 ObjPtr<mirror::ClassLoader> class_loader,
8549 uint32_t field_idx) {
8550 ArtField* resolved = nullptr;
8551 Thread* self = Thread::Current();
8552 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008553 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008554
8555 const char* name = dex_file.GetFieldName(field_id);
8556 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8557 resolved = mirror::Class::FindField(self, klass, name, type);
8558
8559 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008560 hiddenapi::ShouldDenyAccessToMember(resolved,
8561 hiddenapi::AccessContext(class_loader, dex_cache),
8562 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008563 resolved = nullptr;
8564 }
8565
8566 if (resolved != nullptr) {
8567 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8568 }
8569
8570 return resolved;
8571}
8572
Vladimir Markoaf940202017-12-08 15:01:18 +00008573ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8574 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008575 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008576 Handle<mirror::DexCache> dex_cache,
8577 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008578 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008579 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008580
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008581 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008582 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008583 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008584 }
8585
Narayan Kamath25352fc2016-08-03 12:46:58 +01008586 StackHandleScope<4> hs(self);
8587
8588 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008589 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008590 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008591 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008592 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008593 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008594 DCHECK(self->IsExceptionPending());
8595 return nullptr;
8596 }
8597
8598 // Then resolve the argument types.
8599 //
8600 // TODO: Is there a better way to figure out the number of method arguments
8601 // other than by looking at the shorty ?
8602 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8603
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008604 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008605 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8606 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008607 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008608 DCHECK(self->IsExceptionPending());
8609 return nullptr;
8610 }
8611
8612 DexFileParameterIterator it(dex_file, proto_id);
8613 int32_t i = 0;
8614 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8615 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008616 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008617 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008618 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008619 DCHECK(self->IsExceptionPending());
8620 return nullptr;
8621 }
8622
8623 method_params->Set(i++, param_class.Get());
8624 }
8625
8626 DCHECK(!it.HasNext());
8627
8628 Handle<mirror::MethodType> type = hs.NewHandle(
8629 mirror::MethodType::Create(self, return_type, method_params));
8630 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8631
8632 return type.Get();
8633}
8634
Vladimir Markoaf940202017-12-08 15:01:18 +00008635ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008636 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008637 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008638 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008639 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8640 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008641 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008642}
8643
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008644mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8645 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008646 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008647 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008648 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008649 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8650 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008651 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008652 bool is_static;
8653 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008654 switch (handle_type) {
8655 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008656 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008657 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008658 is_static = true;
8659 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008660 break;
8661 }
8662 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008663 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008664 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008665 is_static = true;
8666 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008667 break;
8668 }
8669 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008670 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008671 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008672 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008673 num_params = 2;
8674 break;
8675 }
8676 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008677 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008678 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008679 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008680 num_params = 1;
8681 break;
8682 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008683 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008684 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008685 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008686 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008687 case DexFile::MethodHandleType::kInvokeInterface:
8688 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008689 }
8690
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008691 ArtField* target_field =
8692 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8693 if (LIKELY(target_field != nullptr)) {
8694 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8695 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8696 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8697 ThrowIllegalAccessErrorField(referring_class, target_field);
8698 return nullptr;
8699 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008700 if (UNLIKELY(is_put && target_field->IsFinal())) {
8701 ThrowIllegalAccessErrorField(referring_class, target_field);
8702 return nullptr;
8703 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008704 } else {
8705 DCHECK(Thread::Current()->IsExceptionPending());
8706 return nullptr;
8707 }
8708
8709 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008710 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008711 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8712 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008713 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008714 DCHECK(self->IsExceptionPending());
8715 return nullptr;
8716 }
8717
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008718 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008719 Handle<mirror::Class> return_type;
8720 switch (handle_type) {
8721 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008722 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008723 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008724 break;
8725 }
8726 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008727 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008728 break;
8729 }
8730 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008731 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008732 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008733 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008734 break;
8735 }
8736 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008737 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008738 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008739 break;
8740 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008741 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008742 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008743 case DexFile::MethodHandleType::kInvokeConstructor:
8744 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008745 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008746 UNREACHABLE();
8747 }
8748
8749 for (int32_t i = 0; i < num_params; ++i) {
8750 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8751 DCHECK(self->IsExceptionPending());
8752 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008753 }
8754 }
8755
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008756 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008757 DCHECK(self->IsExceptionPending());
8758 return nullptr;
8759 }
8760
8761 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008762 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8763 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008764 DCHECK(self->IsExceptionPending());
8765 return nullptr;
8766 }
Orion Hodson631827d2017-04-10 14:53:47 +01008767
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008768 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8769 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8770}
8771
8772mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8773 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008774 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008775 ArtMethod* referrer) {
8776 DexFile::MethodHandleType handle_type =
8777 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8778 mirror::MethodHandle::Kind kind;
8779 uint32_t receiver_count = 0;
8780 ArtMethod* target_method = nullptr;
8781 switch (handle_type) {
8782 case DexFile::MethodHandleType::kStaticPut:
8783 case DexFile::MethodHandleType::kStaticGet:
8784 case DexFile::MethodHandleType::kInstancePut:
8785 case DexFile::MethodHandleType::kInstanceGet:
8786 UNREACHABLE();
8787 case DexFile::MethodHandleType::kInvokeStatic: {
8788 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8789 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008790 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8791 method_handle.field_or_method_idx_,
8792 referrer,
8793 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008794 break;
8795 }
8796 case DexFile::MethodHandleType::kInvokeInstance: {
8797 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8798 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008799 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8800 method_handle.field_or_method_idx_,
8801 referrer,
8802 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008803 break;
8804 }
8805 case DexFile::MethodHandleType::kInvokeConstructor: {
8806 // Constructors are currently implemented as a transform. They
8807 // are special cased later in this method.
8808 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8809 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008810 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8811 method_handle.field_or_method_idx_,
8812 referrer,
8813 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008814 break;
8815 }
8816 case DexFile::MethodHandleType::kInvokeDirect: {
8817 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8818 receiver_count = 1;
8819 StackHandleScope<2> hs(self);
8820 // A constant method handle with type kInvokeDirect can refer to
8821 // a method that is private or to a method in a super class. To
8822 // disambiguate the two options, we resolve the method ignoring
8823 // the invocation type to determine if the method is private. We
8824 // then resolve again specifying the intended invocation type to
8825 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008826 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008827 hs.NewHandle(referrer->GetDexCache()),
8828 hs.NewHandle(referrer->GetClassLoader()));
8829 if (UNLIKELY(target_method == nullptr)) {
8830 break;
8831 }
8832
8833 if (target_method->IsPrivate()) {
8834 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008835 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8836 method_handle.field_or_method_idx_,
8837 referrer,
8838 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008839 } else {
8840 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008841 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8842 method_handle.field_or_method_idx_,
8843 referrer,
8844 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008845 if (UNLIKELY(target_method == nullptr)) {
8846 break;
8847 }
8848 // Find the method specified in the parent in referring class
8849 // so invoke-super invokes the method in the parent of the
8850 // referrer.
8851 target_method =
8852 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8853 kRuntimePointerSize);
8854 }
8855 break;
8856 }
8857 case DexFile::MethodHandleType::kInvokeInterface: {
8858 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8859 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008860 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8861 method_handle.field_or_method_idx_,
8862 referrer,
8863 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008864 break;
8865 }
Orion Hodson631827d2017-04-10 14:53:47 +01008866 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008867
8868 if (UNLIKELY(target_method == nullptr)) {
8869 DCHECK(Thread::Current()->IsExceptionPending());
8870 return nullptr;
8871 }
8872
8873 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8874 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8875 uint32_t access_flags = target_method->GetAccessFlags();
8876 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8877 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8878 return nullptr;
8879 }
8880
8881 // Calculate the number of parameters from the method shorty. We add the
8882 // receiver count (0 or 1) and deduct one for the return value.
8883 uint32_t shorty_length;
8884 target_method->GetShorty(&shorty_length);
8885 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8886
Orion Hodsonecd58562018-09-24 11:27:33 +01008887 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008888 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008889 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8890 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8891 if (method_params.Get() == nullptr) {
8892 DCHECK(self->IsExceptionPending());
8893 return nullptr;
8894 }
8895
Orion Hodsonecd58562018-09-24 11:27:33 +01008896 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008897 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008898 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008899 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01008900 // Insert receiver. Use the class identified in the method handle rather than the declaring
8901 // class of the resolved method which may be super class or default interface method
8902 // (b/115964401).
8903 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
8904 // receiver_class should have been resolved when resolving the target method.
8905 DCHECK(receiver_class != nullptr);
8906 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008907 }
Orion Hodsonecd58562018-09-24 11:27:33 +01008908
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008909 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01008910 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008911 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008912 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008913 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01008914 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008915 if (nullptr == klass) {
8916 DCHECK(self->IsExceptionPending());
8917 return nullptr;
8918 }
8919 method_params->Set(index++, klass);
8920 it.Next();
8921 }
8922
Orion Hodsonecd58562018-09-24 11:27:33 +01008923 Handle<mirror::Class> return_type =
8924 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008925 if (UNLIKELY(return_type.IsNull())) {
8926 DCHECK(self->IsExceptionPending());
8927 return nullptr;
8928 }
8929
8930 Handle<mirror::MethodType>
8931 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8932 if (UNLIKELY(method_type.IsNull())) {
8933 DCHECK(self->IsExceptionPending());
8934 return nullptr;
8935 }
8936
8937 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8938 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8939 Handle<mirror::MethodHandlesLookup> lookup =
8940 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8941 return lookup->FindConstructor(self, constructor_class, method_type);
8942 }
8943
8944 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8945 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8946}
8947
Vladimir Markoaf940202017-12-08 15:01:18 +00008948ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8949 uint32_t method_handle_idx,
8950 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008951 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008952 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008953 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008954 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8955 case DexFile::MethodHandleType::kStaticPut:
8956 case DexFile::MethodHandleType::kStaticGet:
8957 case DexFile::MethodHandleType::kInstancePut:
8958 case DexFile::MethodHandleType::kInstanceGet:
8959 return ResolveMethodHandleForField(self, method_handle, referrer);
8960 case DexFile::MethodHandleType::kInvokeStatic:
8961 case DexFile::MethodHandleType::kInvokeInstance:
8962 case DexFile::MethodHandleType::kInvokeConstructor:
8963 case DexFile::MethodHandleType::kInvokeDirect:
8964 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008965 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008966 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008967}
8968
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008969bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8970 return (entry_point == GetQuickResolutionStub()) ||
8971 (quick_resolution_trampoline_ == entry_point);
8972}
8973
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008974bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8975 return (entry_point == GetQuickToInterpreterBridge()) ||
8976 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8977}
8978
8979bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8980 return (entry_point == GetQuickGenericJniStub()) ||
8981 (quick_generic_jni_trampoline_ == entry_point);
8982}
8983
David Sehra49e0532017-08-25 08:05:29 -07008984bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8985 return entry_point == GetJniDlsymLookupStub();
8986}
8987
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008988const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8989 return GetQuickGenericJniStub();
8990}
8991
Mathieu Chartiere401d142015-04-22 13:56:20 -07008992void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008993 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008994 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8995 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008996 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008997 }
8998}
8999
Alex Lightdb01a092017-04-03 15:39:55 -07009000void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9001 DCHECK(method->IsObsolete());
9002 // We cannot mess with the entrypoints of native methods because they are used to determine how
9003 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9004 if (!method->IsNative()) {
9005 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9006 }
9007}
9008
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009009void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009010 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009011 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009012 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9013 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009014 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9015 os << "Dumping registered class loaders\n";
9016 size_t class_loader_index = 0;
9017 for (const ClassLoaderData& class_loader : class_loaders_) {
9018 ObjPtr<mirror::ClassLoader> loader =
9019 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9020 if (loader != nullptr) {
9021 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9022 bool saw_one_dex_file = false;
9023 for (const DexCacheData& dex_cache : dex_caches_) {
9024 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9025 if (saw_one_dex_file) {
9026 os << ":";
9027 }
9028 saw_one_dex_file = true;
9029 os << dex_cache.dex_file->GetLocation();
9030 }
9031 }
9032 os << "]";
9033 bool found_parent = false;
9034 if (loader->GetParent() != nullptr) {
9035 size_t parent_index = 0;
9036 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9037 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9038 soa.Self()->DecodeJObject(class_loader2.weak_root));
9039 if (loader2 == loader->GetParent()) {
9040 os << ", parent #" << parent_index;
9041 found_parent = true;
9042 break;
9043 }
9044 parent_index++;
9045 }
9046 if (!found_parent) {
9047 os << ", unregistered parent of type "
9048 << loader->GetParent()->GetClass()->PrettyDescriptor();
9049 }
9050 } else {
9051 os << ", no parent";
9052 }
9053 os << "\n";
9054 }
9055 }
9056 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009057}
9058
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009059class CountClassesVisitor : public ClassLoaderVisitor {
9060 public:
9061 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9062
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009063 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009064 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009065 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009066 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009067 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9068 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009069 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009070 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009071
9072 size_t num_zygote_classes;
9073 size_t num_non_zygote_classes;
9074};
9075
9076size_t ClassLinker::NumZygoteClasses() const {
9077 CountClassesVisitor visitor;
9078 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009079 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009080}
9081
9082size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009083 CountClassesVisitor visitor;
9084 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009085 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009086}
9087
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009088size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009089 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009090 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009091 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009092}
9093
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009094pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009095 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009096}
9097
9098pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009099 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009100}
9101
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009102void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009103 DCHECK(!init_done_);
9104
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009105 DCHECK(klass != nullptr);
9106 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009107
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009108 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009109 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009110 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9111 int32_t index = static_cast<int32_t>(class_root);
9112 DCHECK(class_roots->Get(index) == nullptr);
9113 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009114}
9115
Roland Levillain0e840272018-08-23 19:55:30 +01009116void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9117 ObjPtr<mirror::Class> java_lang_Class,
9118 ClassRoot primitive_array_class_root,
9119 ClassRoot primitive_class_root,
9120 const char* descriptor) {
9121 StackHandleScope<1> hs(self);
9122 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9123 AllocPrimitiveArrayClass(self, java_lang_Class)));
9124 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9125 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9126 CheckSystemClass(self, primitive_array_class, descriptor);
9127}
9128
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009129ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9130 Thread* self,
9131 const std::vector<const DexFile*>& dex_files,
9132 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009133 Handle<mirror::ClassLoader> parent_loader,
9134 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009135
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009136 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009137
Mathieu Chartierc7853442015-03-27 14:35:38 -07009138 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009139 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009140
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009141 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009142 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009143 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009144 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009145 mirror::ObjectArray<mirror::Object>::Alloc(self,
9146 dex_elements_class.Get(),
9147 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009148 Handle<mirror::Class> h_dex_element_class =
9149 hs.NewHandle(dex_elements_class->GetComponentType());
9150
Mathieu Chartierc7853442015-03-27 14:35:38 -07009151 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009152 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009153 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009154
Andreas Gampe08883de2016-11-08 13:20:52 -08009155 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009156 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009157
Andreas Gampe08883de2016-11-08 13:20:52 -08009158 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009159 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009160
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009161 // Fill the elements array.
9162 int32_t index = 0;
9163 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009164 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009165
Calin Juravle7865ac72017-06-28 11:03:12 -07009166 // CreateWellKnownClassLoader is only used by gtests and compiler.
9167 // 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 -07009168 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9169 self,
9170 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009171 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009172 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009173
Mathieu Chartier3738e982017-05-12 16:07:28 -07009174 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9175 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009176 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009177 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009178 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009179 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009180
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009181 Handle<mirror::String> h_file_name = hs2.NewHandle(
9182 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009183 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009184 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9185
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009186 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009187 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009188 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009189
9190 h_dex_elements->Set(index, h_element.Get());
9191 index++;
9192 }
9193 DCHECK_EQ(index, h_dex_elements->GetLength());
9194
9195 // Create DexPathList.
9196 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009197 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009198 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009199 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009200 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009201 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9202 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9203 // elements.
9204 {
9205 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9206 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9207 DCHECK(native_lib_dirs != nullptr);
9208 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9209 DCHECK(list_class != nullptr);
9210 {
9211 StackHandleScope<1> h_list_scope(self);
9212 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9213 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9214 DCHECK(list_init);
9215 list_class = h_list_class.Get();
9216 }
9217 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9218 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9219 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9220 // normally never null), as long as one does not try to add elements, this will still
9221 // work.
9222 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9223 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009224
Calin Juravle7865ac72017-06-28 11:03:12 -07009225 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009226 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9227 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009228 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009229 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009230 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009231 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009232 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009233 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009234
9235 // Make a pretend boot-classpath.
9236 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009237 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009238 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009239 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009240 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009241 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009242 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009243 if (parent_loader.Get() == nullptr) {
9244 ScopedObjectAccessUnchecked soa(self);
9245 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9246 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9247 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9248 } else {
9249 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9250 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009251
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009252 ArtField* shared_libraries_field =
9253 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9254 DCHECK(shared_libraries_field != nullptr);
9255 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9256
9257 return h_class_loader.Get();
9258}
9259
9260jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9261 const std::vector<const DexFile*>& dex_files,
9262 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009263 jobject parent_loader,
9264 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009265 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9266 WellKnownClasses::dalvik_system_PathClassLoader) ||
9267 self->GetJniEnv()->IsSameObject(loader_class,
9268 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
9269
9270 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9271 // We could move the jobject to the callers, but all call-sites do this...
9272 ScopedObjectAccessUnchecked soa(self);
9273
9274 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009275 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009276
9277 Handle<mirror::Class> h_loader_class =
9278 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009279 Handle<mirror::ClassLoader> h_parent =
9280 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9281 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9282 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009283
9284 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9285 self,
9286 dex_files,
9287 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009288 h_parent,
9289 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009290
9291 // Make it a global ref and return.
9292 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009293 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009294 return soa.Env()->NewGlobalRef(local_ref.get());
9295}
9296
Calin Juravle7865ac72017-06-28 11:03:12 -07009297jobject ClassLinker::CreatePathClassLoader(Thread* self,
9298 const std::vector<const DexFile*>& dex_files) {
9299 return CreateWellKnownClassLoader(self,
9300 dex_files,
9301 WellKnownClasses::dalvik_system_PathClassLoader,
9302 nullptr);
9303}
9304
Andreas Gampe8ac75952015-06-02 21:01:45 -07009305void ClassLinker::DropFindArrayClassCache() {
9306 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9307 find_array_class_cache_next_victim_ = 0;
9308}
9309
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009310void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009311 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009312 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009313 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009314 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9315 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009316 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009317 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009318 }
9319 }
9320}
9321
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009322void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9323 for (const ClassLoaderData& data : class_loaders_) {
9324 LinearAlloc* alloc = data.allocator;
9325 if (alloc != nullptr && !visitor->Visit(alloc)) {
9326 break;
9327 }
9328 }
9329}
9330
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009331void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9332 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009333 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009334 Thread* const self = Thread::Current();
9335 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009336 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009337 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009338 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009339 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9340 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009341 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009342 }
9343}
9344
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009345void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009346 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009347 std::vector<ClassLoaderData> to_delete;
9348 // Do the delete outside the lock to avoid lock violation in jit code cache.
9349 {
9350 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9351 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9352 const ClassLoaderData& data = *it;
9353 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009354 ObjPtr<mirror::ClassLoader> class_loader =
9355 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009356 if (class_loader != nullptr) {
9357 ++it;
9358 } else {
9359 VLOG(class_linker) << "Freeing class loader";
9360 to_delete.push_back(data);
9361 it = class_loaders_.erase(it);
9362 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009363 }
9364 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009365 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009366 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009367 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009368 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009369}
9370
Vladimir Marko21300532017-01-24 18:06:55 +00009371class GetResolvedClassesVisitor : public ClassVisitor {
9372 public:
9373 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9374 : result_(result),
9375 ignore_boot_classes_(ignore_boot_classes),
9376 last_resolved_classes_(result->end()),
9377 last_dex_file_(nullptr),
9378 vlog_is_on_(VLOG_IS_ON(class_linker)),
9379 extra_stats_(),
9380 last_extra_stats_(extra_stats_.end()) { }
9381
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009382 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009383 if (!klass->IsProxyClass() &&
9384 !klass->IsArrayClass() &&
9385 klass->IsResolved() &&
9386 !klass->IsErroneousResolved() &&
9387 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9388 const DexFile& dex_file = klass->GetDexFile();
9389 if (&dex_file != last_dex_file_) {
9390 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009391 DexCacheResolvedClasses resolved_classes(
9392 dex_file.GetLocation(),
9393 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9394 dex_file.GetLocationChecksum(),
9395 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009396 last_resolved_classes_ = result_->find(resolved_classes);
9397 if (last_resolved_classes_ == result_->end()) {
9398 last_resolved_classes_ = result_->insert(resolved_classes).first;
9399 }
9400 }
9401 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9402 if (UNLIKELY(vlog_is_on_) && added) {
9403 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9404 if (last_extra_stats_ == extra_stats_.end() ||
9405 last_extra_stats_->first != resolved_classes) {
9406 last_extra_stats_ = extra_stats_.find(resolved_classes);
9407 if (last_extra_stats_ == extra_stats_.end()) {
9408 last_extra_stats_ =
9409 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9410 }
9411 }
9412 }
9413 }
9414 return true;
9415 }
9416
9417 void PrintStatistics() const {
9418 if (vlog_is_on_) {
9419 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9420 auto it = extra_stats_.find(std::addressof(resolved_classes));
9421 DCHECK(it != extra_stats_.end());
9422 const ExtraStats& extra_stats = it->second;
9423 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9424 << " has " << resolved_classes.GetClasses().size() << " / "
9425 << extra_stats.number_of_class_defs_ << " resolved classes";
9426 }
9427 }
9428 }
9429
9430 private:
9431 struct ExtraStats {
9432 explicit ExtraStats(uint32_t number_of_class_defs)
9433 : number_of_class_defs_(number_of_class_defs) {}
9434 uint32_t number_of_class_defs_;
9435 };
9436
9437 std::set<DexCacheResolvedClasses>* result_;
9438 bool ignore_boot_classes_;
9439 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9440 const DexFile* last_dex_file_;
9441
9442 // Statistics.
9443 bool vlog_is_on_;
9444 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9445 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9446};
9447
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009448std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009449 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009450 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009451 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009452 std::set<DexCacheResolvedClasses> ret;
9453 VLOG(class_linker) << "Collecting resolved classes";
9454 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009455 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9456 VisitClasses(&visitor);
9457 if (VLOG_IS_ON(class_linker)) {
9458 visitor.PrintStatistics();
9459 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009460 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009461 return ret;
9462}
9463
Mathieu Chartier65975772016-08-05 10:46:36 -07009464class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9465 public:
9466 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9467 : method_(method),
9468 pointer_size_(pointer_size) {}
9469
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009470 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009471 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9472 holder_ = klass;
9473 }
9474 // Return false to stop searching if holder_ is not null.
9475 return holder_ == nullptr;
9476 }
9477
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009478 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009479 const ArtMethod* const method_;
9480 const PointerSize pointer_size_;
9481};
9482
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009483ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009484 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9485 CHECK(method->IsCopied());
9486 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9487 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009488 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009489}
9490
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009491ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9492 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009493 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009494 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009495 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009496}
9497
Roland Levillain0e840272018-08-23 19:55:30 +01009498// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009499template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009500 uint32_t method_idx,
9501 Handle<mirror::DexCache> dex_cache,
9502 Handle<mirror::ClassLoader> class_loader,
9503 ArtMethod* referrer,
9504 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009505template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009506 uint32_t method_idx,
9507 Handle<mirror::DexCache> dex_cache,
9508 Handle<mirror::ClassLoader> class_loader,
9509 ArtMethod* referrer,
9510 InvokeType type);
9511
Roland Levillain0e840272018-08-23 19:55:30 +01009512// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009513template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009514 Thread* self,
9515 ObjPtr<mirror::Class> java_lang_Class,
9516 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009517template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009518 Thread* self,
9519 ObjPtr<mirror::Class> java_lang_Class,
9520 uint32_t class_size);
9521
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009522} // namespace art