blob: 3b92e2c6581cf7fb23d8fa53cb6ce23755a6785f [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 Gampec55bb392018-09-21 00:02:02 +00002631using ClassPathEntry = std::pair<const DexFile*, const DexFile::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) {
David Sehr9aa352e2016-09-15 18:13:52 -07002637 const DexFile::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_) {
2787 const DexFile::ClassDef* dex_class_def =
2788 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2789 if (dex_class_def != nullptr) {
2790 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2791 descriptor,
2792 hash,
2793 class_loader,
2794 *cp_dex_file,
2795 *dex_class_def);
2796 if (klass == nullptr) {
2797 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2798 soa.Self()->ClearException();
2799 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002800 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002801 ret = klass;
2802 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002803 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002804 return true; // Continue with the next DexFile.
2805 };
2806
2807 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2808 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002809}
2810
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002811ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2812 const char* descriptor,
2813 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002814 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002815 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002816 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002817 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002818 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002819 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2820 // for primitive classes that aren't backed by dex files.
2821 return FindPrimitiveClass(descriptor[0]);
2822 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002823 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002824 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002825 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002826 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002827 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002828 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002829 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002830 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002831 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002832 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002833 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002834 return DefineClass(self,
2835 descriptor,
2836 hash,
2837 ScopedNullHandle<mirror::ClassLoader>(),
2838 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002839 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002840 } else {
2841 // The boot class loader is searched ahead of the application class loader, failures are
2842 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2843 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002844 ObjPtr<mirror::Throwable> pre_allocated =
2845 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002846 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002847 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002848 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002849 }
2850 ObjPtr<mirror::Class> result_ptr;
2851 bool descriptor_equals;
2852 if (descriptor[0] == '[') {
2853 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2854 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2855 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2856 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002857 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002858 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002859 bool known_hierarchy =
2860 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2861 if (result_ptr != nullptr) {
2862 // The chain was understood and we found the class. We still need to add the class to
2863 // the class table to protect from racy programs that can try and redefine the path list
2864 // which would change the Class<?> returned for subsequent evaluation of const-class.
2865 DCHECK(known_hierarchy);
2866 DCHECK(result_ptr->DescriptorEquals(descriptor));
2867 descriptor_equals = true;
2868 } else {
2869 // Either the chain wasn't understood or the class wasn't found.
2870 //
2871 // If the chain was understood but we did not find the class, let the Java-side
2872 // rediscover all this and throw the exception with the right stack trace. Note that
2873 // the Java-side could still succeed for racy programs if another thread is actively
2874 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002875
Alex Light185a4612018-10-04 15:54:25 -07002876 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002877 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002878 // Oops, we can't call into java so we can't run actual class-loader code.
2879 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002880 ObjPtr<mirror::Throwable> pre_allocated =
2881 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2882 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002883 return nullptr;
2884 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002885
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002886 // Inlined DescriptorToDot(descriptor) with extra validation.
2887 //
2888 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2889 // the DescriptorEquals() check below and give a confusing error message. For example,
2890 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2891 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2892 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2893 size_t descriptor_length = strlen(descriptor);
2894 if (UNLIKELY(descriptor[0] != 'L') ||
2895 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2896 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2897 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2898 return nullptr;
2899 }
2900 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2901 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2902
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002903 ScopedLocalRef<jobject> class_loader_object(
2904 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002905 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2906 {
2907 ScopedThreadStateChange tsc(self, kNative);
2908 ScopedLocalRef<jobject> class_name_object(
2909 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2910 if (class_name_object.get() == nullptr) {
2911 DCHECK(self->IsExceptionPending()); // OOME.
2912 return nullptr;
2913 }
2914 CHECK(class_loader_object.get() != nullptr);
2915 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2916 WellKnownClasses::java_lang_ClassLoader_loadClass,
2917 class_name_object.get()));
2918 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002919 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002920 // broken loader - throw NPE to be compatible with Dalvik
2921 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2922 class_name_string.c_str()).c_str());
2923 return nullptr;
2924 }
2925 result_ptr = soa.Decode<mirror::Class>(result.get());
2926 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002927 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002928 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002929 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002930
2931 if (self->IsExceptionPending()) {
2932 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2933 // However, to comply with the RI behavior, first check if another thread succeeded.
2934 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2935 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2936 self->ClearException();
2937 return EnsureResolved(self, descriptor, result_ptr);
2938 }
2939 return nullptr;
2940 }
2941
2942 // Try to insert the class to the class table, checking for mismatch.
2943 ObjPtr<mirror::Class> old;
2944 {
2945 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2946 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2947 old = class_table->Lookup(descriptor, hash);
2948 if (old == nullptr) {
2949 old = result_ptr; // For the comparison below, after releasing the lock.
2950 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002951 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002952 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002953 } // else throw below, after releasing the lock.
2954 }
2955 }
2956 if (UNLIKELY(old != result_ptr)) {
2957 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2958 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2959 mirror::Class* loader_class = class_loader->GetClass();
2960 const char* loader_class_name =
2961 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2962 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2963 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2964 << DescriptorToDot(descriptor) << "\").";
2965 return EnsureResolved(self, descriptor, old);
2966 }
2967 if (UNLIKELY(!descriptor_equals)) {
2968 std::string result_storage;
2969 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2970 std::string loader_storage;
2971 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2972 ThrowNoClassDefFoundError(
2973 "Initiating class loader of type %s returned class %s instead of %s.",
2974 DescriptorToDot(loader_class_name).c_str(),
2975 DescriptorToDot(result_name).c_str(),
2976 DescriptorToDot(descriptor).c_str());
2977 return nullptr;
2978 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002979 // Success.
2980 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002981}
2982
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002983ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
2984 const char* descriptor,
2985 size_t hash,
2986 Handle<mirror::ClassLoader> class_loader,
2987 const DexFile& dex_file,
2988 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002989 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002990 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002991
Brian Carlstromaded5f72011-10-07 17:15:04 -07002992 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002993 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002994 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002995 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002996 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002997 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002998 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002999 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003000 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003001 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003002 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003003 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003004 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003005 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003006 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003007 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003008 }
3009
Alex Lighte9f61032018-09-24 16:04:51 -07003010 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3011 // code to be executed. We put it up here so we can avoid all the allocations associated with
3012 // creating the class. This can happen with (eg) jit threads.
3013 if (!self->CanLoadClasses()) {
3014 // Make sure we don't try to load anything, potentially causing an infinite loop.
3015 ObjPtr<mirror::Throwable> pre_allocated =
3016 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3017 self->SetException(pre_allocated);
3018 return nullptr;
3019 }
3020
Andreas Gampefa4333d2017-02-14 11:10:34 -08003021 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003022 // Allocate a class with the status of not ready.
3023 // Interface object should get the right size here. Regular class will
3024 // figure out the right size later and be replaced with one of the right
3025 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003026 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003027 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003028 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003029 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003030 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003031 }
Alex Lightb0f11922017-01-23 14:25:17 -08003032 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3033 // nothing.
3034 DexFile const* new_dex_file = nullptr;
3035 DexFile::ClassDef const* new_class_def = nullptr;
3036 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3037 // will only be called once.
3038 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3039 klass,
3040 class_loader,
3041 dex_file,
3042 dex_class_def,
3043 &new_dex_file,
3044 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003045 // Check to see if an exception happened during runtime callbacks. Return if so.
3046 if (self->IsExceptionPending()) {
3047 return nullptr;
3048 }
Alex Lightb0f11922017-01-23 14:25:17 -08003049 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003050 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003051 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003052 return nullptr;
3053 }
3054 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003055 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003056
Jeff Hao848f70a2014-01-15 13:49:50 -08003057 // Mark the string class by setting its access flag.
3058 if (UNLIKELY(!init_done_)) {
3059 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3060 klass->SetStringClass();
3061 }
3062 }
3063
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003064 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003065 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003066 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003067 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003068
Mathieu Chartier590fee92013-09-13 13:46:47 -07003069 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003070 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003071 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003072 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3073 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003074 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003075 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003076
Mathieu Chartierc7853442015-03-27 14:35:38 -07003077 // Load the fields and other things after we are inserted in the table. This is so that we don't
3078 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3079 // other reason is that the field roots are only visited from the class table. So we need to be
3080 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003081 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003082 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003083 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003084 // An exception occured during load, set status to erroneous while holding klass' lock in case
3085 // notification is necessary.
3086 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003087 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003088 }
3089 return nullptr;
3090 }
3091
Brian Carlstromaded5f72011-10-07 17:15:04 -07003092 // Finish loading (if necessary) by finding parents
3093 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003094 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003095 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003096 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003097 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003098 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003099 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003100 }
3101 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003102
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003103 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003104 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003105 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003106
Brian Carlstromaded5f72011-10-07 17:15:04 -07003107 // Link the class (if necessary)
3108 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003109 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003110 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003111
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003112 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003113 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003114 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003115 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003116 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003117 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003118 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003119 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003120 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003121 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003122 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003123
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003124 // Instrumentation may have updated entrypoints for all methods of all
3125 // classes. However it could not update methods of this class while we
3126 // were loading it. Now the class is resolved, we can update entrypoints
3127 // as required by instrumentation.
3128 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3129 // We must be in the kRunnable state to prevent instrumentation from
3130 // suspending all threads to update entrypoints while we are doing it
3131 // for this class.
3132 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003133 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003134 }
3135
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003136 /*
3137 * We send CLASS_PREPARE events to the debugger from here. The
3138 * definition of "preparation" is creating the static fields for a
3139 * class and initializing them to the standard default values, but not
3140 * executing any code (that comes later, during "initialization").
3141 *
3142 * We did the static preparation in LinkClass.
3143 *
3144 * The class has been prepared and resolved but possibly not yet verified
3145 * at this point.
3146 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003147 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003148
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003149 // Notify native debugger of the new class and its layout.
3150 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3151
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003152 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003153}
3154
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003155uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
3156 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003157 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003158 size_t num_8 = 0;
3159 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003160 size_t num_32 = 0;
3161 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003162 ClassAccessor accessor(dex_file, dex_class_def);
3163 // We allow duplicate definitions of the same field in a class_data_item
3164 // but ignore the repeated indexes here, b/21868015.
3165 uint32_t last_field_idx = dex::kDexNoIndex;
3166 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3167 uint32_t field_idx = field.GetIndex();
3168 // Ordering enforced by DexFileVerifier.
3169 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3170 if (UNLIKELY(field_idx == last_field_idx)) {
3171 continue;
3172 }
3173 last_field_idx = field_idx;
3174 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3175 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3176 char c = descriptor[0];
3177 switch (c) {
3178 case 'L':
3179 case '[':
3180 num_ref++;
3181 break;
3182 case 'J':
3183 case 'D':
3184 num_64++;
3185 break;
3186 case 'I':
3187 case 'F':
3188 num_32++;
3189 break;
3190 case 'S':
3191 case 'C':
3192 num_16++;
3193 break;
3194 case 'B':
3195 case 'Z':
3196 num_8++;
3197 break;
3198 default:
3199 LOG(FATAL) << "Unknown descriptor: " << c;
3200 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003201 }
3202 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003203 return mirror::Class::ComputeClassSize(false,
3204 0,
3205 num_8,
3206 num_16,
3207 num_32,
3208 num_64,
3209 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003210 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003211}
3212
Alex Lightfc49fec2018-01-16 22:28:36 +00003213// Special case to get oat code without overwriting a trampoline.
3214const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003215 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003216 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003217 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003218 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003219 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3220 if (code != nullptr) {
3221 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003222 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003223 if (method->IsNative()) {
3224 // No code and native? Use generic trampoline.
3225 return GetQuickGenericJniStub();
3226 }
3227 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003228}
3229
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003230bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003231 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003232 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3233 return false;
3234 }
3235
Elliott Hughes956af0f2014-12-11 14:34:28 -08003236 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003237 return true;
3238 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003239
3240 Runtime* runtime = Runtime::Current();
3241 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3242 if (instr->InterpretOnly()) {
3243 return true;
3244 }
3245
3246 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3247 // Doing this check avoids doing compiled/interpreter transitions.
3248 return true;
3249 }
3250
3251 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
3252 // Force the use of interpreter when it is required by the debugger.
3253 return true;
3254 }
3255
Alex Light8f34aba2017-10-09 13:46:32 -07003256 if (Thread::Current()->IsAsyncExceptionPending()) {
3257 // Force use of interpreter to handle async-exceptions
3258 return true;
3259 }
3260
Alex Light2d441b12018-06-08 15:33:21 -07003261 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3262 const void* instr_target = instr->GetCodeForInvoke(method);
3263 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3264 return ShouldUseInterpreterEntrypoint(method, instr_target);
3265 }
3266
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003267 if (runtime->IsJavaDebuggable()) {
3268 // For simplicity, we ignore precompiled code and go to the interpreter
3269 // assuming we don't already have jitted code.
3270 // We could look at the oat file where `quick_code` is being defined,
3271 // and check whether it's been compiled debuggable, but we decided to
3272 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003273 jit::Jit* jit = Runtime::Current()->GetJit();
3274 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3275 }
3276
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003277 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003278 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003279 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003280 // since we want to JIT it (at first use) with extra stackmaps for native
3281 // debugging. We keep however all AOT code from the boot image,
3282 // since the JIT-at-first-use is blocking and would result in non-negligible
3283 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003284 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003285 }
3286
3287 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003288}
3289
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003290void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003291 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003292 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003293 if (klass->NumDirectMethods() == 0) {
3294 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003295 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003296 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003297 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003298 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003299 return; // OAT file unavailable.
3300 }
Ian Rogers19846512012-02-24 11:42:47 -08003301 }
Alex Light64ad14d2014-08-19 14:23:13 -07003302
Mathieu Chartierf8322842014-05-16 10:59:25 -07003303 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003304 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3305 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3306 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003307 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003308 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003309 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003310 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3311 klass->GetDexClassDefIndex(),
3312 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003313 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003314 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003315 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003316 if (!method->IsStatic()) {
3317 // Only update static methods.
3318 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003319 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003320 const void* quick_code = nullptr;
3321 if (has_oat_class) {
3322 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003323 quick_code = oat_method.GetQuickCode();
3324 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003325 // Check whether the method is native, in which case it's generic JNI.
3326 if (quick_code == nullptr && method->IsNative()) {
3327 quick_code = GetQuickGenericJniStub();
3328 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003329 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003330 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003331 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003332 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003333 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003334 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003335}
3336
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003337// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3338// method. Should only be called on non-invokable methods.
3339inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003340 DCHECK(method != nullptr);
3341 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003342 method->SetEntryPointFromQuickCompiledCodePtrSize(
3343 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3344 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003345}
3346
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003347static void LinkCode(ClassLinker* class_linker,
3348 ArtMethod* method,
3349 const OatFile::OatClass* oat_class,
3350 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003351 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003352 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003353 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003354 // The following code only applies to a non-compiler runtime.
3355 return;
3356 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003357 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003358 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003359 if (oat_class != nullptr) {
3360 // Every kind of method should at least get an invoke stub from the oat_method.
3361 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003362 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003363 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003364 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003365
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003366 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003367 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003368 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003369
Alex Light9139e002015-10-09 15:59:48 -07003370 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003371 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003372 return;
3373 }
Ian Rogers19846512012-02-24 11:42:47 -08003374
3375 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003376 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003377 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3378 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003379 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003380 } else if (quick_code == nullptr && method->IsNative()) {
3381 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003382 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003383 // Set entry point from compiled code if there's no code or in interpreter only mode.
3384 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003385 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003386
Ian Rogers62d6c772013-02-27 08:32:07 -08003387 if (method->IsNative()) {
3388 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003389 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003390
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003391 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003392 // We have a native method here without code. Then it should have either the generic JNI
3393 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3394 // TODO: this doesn't handle all the cases where trampolines may be installed.
3395 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003396 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3397 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003398 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003399 }
3400}
3401
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003402void ClassLinker::SetupClass(const DexFile& dex_file,
3403 const DexFile::ClassDef& dex_class_def,
3404 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003405 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003406 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003407 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003408 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003409 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003410 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003411
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003412 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003413 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003414 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003415 klass->SetAccessFlags(access_flags);
3416 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003417 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003418 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003419
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003420 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003421 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003422}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003423
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003424LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3425 LinearAlloc* allocator,
3426 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003427 if (length == 0) {
3428 return nullptr;
3429 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003430 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3431 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3432 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003433 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003434 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003435 CHECK(ret != nullptr);
3436 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3437 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003438}
3439
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003440LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3441 LinearAlloc* allocator,
3442 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003443 if (length == 0) {
3444 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003445 }
Vladimir Marko14632852015-08-17 12:07:23 +01003446 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3447 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003448 const size_t storage_size =
3449 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003450 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003451 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003452 CHECK(ret != nullptr);
3453 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003454 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003455 }
3456 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003457}
3458
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003459LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003460 if (class_loader == nullptr) {
3461 return Runtime::Current()->GetLinearAlloc();
3462 }
3463 LinearAlloc* allocator = class_loader->GetAllocator();
3464 DCHECK(allocator != nullptr);
3465 return allocator;
3466}
3467
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003468LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003469 if (class_loader == nullptr) {
3470 return Runtime::Current()->GetLinearAlloc();
3471 }
3472 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3473 LinearAlloc* allocator = class_loader->GetAllocator();
3474 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003475 RegisterClassLoader(class_loader);
3476 allocator = class_loader->GetAllocator();
3477 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003478 }
3479 return allocator;
3480}
3481
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003482void ClassLinker::LoadClass(Thread* self,
3483 const DexFile& dex_file,
3484 const DexFile::ClassDef& dex_class_def,
3485 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003486 ClassAccessor accessor(dex_file,
3487 dex_class_def,
3488 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003489 if (!accessor.HasClassData()) {
3490 return;
3491 }
3492 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003493 {
3494 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3495 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003496 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003497 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003498 // We allow duplicate definitions of the same field in a class_data_item
3499 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003500 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003501 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3502 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003503 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003504 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3505 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003506 accessor.NumInstanceFields());
3507 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003508 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003509 uint32_t last_static_field_idx = 0u;
3510 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003511
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003512 // Methods
3513 bool has_oat_class = false;
3514 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3515 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3516 : OatFile::OatClass::Invalid();
3517 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3518 klass->SetMethodsPtr(
3519 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3520 accessor.NumDirectMethods(),
3521 accessor.NumVirtualMethods());
3522 size_t class_def_method_index = 0;
3523 uint32_t last_dex_method_index = dex::kDexNoIndex;
3524 size_t last_class_def_method_index = 0;
3525
3526 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3527 // methods needs to decode all of the fields.
3528 accessor.VisitFieldsAndMethods([&](
3529 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3530 uint32_t field_idx = field.GetIndex();
3531 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3532 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3533 LoadField(field, klass, &sfields->At(num_sfields));
3534 ++num_sfields;
3535 last_static_field_idx = field_idx;
3536 }
3537 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3538 uint32_t field_idx = field.GetIndex();
3539 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3540 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3541 LoadField(field, klass, &ifields->At(num_ifields));
3542 ++num_ifields;
3543 last_instance_field_idx = field_idx;
3544 }
3545 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3546 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3547 image_pointer_size_);
3548 LoadMethod(dex_file, method, klass, art_method);
3549 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3550 uint32_t it_method_index = method.GetIndex();
3551 if (last_dex_method_index == it_method_index) {
3552 // duplicate case
3553 art_method->SetMethodIndex(last_class_def_method_index);
3554 } else {
3555 art_method->SetMethodIndex(class_def_method_index);
3556 last_dex_method_index = it_method_index;
3557 last_class_def_method_index = class_def_method_index;
3558 }
3559 ++class_def_method_index;
3560 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3561 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3562 class_def_method_index - accessor.NumDirectMethods(),
3563 image_pointer_size_);
3564 LoadMethod(dex_file, method, klass, art_method);
3565 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3566 ++class_def_method_index;
3567 });
3568
3569 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003570 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003571 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3572 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3573 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003574 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3575 if (sfields != nullptr) {
3576 sfields->SetSize(num_sfields);
3577 }
3578 if (ifields != nullptr) {
3579 ifields->SetSize(num_ifields);
3580 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003581 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003582 // Set the field arrays.
3583 klass->SetSFieldsPtr(sfields);
3584 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003585 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003586 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003587 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003588 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003589 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003590 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003591}
3592
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003593void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003594 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003595 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003596 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003597 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003598 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003599
David Brazdil85865692018-10-30 17:26:20 +00003600 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3601 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003602}
3603
Mathieu Chartier268764d2016-09-13 12:09:38 -07003604void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003605 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003606 Handle<mirror::Class> klass,
3607 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003608 const uint32_t dex_method_idx = method.GetIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003609 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003610 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003611
Mathieu Chartier268764d2016-09-13 12:09:38 -07003612 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003613 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003614 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003615 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003616
David Brazdil85865692018-10-30 17:26:20 +00003617 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3618 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003619
Ian Rogersdfb325e2013-10-30 01:00:44 -07003620 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003621 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003622 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3623 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003624 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003625 klass->SetFinalizable();
3626 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003627 std::string temp;
3628 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003629 // The Enum class declares a "final" finalize() method to prevent subclasses from
3630 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3631 // subclasses, so we exclude it here.
3632 // We also want to avoid setting the flag on Object, where we know that finalize() is
3633 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003634 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3635 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003636 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003637 }
3638 }
3639 }
3640 } else if (method_name[0] == '<') {
3641 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003642 bool is_init = (strcmp("<init>", method_name) == 0);
3643 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003644 if (UNLIKELY(!is_init && !is_clinit)) {
3645 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3646 } else {
3647 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3648 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003649 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003650 access_flags |= kAccConstructor;
3651 }
3652 }
3653 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003654 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3655 // Check if the native method is annotated with @FastNative or @CriticalNative.
3656 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3657 dex_file, dst->GetClassDef(), dex_method_idx);
3658 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003659 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003660 // Must be done after SetAccessFlags since IsAbstract depends on it.
3661 if (klass->IsInterface() && dst->IsAbstract()) {
3662 dst->CalculateAndSetImtIndex();
3663 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003664}
3665
Ian Rogers7b078e82014-09-10 14:44:24 -07003666void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003667 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003668 self,
3669 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003670 Runtime::Current()->GetLinearAlloc());
3671 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003672 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003673}
3674
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003675void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003676 ObjPtr<mirror::DexCache> dex_cache) {
3677 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003678 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003679 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003680 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003681}
3682
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003683void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003684 ObjPtr<mirror::DexCache> dex_cache,
3685 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003686 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003687 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003688 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003689 // For app images, the dex cache location may be a suffix of the dex file location since the
3690 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003691 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3692 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003693 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3694 std::string dex_file_location = dex_file.GetLocation();
3695 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003696 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003697 // Take suffix.
3698 const std::string dex_file_suffix = dex_file_location.substr(
3699 dex_file_location.length() - dex_cache_length,
3700 dex_cache_length);
3701 // Example dex_cache location is SettingsProvider.apk and
3702 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003703 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003704 const OatFile* oat_file =
3705 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003706 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3707 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3708 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3709 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003710 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003711 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3712 DexCacheData data = *it;
3713 if (self->IsJWeakCleared(data.weak_root)) {
3714 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003715 it = dex_caches_.erase(it);
3716 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003717 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003718 it->dex_file->GetOatDexFile() != nullptr &&
3719 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003720 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003721 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003722 ++it;
3723 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003724 }
Vladimir Markob066d432018-01-03 13:14:37 +00003725 if (initialize_oat_file_data) {
3726 // Initialize the .data.bimg.rel.ro section.
3727 if (!oat_file->GetBootImageRelocations().empty()) {
3728 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3729 CheckedCall(mprotect,
3730 "un-protect boot image relocations",
3731 reloc_begin,
3732 oat_file->DataBimgRelRoSize(),
3733 PROT_READ | PROT_WRITE);
3734 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3735 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3736 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3737 const_cast<uint32_t&>(relocation) += boot_image_begin;
3738 }
3739 CheckedCall(mprotect,
3740 "protect boot image relocations",
3741 reloc_begin,
3742 oat_file->DataBimgRelRoSize(),
3743 PROT_READ);
3744 }
3745
3746 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003747 // TODO: Pre-initialize from boot/app image?
3748 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3749 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3750 entry = resolution_method;
3751 }
3752 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003753 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003754 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003755 DexCacheData data;
3756 data.weak_root = dex_cache_jweak;
3757 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003758 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003759 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003760 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003761 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3762 // path dex caches without an image.
3763 data.class_table->InsertStrongRoot(dex_cache);
3764 if (class_loader != nullptr) {
3765 // Since we added a strong root to the class table, do the write barrier as required for
3766 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003767 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003768 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003769 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003770}
3771
Vladimir Markocd556b02017-02-03 11:47:34 +00003772ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3773 return data.IsValid()
3774 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3775 : nullptr;
3776}
3777
3778ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3779 Thread* self,
3780 ObjPtr<mirror::DexCache> dex_cache,
3781 const DexCacheData& data,
3782 ObjPtr<mirror::ClassLoader> class_loader) {
3783 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3784 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3785 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3786 "Attempt to register dex file %s with multiple class loaders",
3787 data.dex_file->GetLocation().c_str());
3788 return nullptr;
3789 }
3790 return dex_cache;
3791}
3792
Alex Light07f06212017-06-01 14:01:43 -07003793void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3794 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003795 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003796 Thread* self = Thread::Current();
3797 StackHandleScope<2> hs(self);
3798 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3799 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3800 const DexFile* dex_file = dex_cache->GetDexFile();
3801 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3802 if (kIsDebugBuild) {
3803 DexCacheData old_data;
3804 {
3805 ReaderMutexLock mu(self, *Locks::dex_lock_);
3806 old_data = FindDexCacheDataLocked(*dex_file);
3807 }
3808 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3809 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3810 << "been registered on dex file " << dex_file->GetLocation();
3811 }
3812 ClassTable* table;
3813 {
3814 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3815 table = InsertClassTableForClassLoader(h_class_loader.Get());
3816 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003817 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3818 // a thread holding the dex lock and blocking on a condition variable regarding
3819 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003820 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003821 WriterMutexLock mu(self, *Locks::dex_lock_);
3822 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3823 table->InsertStrongRoot(h_dex_cache.Get());
3824 if (h_class_loader.Get() != nullptr) {
3825 // Since we added a strong root to the class table, do the write barrier as required for
3826 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003827 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003828 }
3829}
3830
Vladimir Markocd556b02017-02-03 11:47:34 +00003831ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3832 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003833 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003834 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003835 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003836 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003837 old_data = FindDexCacheDataLocked(dex_file);
3838 }
3839 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3840 if (old_dex_cache != nullptr) {
3841 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003842 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003843 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003844 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3845 DCHECK(linear_alloc != nullptr);
3846 ClassTable* table;
3847 {
3848 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3849 table = InsertClassTableForClassLoader(class_loader);
3850 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003851 // Don't alloc while holding the lock, since allocation may need to
3852 // suspend all threads and another thread may need the dex_lock_ to
3853 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003854 StackHandleScope<3> hs(self);
3855 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003856 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003857 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3858 self,
3859 dex_file)));
3860 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003861 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003862 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3863 // a thread holding the dex lock and blocking on a condition variable regarding
3864 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003865 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003866 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003867 old_data = FindDexCacheDataLocked(dex_file);
3868 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003869 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003870 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3871 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3872 // that the arrays are null.
3873 mirror::DexCache::InitializeDexCache(self,
3874 h_dex_cache.Get(),
3875 h_location.Get(),
3876 &dex_file,
3877 linear_alloc,
3878 image_pointer_size_);
3879 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003880 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003881 }
3882 if (old_dex_cache != nullptr) {
3883 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3884 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003885 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003886 self->ClearException();
3887 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3888 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3889 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003890 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003891 self->AssertPendingOOMException();
3892 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003893 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003894 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003895 if (h_class_loader.Get() != nullptr) {
3896 // Since we added a strong root to the class table, do the write barrier as required for
3897 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003898 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003899 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003900 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003901}
3902
Vladimir Markocd556b02017-02-03 11:47:34 +00003903bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003904 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003905 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003906}
3907
Vladimir Markocd556b02017-02-03 11:47:34 +00003908ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3909 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003910 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3911 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003912 if (dex_cache != nullptr) {
3913 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003914 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003915 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003916 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003917 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003918 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003919 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003920 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003921 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3922 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003923 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003924}
3925
Vladimir Markocd556b02017-02-03 11:47:34 +00003926ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3927 const DexFile* dex_file = dex_cache->GetDexFile();
3928 DCHECK(dex_file != nullptr);
3929 ReaderMutexLock mu(self, *Locks::dex_lock_);
3930 // Search assuming unique-ness of dex file.
3931 for (const DexCacheData& data : dex_caches_) {
3932 // Avoid decoding (and read barriers) other unrelated dex caches.
3933 if (data.dex_file == dex_file) {
3934 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3935 if (registered_dex_cache != nullptr) {
3936 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3937 return data.class_table;
3938 }
3939 }
3940 }
3941 return nullptr;
3942}
3943
3944ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3945 // Search assuming unique-ness of dex file.
3946 for (const DexCacheData& data : dex_caches_) {
3947 // Avoid decoding (and read barriers) other unrelated dex caches.
3948 if (data.dex_file == &dex_file) {
3949 return data;
3950 }
3951 }
3952 return DexCacheData();
3953}
3954
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003955ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003956 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003957 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003958 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003959 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003960 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003961 }
Ian Rogers1f539342012-10-03 21:09:42 -07003962 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003963 StackHandleScope<1> hs(self);
3964 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003965 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003966 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3967 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003968 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003969 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003970 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003971 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003972 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3973 h_class.Get(),
3974 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003975 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003976 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003977}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003978
Vladimir Marko02610552018-06-04 14:38:00 +01003979inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
3980 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
3981}
3982
Brian Carlstrombe977852011-07-19 14:54:54 -07003983// Create an array class (i.e. the class object for the array, not the
3984// array itself). "descriptor" looks like "[C" or "[[[[B" or
3985// "[Ljava/lang/String;".
3986//
3987// If "descriptor" refers to an array of primitives, look up the
3988// primitive type's internally-generated class object.
3989//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003990// "class_loader" is the class loader of the class that's referring to
3991// us. It's used to ensure that we're looking for the element type in
3992// the right context. It does NOT become the class loader for the
3993// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003994//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003995// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003996ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
3997 const char* descriptor,
3998 size_t hash,
3999 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004000 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004001 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004002 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004003
4004 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4005 // code to be executed. We put it up here so we can avoid all the allocations associated with
4006 // creating the class. This can happen with (eg) jit threads.
4007 if (!self->CanLoadClasses()) {
4008 // Make sure we don't try to load anything, potentially causing an infinite loop.
4009 ObjPtr<mirror::Throwable> pre_allocated =
4010 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4011 self->SetException(pre_allocated);
4012 return nullptr;
4013 }
4014
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004015 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4016 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004017 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004018 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004019 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004020 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4021 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004022 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004023 DCHECK(self->IsExceptionPending());
4024 return nullptr;
4025 } else {
4026 self->ClearException();
4027 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004028 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004029 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4030 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4031 return nullptr;
4032 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004033 // See if the component type is already loaded. Array classes are
4034 // always associated with the class loader of their underlying
4035 // element type -- an array of Strings goes with the loader for
4036 // java/lang/String -- so we need to look for it there. (The
4037 // caller should have checked for the existence of the class
4038 // before calling here, but they did so with *their* class loader,
4039 // not the component type's loader.)
4040 //
4041 // If we find it, the caller adds "loader" to the class' initiating
4042 // loader list, which should prevent us from going through this again.
4043 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004044 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004045 // are the same, because our caller (FindClass) just did the
4046 // lookup. (Even if we get this wrong we still have correct behavior,
4047 // because we effectively do this lookup again when we add the new
4048 // class to the hash table --- necessary because of possible races with
4049 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004050 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004051 ObjPtr<mirror::Class> new_class =
4052 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004053 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004054 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004055 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004056 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004057
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004058 // Fill out the fields in the Class.
4059 //
4060 // It is possible to execute some methods against arrays, because
4061 // all arrays are subclasses of java_lang_Object_, so we need to set
4062 // up a vtable. We can just point at the one in java_lang_Object_.
4063 //
4064 // Array classes are simple enough that we don't need to do a full
4065 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004066 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004067 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004068 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004069 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004070 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004071 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004072 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4073 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4074 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004075 } else if (strcmp(descriptor, "[Z") == 0) {
4076 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4077 } else if (strcmp(descriptor, "[B") == 0) {
4078 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4079 } else if (strcmp(descriptor, "[C") == 0) {
4080 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4081 } else if (strcmp(descriptor, "[S") == 0) {
4082 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004083 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004084 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004085 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004086 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004087 } else if (strcmp(descriptor, "[F") == 0) {
4088 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4089 } else if (strcmp(descriptor, "[D") == 0) {
4090 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004091 }
4092 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004093 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004094 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004095 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004096 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004097 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004098 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004099 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004100 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004101 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004102 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004103 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004104 new_class->SetSuperClass(java_lang_Object);
4105 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004106 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004107 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004108 if (component_type->IsPrimitive()) {
4109 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4110 } else {
4111 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4112 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004113 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004114 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4115 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4116 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004117 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004118 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004119 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004120 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004121
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004122 // All arrays have java/lang/Cloneable and java/io/Serializable as
4123 // interfaces. We need to set that up here, so that stuff like
4124 // "instanceof" works right.
4125 //
4126 // Note: The GC could run during the call to FindSystemClass,
4127 // so we need to make sure the class object is GC-valid while we're in
4128 // there. Do this by clearing the interface list so the GC will just
4129 // think that the entries are null.
4130
4131
4132 // Use the single, global copies of "interfaces" and "iftable"
4133 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004134 {
Vladimir Marko02610552018-06-04 14:38:00 +01004135 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004136 CHECK(array_iftable != nullptr);
4137 new_class->SetIfTable(array_iftable);
4138 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004139
Elliott Hughes00626c22013-06-14 15:04:14 -07004140 // Inherit access flags from the component type.
4141 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4142 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4143 access_flags &= kAccJavaFlagsMask;
4144 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004145 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004146 access_flags |= kAccAbstract | kAccFinal;
4147 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004148 // Arrays are access-checks-clean and preverified.
4149 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004150
4151 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004152
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004153 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004154 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004155 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4156 // duplicate events in case of races. Array classes don't really follow dedicated
4157 // load and prepare, anyways.
4158 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4159 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4160
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004161 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004162 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004163 }
4164 // Another thread must have loaded the class after we
4165 // started but before we finished. Abandon what we've
4166 // done.
4167 //
4168 // (Yes, this happens.)
4169
Vladimir Markobcf17522018-06-01 13:14:32 +01004170 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004171}
4172
Vladimir Marko9186b182018-11-06 14:55:54 +00004173ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4174 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004175 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004176 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4177 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4178 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4179 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4180 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4181 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4182 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4183 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4184 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004185 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004186 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004187 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004188 return GetClassRoot(class_root, this);
4189}
4190
4191ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4192 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4193 if (UNLIKELY(result == nullptr)) {
4194 std::string printable_type(PrintableChar(type));
4195 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4196 }
4197 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198}
4199
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004200ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4201 ObjPtr<mirror::Class> klass,
4202 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004203 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004204 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004205 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004206 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004207 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004208 source += " from ";
4209 source += dex_cache->GetLocation()->ToModifiedUtf8();
4210 }
4211 LOG(INFO) << "Loaded class " << descriptor << source;
4212 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004213 {
4214 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004215 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004216 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004217 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004218 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004219 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004220 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004221 VerifyObject(klass);
4222 class_table->InsertWithHash(klass, hash);
4223 if (class_loader != nullptr) {
4224 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004225 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004226 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004227 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004228 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004229 }
4230 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004231 if (kIsDebugBuild) {
4232 // Test that copied methods correctly can find their holder.
4233 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4234 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4235 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004236 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004237 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004238}
4239
Vladimir Marko1998cd02017-01-13 13:02:58 +00004240void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004241 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4242 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4243 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4244 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004245 }
4246}
4247
Alex Lighte64300b2015-12-15 15:02:47 -08004248// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004249void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004250 LengthPrefixedArray<ArtMethod>* new_methods) {
4251 klass->SetMethodsPtrUnchecked(new_methods,
4252 klass->NumDirectMethods(),
4253 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004254 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004255 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004256}
4257
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004258ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4259 const char* descriptor,
4260 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004261 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4262}
4263
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004264ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4265 const char* descriptor,
4266 size_t hash,
4267 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004268 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4269 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4270 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004271 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004272 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004273 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004274 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004275 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004276 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004277}
4278
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004279class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4280 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004281 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004282
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004283 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004284 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004285 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004286 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004287 if (class_table != nullptr) {
4288 class_table->FreezeSnapshot();
4289 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004290 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004291};
4292
4293void ClassLinker::MoveClassTableToPreZygote() {
4294 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004295 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004296 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004297 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004298}
4299
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004300// Look up classes by hash and descriptor and put all matching ones in the result array.
4301class LookupClassesVisitor : public ClassLoaderVisitor {
4302 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004303 LookupClassesVisitor(const char* descriptor,
4304 size_t hash,
4305 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004306 : descriptor_(descriptor),
4307 hash_(hash),
4308 result_(result) {}
4309
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004310 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004311 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004312 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004313 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004314 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4315 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004316 result_->push_back(klass);
4317 }
4318 }
4319
4320 private:
4321 const char* const descriptor_;
4322 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004323 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004324};
4325
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004326void ClassLinker::LookupClasses(const char* descriptor,
4327 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004328 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004329 Thread* const self = Thread::Current();
4330 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004331 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004332 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004333 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004334 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004335 result.push_back(klass);
4336 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004337 LookupClassesVisitor visitor(descriptor, hash, &result);
4338 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004339}
4340
Alex Lightf1f10492015-10-07 16:08:36 -07004341bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4342 Handle<mirror::Class> klass,
4343 Handle<mirror::Class> supertype) {
4344 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004345 DCHECK(klass != nullptr);
4346 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004347
Alex Lightf1f10492015-10-07 16:08:36 -07004348 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4349 VerifyClass(self, supertype);
4350 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004351
4352 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4353 // The supertype is either verified, or we soft failed at AOT time.
4354 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004355 return true;
4356 }
4357 // If we got this far then we have a hard failure.
4358 std::string error_msg =
4359 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004360 klass->PrettyDescriptor().c_str(),
4361 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004362 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004363 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004364 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004365 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004366 // Set during VerifyClass call (if at all).
4367 self->ClearException();
4368 }
4369 // Change into a verify error.
4370 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004371 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004372 self->GetException()->SetCause(cause.Get());
4373 }
4374 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4375 if (Runtime::Current()->IsAotCompiler()) {
4376 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4377 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004378 // Need to grab the lock to change status.
4379 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004380 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004381 return false;
4382}
4383
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004384verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004385 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004386 {
4387 // TODO: assert that the monitor on the Class is held
4388 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004389
Andreas Gampe884f3b82016-03-30 19:52:58 -07004390 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004391 ClassStatus old_status = klass->GetStatus();
4392 while (old_status == ClassStatus::kVerifying ||
4393 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004394 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004395 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4396 // case we may see the same status again. b/62912904. This is why the check is
4397 // greater or equal.
4398 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004399 << "Class '" << klass->PrettyClass()
4400 << "' performed an illegal verification state transition from " << old_status
4401 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004402 old_status = klass->GetStatus();
4403 }
jeffhao98eacac2011-09-14 16:11:53 -07004404
Andreas Gampe884f3b82016-03-30 19:52:58 -07004405 // The class might already be erroneous, for example at compile time if we attempted to verify
4406 // this class as a parent to another.
4407 if (klass->IsErroneous()) {
4408 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004409 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004410 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004411
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004412 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004413 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004414 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004415 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004416 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004417
4418 // For AOT, don't attempt to re-verify if we have already found we should
4419 // verify at runtime.
4420 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004421 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004422 }
jeffhao98eacac2011-09-14 16:11:53 -07004423
Vladimir Marko2c64a832018-01-04 11:31:56 +00004424 if (klass->GetStatus() == ClassStatus::kResolved) {
4425 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004426 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004427 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004428 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004429 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004430 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004431 }
4432
4433 // Skip verification if disabled.
4434 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004435 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004436 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004437 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004438 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004439 }
4440
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004441 VLOG(class_linker) << "Beginning verification for class: "
4442 << klass->PrettyDescriptor()
4443 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4444
Ian Rogers9ffb0392012-09-10 11:56:50 -07004445 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004446 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004447 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4448 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004449 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004450 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004451 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004452 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004453
Alex Lightf1f10492015-10-07 16:08:36 -07004454 // Verify all default super-interfaces.
4455 //
4456 // (1) Don't bother if the superclass has already had a soft verification failure.
4457 //
4458 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4459 // recursive initialization by themselves. This is because when an interface is initialized
4460 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4461 // but choose not to for an optimization. If the interfaces is being verified due to a class
4462 // initialization (which would need all the default interfaces to be verified) the class code
4463 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004464 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004465 && !klass->IsInterface()) { // See (2)
4466 int32_t iftable_count = klass->GetIfTableCount();
4467 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4468 // Loop through all interfaces this class has defined. It doesn't matter the order.
4469 for (int32_t i = 0; i < iftable_count; i++) {
4470 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004471 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004472 // We only care if we have default interfaces and can skip if we are already verified...
4473 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4474 continue;
4475 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4476 // We had a hard failure while verifying this interface. Just return immediately.
4477 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004478 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004479 } else if (UNLIKELY(!iface->IsVerified())) {
4480 // We softly failed to verify the iface. Stop checking and clean up.
4481 // Put the iface into the supertype handle so we know what caused us to fail.
4482 supertype.Assign(iface.Get());
4483 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004484 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004485 }
4486 }
4487
Alex Lightf1f10492015-10-07 16:08:36 -07004488 // At this point if verification failed, then supertype is the "first" supertype that failed
4489 // verification (without a specific order). If verification succeeded, then supertype is either
4490 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004491 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004492 supertype.Get() == klass->GetSuperClass() ||
4493 !supertype->IsVerified());
4494
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004495 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004496 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004497 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004498 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004499
4500 VLOG(class_linker) << "Class preverified status for class "
4501 << klass->PrettyDescriptor()
4502 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4503 << ": "
4504 << preverified;
4505
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004506 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4507 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004508 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4509 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004510
Ian Rogers62d6c772013-02-27 08:32:07 -08004511 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004512 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004513 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004514 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004515 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004516
4517 // Verification is done, grab the lock again.
4518 ObjectLock<mirror::Class> lock(self, klass);
4519
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004520 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4521 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004522 VLOG(class_linker) << "Soft verification failure in class "
4523 << klass->PrettyDescriptor()
4524 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4525 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004526 }
Ian Rogers1f539342012-10-03 21:09:42 -07004527 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004528 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004529 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004530 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004531 // Even though there were no verifier failures we need to respect whether the super-class and
4532 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004533 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004534 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004535 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004536 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4537 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004538 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004539 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004540 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004541 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004542 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004543 // Soft failures at compile time should be retried at runtime. Soft
4544 // failures at runtime will be handled by slow paths in the generated
4545 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004546 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004547 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004548 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004549 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004550 // As this is a fake verified status, make sure the methods are _not_ marked
4551 // kAccSkipAccessChecks later.
4552 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004553 }
4554 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004555 } else {
David Sehr709b0702016-10-13 09:12:37 -07004556 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004557 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4558 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004559 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004560 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004561 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004562 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004563 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004564 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004565 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004566 // method.
4567 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004568 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004569 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004570
4571 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4572 // Never skip access checks if the verification soft fail is forced.
4573 // Mark the class as having a verification attempt to avoid re-running the verifier.
4574 klass->SetVerificationAttempted();
4575 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004576 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004577 }
Andreas Gampe48498592014-09-10 19:48:05 -07004578 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004579 // Done verifying. Notify the compiler about the verification status, in case the class
4580 // was verified implicitly (eg super class of a compiled class).
4581 if (Runtime::Current()->IsAotCompiler()) {
4582 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4583 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4584 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004585 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004586}
4587
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004588verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4589 Handle<mirror::Class> klass,
4590 verifier::HardFailLogMode log_level,
4591 std::string* error_msg) {
4592 Runtime* const runtime = Runtime::Current();
4593 return verifier::MethodVerifier::VerifyClass(self,
4594 klass.Get(),
4595 runtime->GetCompilerCallbacks(),
4596 runtime->IsAotCompiler(),
4597 log_level,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07004598 Runtime::Current()->GetTargetSdkVersion(),
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004599 error_msg);
4600}
4601
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004602bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004603 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004604 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004605 // If we're compiling, we can only verify the class using the oat file if
4606 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004607 // the compilation unit (app - dependencies). We will let the compiler callback
4608 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004609 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004610 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004611 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004612 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004613 return false;
4614 }
4615 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004616 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004617 return false;
4618 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004619 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004620
Andreas Gampeb40d3612018-06-26 15:49:42 -07004621 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004622 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004623 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004624 return false;
4625 }
4626
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004627 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004628 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004629 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004630 return true;
4631 }
4632 // If we only verified a subset of the classes at compile time, we can end up with classes that
4633 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004634 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004635 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004636 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004637 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004638 // Compile time verification failed with a soft error. Compile time verification can fail
4639 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004640 // class ... {
4641 // Foo x;
4642 // .... () {
4643 // if (...) {
4644 // v1 gets assigned a type of resolved class Foo
4645 // } else {
4646 // v1 gets assigned a type of unresolved class Bar
4647 // }
4648 // iput x = v1
4649 // } }
4650 // when we merge v1 following the if-the-else it results in Conflict
4651 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4652 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4653 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4654 // at compile time).
4655 return false;
4656 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004657 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004658 // Compile time verification failed with a hard error. This is caused by invalid instructions
4659 // in the class. These errors are unrecoverable.
4660 return false;
4661 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004662 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004663 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4664 // not loading the class.
4665 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4666 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004667 return false;
4668 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004669 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004670 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004671 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004672 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004673 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004674}
4675
Alex Light5a559862016-01-29 12:24:48 -08004676void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004677 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004678 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004679 }
4680}
4681
Alex Light5a559862016-01-29 12:24:48 -08004682void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004683 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004684 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004685 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004686 return; // native or abstract method
4687 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004688 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004689 return; // nothing to process
4690 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004691 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004692 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004693 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4694 CatchHandlerIterator iterator(handlers_ptr);
4695 for (; iterator.HasNext(); iterator.Next()) {
4696 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4697 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004698 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004699 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004700 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004701 DCHECK(Thread::Current()->IsExceptionPending());
4702 Thread::Current()->ClearException();
4703 }
4704 }
4705 }
4706 handlers_ptr = iterator.EndDataPointer();
4707 }
4708}
4709
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004710ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4711 jstring name,
4712 jobjectArray interfaces,
4713 jobject loader,
4714 jobjectArray methods,
4715 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004716 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004717
4718 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4719 // code to be executed. We put it up here so we can avoid all the allocations associated with
4720 // creating the class. This can happen with (eg) jit-threads.
4721 if (!self->CanLoadClasses()) {
4722 // Make sure we don't try to load anything, potentially causing an infinite loop.
4723 ObjPtr<mirror::Throwable> pre_allocated =
4724 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4725 self->SetException(pre_allocated);
4726 return nullptr;
4727 }
4728
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004729 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004730 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004731 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004732 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004733 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004734 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004735 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004736 DCHECK(temp_klass->GetClass() != nullptr);
4737 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004738 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4739 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004740 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4741 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4742 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4743 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004744 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004745 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004746 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004747 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004748 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004749 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004750
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004751 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004752 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004753
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004754 // Insert the class before loading the fields as the field roots
4755 // (ArtField::declaring_class_) are only visited from the class
4756 // table. There can't be any suspend points between inserting the
4757 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004758 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004759 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004760
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004761 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004762 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004763 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004764 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004765
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004766 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4767 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004768 ArtField& interfaces_sfield = sfields->At(0);
4769 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004770 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004771 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004772
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004773 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004774 ArtField& throws_sfield = sfields->At(1);
4775 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004776 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004777 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004778
Ian Rogers466bb252011-10-14 03:29:56 -07004779 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004780 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004781
Alex Lighte64300b2015-12-15 15:02:47 -08004782 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004783 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004784 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004785 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004786 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004787
4788 // Create the methods array.
4789 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4790 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004791 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4792 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004793 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004794 self->AssertPendingOOMException();
4795 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004796 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004797 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004798
4799 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004800 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004801
4802 // Create virtual method using specified prototypes.
4803 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004804 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004805 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004806 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004807 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004808 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4809 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004810 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004811
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004812 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004813 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004814 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004815 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004816 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004817
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004818 // At this point the class is loaded. Publish a ClassLoad event.
4819 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4820 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4821
4822 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004823 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004824 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004825 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004826 // Link the fields and virtual methods, creating vtable and iftables.
4827 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004828 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004829 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004830 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004831 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004832 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004833 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004834 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004835 CHECK(temp_klass->IsRetired());
4836 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004837
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004838 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004839 interfaces_sfield.SetObject<false>(
4840 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004841 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004842 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4843 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004844 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004845 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004846
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004847 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4848
Vladimir Marko305c38b2018-02-14 11:50:07 +00004849 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4850 // See also ClassLinker::EnsureInitialized().
4851 if (kBitstringSubtypeCheckEnabled) {
4852 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4853 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4854 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4855 }
4856
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004857 {
4858 // Lock on klass is released. Lock new class object.
4859 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004860 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004861 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004862 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004863
4864 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004865 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004866 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004867 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4868
Ian Rogersc2b44472011-12-14 21:17:17 -08004869 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004870 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4871 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004872 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004873 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004874
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004875 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004876 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004877 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004878 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004879 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004880
4881 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004882 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004883 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004884
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004885 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004886 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004887 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004888 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004889 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004890 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004891}
4892
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004893std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004894 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004895 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004896 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004897 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4898}
4899
Mathieu Chartiere401d142015-04-22 13:56:20 -07004900void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4901 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004902 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4903 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004904
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004905 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4906 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004907 ArtMethod* proxy_constructor =
4908 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004909 DCHECK(proxy_constructor != nullptr)
4910 << "Could not find <init> method in java.lang.reflect.Proxy";
4911
Jeff Haodb8a6642014-08-14 17:18:52 -07004912 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4913 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004914 DCHECK(out != nullptr);
4915 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004916 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004917 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004918 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004919 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4920 kAccPublic |
4921 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004922 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004923
4924 // Set the original constructor method.
4925 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004926}
4927
Mathieu Chartiere401d142015-04-22 13:56:20 -07004928void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004929 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004930 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4931 CHECK_STREQ(np->GetName(), "<init>");
4932 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004933 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004934}
4935
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004936void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004937 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004938 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004939 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004940 DCHECK(out != nullptr);
4941 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004942
Alex Lighte9dd04f2016-03-16 16:09:45 -07004943 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004944 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004945 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4946 // preference to the invocation handler.
4947 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4948 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004949 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4950 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004951 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4952
4953 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4954 // method they copy might (if it's a default method).
4955 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004956
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004957 // Set the original interface method.
4958 out->SetDataPtrSize(prototype, image_pointer_size_);
4959
Ian Rogers466bb252011-10-14 03:29:56 -07004960 // At runtime the method looks like a reference and argument saving method, clone the code
4961 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004962 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004963}
Jesse Wilson95caa792011-10-12 18:14:17 -04004964
Mathieu Chartiere401d142015-04-22 13:56:20 -07004965void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004966 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004967 CHECK(!prototype->IsFinal());
4968 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004969 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004970
4971 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4972 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004973 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004974 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004975}
4976
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004977bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004978 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004979 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004980 return true;
4981 }
4982 if (!can_init_statics) {
4983 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004984 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004985 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004986 return false;
4987 }
4988 // Check if there are encoded static values needing initialization.
4989 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004990 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004991 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004992 if (dex_class_def->static_values_off_ != 0) {
4993 return false;
4994 }
4995 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004996 // If we are a class we need to initialize all interfaces with default methods when we are
4997 // initialized. Check all of them.
4998 if (!klass->IsInterface()) {
4999 size_t num_interfaces = klass->GetIfTableCount();
5000 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005001 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005002 if (iface->HasDefaultMethods() &&
5003 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5004 return false;
5005 }
5006 }
5007 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005008 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005009 if (klass->IsInterface() || !klass->HasSuperClass()) {
5010 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005011 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005012 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005013 if (!can_init_parents && !super_class->IsInitialized()) {
5014 return false;
5015 }
5016 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005017}
5018
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005019bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5020 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005021 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5022
5023 // Are we already initialized and therefore done?
5024 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5025 // an initialized class will never change its state.
5026 if (klass->IsInitialized()) {
5027 return true;
5028 }
5029
5030 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005031 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005032 return false;
5033 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005034
Ian Rogers7b078e82014-09-10 14:44:24 -07005035 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005036 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005037 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005038 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005039
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005040 // Re-check under the lock in case another thread initialized ahead of us.
5041 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005042 return true;
5043 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005044
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005045 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005046 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08005047 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005048 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005049 return false;
5050 }
5051
Vladimir Marko72ab6842017-01-20 19:32:50 +00005052 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5053 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005054
5055 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005056 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005057 if (!klass->IsVerified()) {
5058 // We failed to verify, expect either the klass to be erroneous or verification failed at
5059 // compile time.
5060 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005061 // The class is erroneous. This may be a verifier error, or another thread attempted
5062 // verification and/or initialization and failed. We can distinguish those cases by
5063 // whether an exception is already pending.
5064 if (self->IsExceptionPending()) {
5065 // Check that it's a VerifyError.
5066 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005067 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005068 } else {
5069 // Check that another thread attempted initialization.
5070 DCHECK_NE(0, klass->GetClinitThreadId());
5071 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5072 // Need to rethrow the previous failure now.
5073 ThrowEarlierClassFailure(klass.Get(), true);
5074 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005075 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005076 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005077 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005078 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005079 self->AssertNoPendingException();
5080 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005081 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005082 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005083 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005084 } else {
5085 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005086 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005087
5088 // A separate thread could have moved us all the way to initialized. A "simple" example
5089 // involves a subclass of the current class being initialized at the same time (which
5090 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005091 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005092 if (klass->IsInitialized()) {
5093 return true;
5094 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005095 }
5096
Vladimir Marko2c64a832018-01-04 11:31:56 +00005097 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005098 // initializing higher up the stack or another thread has beat us
5099 // to initializing and we need to wait. Either way, this
5100 // invocation of InitializeClass will not be responsible for
5101 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005102 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005103 // Could have got an exception during verification.
5104 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005105 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005106 return false;
5107 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005108 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005109 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005110 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005111 return true;
5112 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005113 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005114 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005115 }
5116
Jeff Haoe2e40342017-07-19 10:45:18 -07005117 // Try to get the oat class's status for this class if the oat file is present. The compiler
5118 // tries to validate superclass descriptors, and writes the result into the oat file.
5119 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5120 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5121 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005122 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005123 const Runtime* runtime = Runtime::Current();
5124 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5125 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5126 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005127 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005128 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005129 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005130 return false;
5131 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005132 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005133
Vladimir Marko2c64a832018-01-04 11:31:56 +00005134 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005135 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005136
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005137 // From here out other threads may observe that we're initializing and so changes of state
5138 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005139 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005140 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005141
5142 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005143 }
5144
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005145 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005146 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005147 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005148 if (!super_class->IsInitialized()) {
5149 CHECK(!super_class->IsInterface());
5150 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005151 StackHandleScope<1> hs(self);
5152 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005153 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005154 if (!super_initialized) {
5155 // The super class was verified ahead of entering initializing, we should only be here if
5156 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005157 // For the case of aot compiler, the super class might also be initializing but we don't
5158 // want to process circular dependencies in pre-compile.
5159 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005160 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005161 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005162 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005163 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005164 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005165 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005166 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005167 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005168 return false;
5169 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005171 }
5172
Alex Lighteb7c1442015-08-31 13:17:42 -07005173 if (!klass->IsInterface()) {
5174 // Initialize interfaces with default methods for the JLS.
5175 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005176 // Only setup the (expensive) handle scope if we actually need to.
5177 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005178 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005179 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5180 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005181 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005182 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005183 CHECK(handle_scope_iface->IsInterface());
5184 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5185 // We have already done this for this interface. Skip it.
5186 continue;
5187 }
5188 // We cannot just call initialize class directly because we need to ensure that ALL
5189 // interfaces with default methods are initialized. Non-default interface initialization
5190 // will not affect other non-default super-interfaces.
5191 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5192 handle_scope_iface,
5193 can_init_statics,
5194 can_init_parents);
5195 if (!iface_initialized) {
5196 ObjectLock<mirror::Class> lock(self, klass);
5197 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005198 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005199 return false;
5200 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005201 }
5202 }
5203 }
5204
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005205 const size_t num_static_fields = klass->NumStaticFields();
5206 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005207 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005208 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005209 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005210 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005211 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005212
5213 // Eagerly fill in static fields so that the we don't have to do as many expensive
5214 // Class::FindStaticField in ResolveField.
5215 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005216 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005217 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005218 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005219 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005220 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005221 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5222 field,
5223 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5224 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005225 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005226 } else {
5227 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005228 }
5229 }
5230
Vladimir Markoe11dd502017-12-08 14:09:45 +00005231 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5232 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005233 this,
5234 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005235 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005236
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005237 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005238 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005239 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005240 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5241 if (!value_it.HasNext()) {
5242 break;
5243 }
5244 ArtField* art_field = ResolveField(field.GetIndex(),
5245 dex_cache,
5246 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005247 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005248 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005249 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005250 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005251 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005252 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005253 if (self->IsExceptionPending()) {
5254 break;
5255 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005256 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005257 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005258 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005259 }
5260 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005261
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005262
Mathieu Chartierda595be2016-08-10 13:57:39 -07005263 if (!self->IsExceptionPending()) {
5264 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5265 if (clinit != nullptr) {
5266 CHECK(can_init_statics);
5267 JValue result;
5268 clinit->Invoke(self, nullptr, 0, &result, "V");
5269 }
5270 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005271 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005272 uint64_t t1 = NanoTime();
5273
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005274 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005275 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005276 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005277
5278 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005279 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005280 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005281 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005282 } else if (Runtime::Current()->IsTransactionAborted()) {
5283 // The exception thrown when the transaction aborted has been caught and cleared
5284 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005285 VLOG(compiler) << "Return from class initializer of "
5286 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005287 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005288 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005289 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005290 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005291 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005292 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5293 RuntimeStats* thread_stats = self->GetStats();
5294 ++global_stats->class_init_count;
5295 ++thread_stats->class_init_count;
5296 global_stats->class_init_time_ns += (t1 - t0);
5297 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005298 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005299 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005300 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005301 std::string temp;
5302 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005303 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005304 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005305 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005306 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005307 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005308 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005309 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005310}
5311
Alex Lighteb7c1442015-08-31 13:17:42 -07005312// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5313// and perform the initialization only on those interfaces that contain default methods.
5314bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5315 Handle<mirror::Class> iface,
5316 bool can_init_statics,
5317 bool can_init_parents) {
5318 CHECK(iface->IsInterface());
5319 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005320 // Only create the (expensive) handle scope if we need it.
5321 if (UNLIKELY(num_direct_ifaces > 0)) {
5322 StackHandleScope<1> hs(self);
5323 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5324 // First we initialize all of iface's super-interfaces recursively.
5325 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005326 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005327 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005328 if (!super_iface->HasBeenRecursivelyInitialized()) {
5329 // Recursive step
5330 handle_super_iface.Assign(super_iface);
5331 if (!InitializeDefaultInterfaceRecursive(self,
5332 handle_super_iface,
5333 can_init_statics,
5334 can_init_parents)) {
5335 return false;
5336 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005337 }
5338 }
5339 }
5340
5341 bool result = true;
5342 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5343 // initialize if we don't have default methods.
5344 if (iface->HasDefaultMethods()) {
5345 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5346 }
5347
5348 // Mark that this interface has undergone recursive default interface initialization so we know we
5349 // can skip it on any later class initializations. We do this even if we are not a default
5350 // interface since we can still avoid the traversal. This is purely a performance optimization.
5351 if (result) {
5352 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005353 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5354 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5355 // initialization is a performance optimization (to avoid another idempotent visit
5356 // for other implementing classes/interfaces), and can be revisited later.
5357 ObjectTryLock<mirror::Class> lock(self, iface);
5358 if (lock.Acquired()) {
5359 iface->SetRecursivelyInitialized();
5360 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005361 }
5362 return result;
5363}
5364
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005365bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5366 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005367 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005368 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005369 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005370 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005371 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005372 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005373
5374 // When we wake up, repeat the test for init-in-progress. If
5375 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005376 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005377 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005378 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005379 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005380 return false;
5381 }
5382 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005383 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005384 continue;
5385 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005386 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005387 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005388 // Compile time initialization failed.
5389 return false;
5390 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005391 if (klass->IsErroneous()) {
5392 // The caller wants an exception, but it was thrown in a
5393 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005394 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005395 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005396 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005397 return false;
5398 }
5399 if (klass->IsInitialized()) {
5400 return true;
5401 }
David Sehr709b0702016-10-13 09:12:37 -07005402 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005403 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005404 }
Ian Rogers07140832014-09-30 15:43:59 -07005405 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005406}
5407
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005408static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5409 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005410 ArtMethod* method,
5411 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005412 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005413 DCHECK(Thread::Current()->IsExceptionPending());
5414 DCHECK(!m->IsProxyMethod());
5415 const DexFile* dex_file = m->GetDexFile();
5416 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5417 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005418 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005419 std::string return_type = dex_file->PrettyType(return_type_idx);
5420 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005421 ThrowWrappedLinkageError(klass.Get(),
5422 "While checking class %s method %s signature against %s %s: "
5423 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005424 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5425 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005426 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005427 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005428 return_type.c_str(), class_loader.c_str());
5429}
5430
5431static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5432 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005433 ArtMethod* method,
5434 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005435 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005436 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005437 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005438 DCHECK(Thread::Current()->IsExceptionPending());
5439 DCHECK(!m->IsProxyMethod());
5440 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005441 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5442 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005443 ThrowWrappedLinkageError(klass.Get(),
5444 "While checking class %s method %s signature against %s %s: "
5445 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005446 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5447 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005448 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005449 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005450 index, arg_type.c_str(), class_loader.c_str());
5451}
5452
5453static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5454 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005455 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005456 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005457 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005458 ThrowLinkageError(klass.Get(),
5459 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005460 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5461 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005462 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005463 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005464 error_msg.c_str());
5465}
5466
Ian Rogersb5fb2072014-12-02 17:22:02 -08005467static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005468 Handle<mirror::Class> klass,
5469 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005470 ArtMethod* method1,
5471 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005472 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005473 {
5474 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005475 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005476 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005477 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005478 return false;
5479 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005480 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005481 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005482 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005483 return false;
5484 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005485 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005486 ThrowSignatureMismatch(klass, super_klass, method1,
5487 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005488 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005489 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005490 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005491 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005492 return false;
5493 }
5494 }
5495 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5496 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5497 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005498 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005499 ThrowSignatureMismatch(klass, super_klass, method1,
5500 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005501 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005502 return false;
5503 }
5504 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005505 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005506 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005507 ThrowSignatureMismatch(klass, super_klass, method1,
5508 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005509 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005510 return false;
5511 }
5512 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005513 }
5514 uint32_t num_types = types1->Size();
5515 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005516 ThrowSignatureMismatch(klass, super_klass, method1,
5517 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005518 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005519 return false;
5520 }
5521 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005522 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005523 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005524 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005525 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005526 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005527 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005528 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005529 return false;
5530 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005531 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005532 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005533 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005534 if (UNLIKELY(other_param_type == nullptr)) {
5535 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005536 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005537 return false;
5538 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005539 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005540 ThrowSignatureMismatch(klass, super_klass, method1,
5541 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5542 i,
David Sehr709b0702016-10-13 09:12:37 -07005543 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005544 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005545 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005546 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005547 return false;
5548 }
5549 }
5550 return true;
5551}
5552
5553
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005554bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005555 if (klass->IsInterface()) {
5556 return true;
5557 }
Ian Rogers151f2212014-05-06 11:27:27 -07005558 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005559 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005560 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005562 if (klass->HasSuperClass() &&
5563 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005564 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005565 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005566 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5567 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5568 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005569 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5570 klass,
5571 super_klass,
5572 m,
5573 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005574 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005575 return false;
5576 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005577 }
5578 }
5579 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005580 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005581 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5582 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5583 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005584 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005585 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5586 j, image_pointer_size_);
5587 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5588 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005589 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5590 klass,
5591 super_klass,
5592 m,
5593 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005594 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005595 return false;
5596 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005597 }
5598 }
5599 }
5600 }
5601 return true;
5602}
5603
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005604bool ClassLinker::EnsureInitialized(Thread* self,
5605 Handle<mirror::Class> c,
5606 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005607 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005608 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005609
Mathieu Chartier524507a2014-08-27 15:28:28 -07005610 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005611 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005612 return true;
5613 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005614 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5615 //
5616 // Ensure the bitstring is initialized before any of the class initialization
5617 // logic occurs. Once a class initializer starts running, objects can
5618 // escape into the heap and use the subtype checking code.
5619 //
5620 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5621 // can be used as a source for the IsSubClass check, and that all ancestors
5622 // of the class are Assigned (can be used as a target for IsSubClass check)
5623 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005624 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005625 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005626 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005627 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5628 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005629 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005630 if (!success) {
5631 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005632 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005633 }
5634 } else {
5635 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005636 }
5637 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005638}
5639
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005640void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5641 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005642 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005643 for (ArtField& field : new_class->GetIFields()) {
5644 if (field.GetDeclaringClass() == temp_class) {
5645 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005646 }
5647 }
5648
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005649 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005650 for (ArtField& field : new_class->GetSFields()) {
5651 if (field.GetDeclaringClass() == temp_class) {
5652 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005653 }
5654 }
5655
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005656 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005657 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005658 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005659 if (method.GetDeclaringClass() == temp_class) {
5660 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005661 }
5662 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005663
5664 // Make sure the remembered set and mod-union tables know that we updated some of the native
5665 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005666 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005667}
5668
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005669void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005670 CHECK(class_loader->GetAllocator() == nullptr);
5671 CHECK(class_loader->GetClassTable() == nullptr);
5672 Thread* const self = Thread::Current();
5673 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005674 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005675 // Create and set the class table.
5676 data.class_table = new ClassTable;
5677 class_loader->SetClassTable(data.class_table);
5678 // Create and set the linear allocator.
5679 data.allocator = Runtime::Current()->CreateLinearAlloc();
5680 class_loader->SetAllocator(data.allocator);
5681 // Add to the list so that we know to free the data later.
5682 class_loaders_.push_back(data);
5683}
5684
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005685ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005686 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005687 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005688 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005689 ClassTable* class_table = class_loader->GetClassTable();
5690 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005691 RegisterClassLoader(class_loader);
5692 class_table = class_loader->GetClassTable();
5693 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005694 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005695 return class_table;
5696}
5697
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005698ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005699 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005700}
5701
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005702static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005703 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005704 while (klass->HasSuperClass()) {
5705 klass = klass->GetSuperClass();
5706 if (klass->ShouldHaveImt()) {
5707 return klass->GetImt(pointer_size);
5708 }
5709 }
5710 return nullptr;
5711}
5712
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005713bool ClassLinker::LinkClass(Thread* self,
5714 const char* descriptor,
5715 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005716 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005717 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005718 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005719
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005720 if (!LinkSuperClass(klass)) {
5721 return false;
5722 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005723 ArtMethod* imt_data[ImTable::kSize];
5724 // If there are any new conflicts compared to super class.
5725 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005726 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005727 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005728 return false;
5729 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005730 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005731 return false;
5732 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005733 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005734 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005735 return false;
5736 }
5737 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005738 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005739
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005740 ImTable* imt = nullptr;
5741 if (klass->ShouldHaveImt()) {
5742 // If there are any new conflicts compared to the super class we can not make a copy. There
5743 // can be cases where both will have a conflict method at the same slot without having the same
5744 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5745 // will possibly create a table that is incorrect for either of the classes.
5746 // Same IMT with new_conflict does not happen very often.
5747 if (!new_conflict) {
5748 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5749 if (super_imt != nullptr) {
5750 bool imt_equals = true;
5751 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5752 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5753 }
5754 if (imt_equals) {
5755 imt = super_imt;
5756 }
5757 }
5758 }
5759 if (imt == nullptr) {
5760 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5761 imt = reinterpret_cast<ImTable*>(
5762 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5763 if (imt == nullptr) {
5764 return false;
5765 }
5766 imt->Populate(imt_data, image_pointer_size_);
5767 }
5768 }
5769
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005770 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5771 // We don't need to retire this class as it has no embedded tables or it was created the
5772 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005773 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005774
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005775 if (klass->ShouldHaveEmbeddedVTable()) {
5776 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005777 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005778 if (klass->ShouldHaveImt()) {
5779 klass->SetImt(imt, image_pointer_size_);
5780 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005781
5782 // Update CHA info based on whether we override methods.
5783 // Have to do this before setting the class as resolved which allows
5784 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005785 if (cha_ != nullptr) {
5786 cha_->UpdateAfterLoadingOf(klass);
5787 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005788
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005789 // This will notify waiters on klass that saw the not yet resolved
5790 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005791 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005792 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005793 } else {
5794 CHECK(!klass->IsResolved());
5795 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005796 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005797 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005798 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5799 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5800 // may not see any references to the target space and clean the card for a class if another
5801 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005802 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005803 klass->SetSFieldsPtrUnchecked(nullptr);
5804 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005805 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005806 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005807 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005808 return false;
5809 }
5810
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005811 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5812 ObjectLock<mirror::Class> lock(self, h_new_class);
5813 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005814
5815 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005816 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005817 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005818 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005819 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005820 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005821 if (class_loader != nullptr) {
5822 // We updated the class in the class table, perform the write barrier so that the GC knows
5823 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005824 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005825 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005826 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005827 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005828 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5829 }
5830 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005831
Mingyao Yang063fc772016-08-02 11:02:54 -07005832 // Update CHA info based on whether we override methods.
5833 // Have to do this before setting the class as resolved which allows
5834 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005835 if (cha_ != nullptr) {
5836 cha_->UpdateAfterLoadingOf(h_new_class);
5837 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005838
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005839 // This will notify waiters on temp class that saw the not yet resolved class in the
5840 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005841 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005842
Vladimir Marko2c64a832018-01-04 11:31:56 +00005843 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005844 // This will notify waiters on new_class that saw the not yet resolved
5845 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005846 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005847 // Return the new class.
5848 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005849 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005850 return true;
5851}
5852
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005853bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005854 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005855 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005856 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5857 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005858 // Check that a class does not inherit from itself directly.
5859 //
5860 // TODO: This is a cheap check to detect the straightforward case
5861 // of a class extending itself (b/28685551), but we should do a
5862 // proper cycle detection on loaded classes, to detect all cases
5863 // of class circularity errors (b/28830038).
5864 if (super_class_idx == class_def.class_idx_) {
5865 ThrowClassCircularityError(klass.Get(),
5866 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005867 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005868 return false;
5869 }
5870
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005871 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005872 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005873 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005874 return false;
5875 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005876 // Verify
5877 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005878 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005879 super_class->PrettyDescriptor().c_str(),
5880 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005881 return false;
5882 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005883 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005884 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005885 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005886 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005887 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005888 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005889 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005890 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005891 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005892 DCHECK(Thread::Current()->IsExceptionPending());
5893 return false;
5894 }
5895 // Verify
5896 if (!klass->CanAccess(interface)) {
5897 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005898 ThrowIllegalAccessError(klass.Get(),
5899 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005900 interface->PrettyDescriptor().c_str(),
5901 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005902 return false;
5903 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005904 }
5905 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005906 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005907 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005908 return true;
5909}
5910
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005911bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005912 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005913 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005914 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5915 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005916 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005917 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005918 return false;
5919 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005920 return true;
5921 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005922 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005923 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005924 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005925 return false;
5926 }
5927 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005928 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005929 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5930 return false;
5931 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005932 if (super->IsFinal()) {
5933 ThrowVerifyError(klass.Get(),
5934 "Superclass %s of %s is declared final",
5935 super->PrettyDescriptor().c_str(),
5936 klass->PrettyDescriptor().c_str());
5937 return false;
5938 }
5939 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005940 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005941 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005942 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005943 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005944 return false;
5945 }
5946 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005947 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005948 super->PrettyDescriptor().c_str(),
5949 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005950 return false;
5951 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005952
Brian Carlstromf3632832014-05-20 15:36:53 -07005953 // Inherit kAccClassIsFinalizable from the superclass in case this
5954 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005955 if (super->IsFinalizable()) {
5956 klass->SetFinalizable();
5957 }
5958
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005959 // Inherit class loader flag form super class.
5960 if (super->IsClassLoaderClass()) {
5961 klass->SetClassLoaderClass();
5962 }
5963
Elliott Hughes2da50362011-10-10 16:57:08 -07005964 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005965 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005966 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005967 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005968 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005969 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005970 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005971 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005972 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005973 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005974 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005975 return false;
5976 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005977
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005978 if (kIsDebugBuild) {
5979 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005980 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005981 CHECK(super->IsResolved());
5982 super = super->GetSuperClass();
5983 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005984 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005985 return true;
5986}
5987
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005988// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005989bool ClassLinker::LinkMethods(Thread* self,
5990 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005991 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005992 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005993 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005994 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005995 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5996 // need to have default methods be in the virtuals array of each class but we don't set that up
5997 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005998 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005999 // Link virtual methods then interface methods.
6000 // We set up the interface lookup table first because we need it to determine if we need to update
6001 // any vtable entries with new default method implementations.
6002 return SetupInterfaceLookupTable(self, klass, interfaces)
6003 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006004 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006005}
6006
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006007// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6008// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6009// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006010class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006011 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006012 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006013 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006014 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6015 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006016 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006017 }
6018
6019 const char* GetName() {
6020 if (name_ == nullptr) {
6021 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6022 }
6023 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006024 }
6025
Mathieu Chartiere401d142015-04-22 13:56:20 -07006026 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006027 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006028 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006029 const DexFile* other_dex_file = other->GetDexFile();
6030 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
6031 if (dex_file_ == other_dex_file) {
6032 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6033 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006034 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006035 uint32_t other_name_len;
6036 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6037 &other_name_len);
6038 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6039 return false;
6040 }
6041 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6042 }
6043
6044 private:
6045 // Dex file for the method to compare against.
6046 const DexFile* const dex_file_;
6047 // MethodId for the method to compare against.
6048 const DexFile::MethodId* const mid_;
6049 // Lazily computed name from the dex file's strings.
6050 const char* name_;
6051 // Lazily computed name length.
6052 uint32_t name_len_;
6053};
6054
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006055class LinkVirtualHashTable {
6056 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006057 LinkVirtualHashTable(Handle<mirror::Class> klass,
6058 size_t hash_size,
6059 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006060 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006061 : klass_(klass),
6062 hash_size_(hash_size),
6063 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006064 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006065 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6066 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006067
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006068 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006069 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6070 virtual_method_index, image_pointer_size_);
6071 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006072 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006073 uint32_t index = hash % hash_size_;
6074 // Linear probe until we have an empty slot.
6075 while (hash_table_[index] != invalid_index_) {
6076 if (++index == hash_size_) {
6077 index = 0;
6078 }
6079 }
6080 hash_table_[index] = virtual_method_index;
6081 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006082
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006083 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006084 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006085 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006086 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006087 size_t index = hash % hash_size_;
6088 while (true) {
6089 const uint32_t value = hash_table_[index];
6090 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6091 // the block and can safely assume not found.
6092 if (value == invalid_index_) {
6093 break;
6094 }
6095 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006096 ArtMethod* virtual_method =
6097 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6098 if (comparator->HasSameNameAndSignature(
6099 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006100 hash_table_[index] = removed_index_;
6101 return value;
6102 }
6103 }
6104 if (++index == hash_size_) {
6105 index = 0;
6106 }
6107 }
6108 return GetNotFoundIndex();
6109 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006110
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006111 static uint32_t GetNotFoundIndex() {
6112 return invalid_index_;
6113 }
6114
6115 private:
6116 static const uint32_t invalid_index_;
6117 static const uint32_t removed_index_;
6118
6119 Handle<mirror::Class> klass_;
6120 const size_t hash_size_;
6121 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006122 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006123};
6124
6125const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6126const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6127
Stephen Hines1ddd9132017-02-08 01:51:18 -08006128bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006129 Thread* self,
6130 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006131 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006132 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006133 if (klass->IsInterface()) {
6134 // No vtable.
6135 if (!IsUint<16>(num_virtual_methods)) {
6136 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6137 return false;
6138 }
6139 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006140 // Assign each method an IMT index and set the default flag.
6141 for (size_t i = 0; i < num_virtual_methods; ++i) {
6142 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6143 m->SetMethodIndex(i);
6144 if (!m->IsAbstract()) {
6145 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6146 has_defaults = true;
6147 }
6148 }
6149 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6150 // during initialization. This is a performance optimization. We could simply traverse the
6151 // virtual_methods_ array again during initialization.
6152 if (has_defaults) {
6153 klass->SetHasDefaultMethods();
6154 }
6155 return true;
6156 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006157 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6158 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006159 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006160 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006161 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006162 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006163 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006164 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006165 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006166 return false;
6167 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006168 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006169 vtable->SetElementPtrSize(
6170 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006171 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006172 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6173 // might give us new default methods). If no new interfaces then we can skip the rest since
6174 // the class cannot override any of the super-class's methods. This is required for
6175 // correctness since without it we might not update overridden default method vtable entries
6176 // correctly.
6177 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006178 klass->SetVTable(vtable.Get());
6179 return true;
6180 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006181 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006182 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006183 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006184 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006185 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6186 // might give us new default methods). See comment above.
6187 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006188 klass->SetVTable(super_vtable);
6189 return true;
6190 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006191 vtable = hs.NewHandle(
6192 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006193 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006194 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006195 return false;
6196 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006197 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006198 // How the algorithm works:
6199 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6200 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6201 // method which has not been matched to a vtable method, and j if the virtual method at the
6202 // index overrode the super virtual method at index j.
6203 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6204 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6205 // the need for the initial vtable which we later shrink back down).
6206 // 3. Add non overridden methods to the end of the vtable.
6207 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006208 // + 1 so that even if we only have new default methods we will still be able to use this hash
6209 // table (i.e. it will never have 0 size).
6210 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006211 uint32_t* hash_table_ptr;
6212 std::unique_ptr<uint32_t[]> hash_heap_storage;
6213 if (hash_table_size <= kMaxStackHash) {
6214 hash_table_ptr = reinterpret_cast<uint32_t*>(
6215 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6216 } else {
6217 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6218 hash_table_ptr = hash_heap_storage.get();
6219 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006220 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006221 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006222 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006223 DCHECK(klass->GetVirtualMethodDuringLinking(
6224 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006225 hash_table.Add(i);
6226 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006227 // 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 -07006228 // the hash table.
6229 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006230 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006231 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006232 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6233 super_method->GetAccessFlags())) {
6234 // Continue on to the next method since this one is package private and canot be overridden.
6235 // Before Android 4.1, the package-private method super_method might have been incorrectly
6236 // overridden.
6237 continue;
6238 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006239 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006240 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006241 // We remove the method so that subsequent lookups will be faster by making the hash-map
6242 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006243 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6244 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006245 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6246 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006247 if (super_method->IsFinal()) {
6248 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6249 virtual_method->PrettyMethod().c_str(),
6250 super_method->GetDeclaringClassDescriptor());
6251 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006252 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006253 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6254 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006255 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006256 // We didn't directly override this method but we might through default methods...
6257 // Check for default method update.
6258 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006259 switch (FindDefaultMethodImplementation(self,
6260 super_method,
6261 klass,
6262 /*out*/&default_method)) {
6263 case DefaultMethodSearchResult::kDefaultConflict: {
6264 // A conflict was found looking for default methods. Note this (assuming it wasn't
6265 // pre-existing) in the translations map.
6266 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6267 // Don't generate another conflict method to reduce memory use as an optimization.
6268 default_translations->insert(
6269 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6270 }
6271 break;
6272 }
6273 case DefaultMethodSearchResult::kAbstractFound: {
6274 // No conflict but method is abstract.
6275 // We note that this vtable entry must be made abstract.
6276 if (UNLIKELY(!super_method->IsAbstract())) {
6277 default_translations->insert(
6278 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6279 }
6280 break;
6281 }
6282 case DefaultMethodSearchResult::kDefaultFound: {
6283 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6284 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6285 // Found a default method implementation that is new.
6286 // TODO Refactor this add default methods to virtuals here and not in
6287 // LinkInterfaceMethods maybe.
6288 // The problem is default methods might override previously present
6289 // default-method or miranda-method vtable entries from the superclass.
6290 // Unfortunately we need these to be entries in this class's virtuals. We do not
6291 // give these entries there until LinkInterfaceMethods so we pass this map around
6292 // to let it know which vtable entries need to be updated.
6293 // Make a note that vtable entry j must be updated, store what it needs to be updated
6294 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6295 // then.
6296 default_translations->insert(
6297 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006298 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6299 << " overridden by default "
6300 << default_method->PrettyMethod()
6301 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006302 }
6303 break;
6304 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006305 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006306 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006307 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006308 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006309 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006310 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006311 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006312 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6313 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006314 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006315 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006316 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006317 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006318 local_method->SetMethodIndex(actual_count);
6319 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006320 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006321 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006322 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006323 return false;
6324 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006325 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006326 CHECK_LE(actual_count, max_count);
6327 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006328 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006329 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006330 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006331 return false;
6332 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006333 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006334 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006335 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006336 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006337 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006338 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6339 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006340 return false;
6341 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006342 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006343 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006344 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006345 return false;
6346 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006347 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006348 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6349 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006350 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006351 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006352 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006353 }
6354 return true;
6355}
6356
Alex Light9139e002015-10-09 15:59:48 -07006357// Determine if the given iface has any subinterface in the given list that declares the method
6358// specified by 'target'.
6359//
6360// Arguments
6361// - self: The thread we are running on
6362// - target: A comparator that will match any method that overrides the method we are checking for
6363// - iftable: The iftable we are searching for an overriding method on.
6364// - ifstart: The index of the interface we are checking to see if anything overrides
6365// - iface: The interface we are checking to see if anything overrides.
6366// - image_pointer_size:
6367// The image pointer size.
6368//
6369// Returns
6370// - True: There is some method that matches the target comparator defined in an interface that
6371// is a subtype of iface.
6372// - False: There is no method that matches the target comparator in any interface that is a subtype
6373// of iface.
6374static bool ContainsOverridingMethodOf(Thread* self,
6375 MethodNameAndSignatureComparator& target,
6376 Handle<mirror::IfTable> iftable,
6377 size_t ifstart,
6378 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006379 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006380 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006381 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006382 DCHECK(iface != nullptr);
6383 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006384 DCHECK_GE(ifstart, 0u);
6385 DCHECK_LT(ifstart, iftable->Count());
6386 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6387 DCHECK(iface->IsInterface());
6388
6389 size_t iftable_count = iftable->Count();
6390 StackHandleScope<1> hs(self);
6391 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6392 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6393 // Skip ifstart since our current interface obviously cannot override itself.
6394 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006395 // Iterate through every method on this interface. The order does not matter.
6396 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006397 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006398 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006399 // Check if the i'th interface is a subtype of this one.
6400 if (iface->IsAssignableFrom(current_iface.Get())) {
6401 return true;
6402 }
6403 break;
6404 }
6405 }
6406 }
6407 return false;
6408}
6409
Alex Lighteb7c1442015-08-31 13:17:42 -07006410// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006411// out_default_method and returns kDefaultFound on success. If no default method was found return
6412// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6413// default_method conflict) it will return kDefaultConflict.
6414ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6415 Thread* self,
6416 ArtMethod* target_method,
6417 Handle<mirror::Class> klass,
6418 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006419 DCHECK(self != nullptr);
6420 DCHECK(target_method != nullptr);
6421 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006422
6423 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006424
6425 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6426 // table. This lets us walk the table backwards when searching for default methods. The first one
6427 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6428 // track of it and then continue checking all other interfaces, since we need to throw an error if
6429 // we encounter conflicting default method implementations (one is not a subtype of the other).
6430 //
6431 // The order of unrelated interfaces does not matter and is not defined.
6432 size_t iftable_count = klass->GetIfTableCount();
6433 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006434 // No interfaces. We have already reset out to null so just return kAbstractFound.
6435 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006436 }
6437
Alex Light9139e002015-10-09 15:59:48 -07006438 StackHandleScope<3> hs(self);
6439 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006440 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006441 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006442 MethodNameAndSignatureComparator target_name_comparator(
6443 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6444 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006445 for (size_t k = iftable_count; k != 0; ) {
6446 --k;
6447
Alex Lighteb7c1442015-08-31 13:17:42 -07006448 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006449
6450 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006451 // Iterate through every declared method on this interface. The order does not matter.
6452 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6453 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006454 // Skip abstract methods and methods with different names.
6455 if (current_method->IsAbstract() ||
6456 !target_name_comparator.HasSameNameAndSignature(
6457 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6458 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006459 } else if (!current_method->IsPublic()) {
6460 // The verifier should have caught the non-public method for dex version 37. Just warn and
6461 // skip it since this is from before default-methods so we don't really need to care that it
6462 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006463 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6464 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006465 << "This will be a fatal error in subsequent versions of android. "
6466 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006467 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006468 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006469 // We have multiple default impls of the same method. This is a potential default conflict.
6470 // We need to check if this possibly conflicting method is either a superclass of the chosen
6471 // default implementation or is overridden by a non-default interface method. In either case
6472 // there is no conflict.
6473 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6474 !ContainsOverridingMethodOf(self,
6475 target_name_comparator,
6476 iftable,
6477 k,
6478 iface,
6479 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006480 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006481 << current_method->PrettyMethod() << " and "
6482 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6483 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006484 *out_default_method = nullptr;
6485 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006486 } else {
6487 break; // Continue checking at the next interface.
6488 }
6489 } else {
Alex Light9139e002015-10-09 15:59:48 -07006490 // chosen_iface == null
6491 if (!ContainsOverridingMethodOf(self,
6492 target_name_comparator,
6493 iftable,
6494 k,
6495 iface,
6496 image_pointer_size_)) {
6497 // Don't set this as the chosen interface if something else is overriding it (because that
6498 // other interface would be potentially chosen instead if it was default). If the other
6499 // interface was abstract then we wouldn't select this interface as chosen anyway since
6500 // the abstract method masks it.
6501 *out_default_method = current_method;
6502 chosen_iface.Assign(iface.Get());
6503 // We should now finish traversing the graph to find if we have default methods that
6504 // conflict.
6505 } else {
David Sehr709b0702016-10-13 09:12:37 -07006506 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6507 << "' was "
6508 << "skipped because it was overridden by an abstract method in a "
6509 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006510 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006511 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006512 break;
6513 }
6514 }
Alex Light9139e002015-10-09 15:59:48 -07006515 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006516 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6517 << "' selected "
6518 << "as the implementation for '" << target_method->PrettyMethod()
6519 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006520 return DefaultMethodSearchResult::kDefaultFound;
6521 } else {
6522 return DefaultMethodSearchResult::kAbstractFound;
6523 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006524}
6525
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006526ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006527 ArtMethod* conflict_method,
6528 ArtMethod* interface_method,
6529 ArtMethod* method,
6530 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006531 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006532 Runtime* const runtime = Runtime::Current();
6533 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6534 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6535
6536 // Create a new entry if the existing one is the shared conflict method.
6537 ArtMethod* new_conflict_method = new_entry
6538 ? runtime->CreateImtConflictMethod(linear_alloc)
6539 : conflict_method;
6540
6541 // Allocate a new table. Note that we will leak this table at the next conflict,
6542 // but that's a tradeoff compared to making the table fixed size.
6543 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006544 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6545 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006546 if (data == nullptr) {
6547 LOG(ERROR) << "Failed to allocate conflict table";
6548 return conflict_method;
6549 }
6550 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6551 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006552 method,
6553 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006554
6555 // Do a fence to ensure threads see the data in the table before it is assigned
6556 // to the conflict method.
6557 // Note that there is a race in the presence of multiple threads and we may leak
6558 // memory from the LinearAlloc, but that's a tradeoff compared to using
6559 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006560 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006561 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006562 return new_conflict_method;
6563}
6564
Vladimir Marko921094a2017-01-12 18:37:06 +00006565bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6566 Handle<mirror::Class> klass,
6567 Handle<mirror::IfTable> iftable) {
6568 DCHECK(!klass->IsInterface());
6569 const bool has_superclass = klass->HasSuperClass();
6570 const bool extend_super_iftable = has_superclass;
6571 const size_t ifcount = klass->GetIfTableCount();
6572 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6573 for (size_t i = 0; i < ifcount; ++i) {
6574 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6575 if (num_methods > 0) {
6576 const bool is_super = i < super_ifcount;
6577 // This is an interface implemented by a super-class. Therefore we can just copy the method
6578 // array from the superclass.
6579 const bool super_interface = is_super && extend_super_iftable;
6580 ObjPtr<mirror::PointerArray> method_array;
6581 if (super_interface) {
6582 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6583 DCHECK(if_table != nullptr);
6584 DCHECK(if_table->GetMethodArray(i) != nullptr);
6585 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006586 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6587 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006588 } else {
6589 method_array = AllocPointerArray(self, num_methods);
6590 }
6591 if (UNLIKELY(method_array == nullptr)) {
6592 self->AssertPendingOOMException();
6593 return false;
6594 }
6595 iftable->SetMethodArray(i, method_array);
6596 }
6597 }
6598 return true;
6599}
6600
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006601void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6602 ArtMethod* imt_conflict_method,
6603 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006604 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006605 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006606 // Place method in imt if entry is empty, place conflict otherwise.
6607 if (*imt_ref == unimplemented_method) {
6608 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006609 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006610 // If we are not a conflict and we have the same signature and name as the imt
6611 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006612 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6613 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006614 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006615 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006616 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006617 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006618 *imt_ref = current_method;
6619 } else {
Alex Light9139e002015-10-09 15:59:48 -07006620 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006621 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006622 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006623 } else {
6624 // Place the default conflict method. Note that there may be an existing conflict
6625 // method in the IMT, but it could be one tailored to the super class, with a
6626 // specific ImtConflictTable.
6627 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006628 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006629 }
6630}
6631
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006632void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006633 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6634 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006635 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006636 Runtime* const runtime = Runtime::Current();
6637 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6638 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006639 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006640 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006641 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006642 FillIMTFromIfTable(klass->GetIfTable(),
6643 unimplemented_method,
6644 conflict_method,
6645 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006646 /*create_conflict_tables=*/true,
6647 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006648 &new_conflict,
6649 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006650 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006651 if (!klass->ShouldHaveImt()) {
6652 return;
6653 }
6654 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6655 // we can just use the same pointer.
6656 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006657 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006658 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6659 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6660 bool same = true;
6661 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6662 ArtMethod* method = imt_data[i];
6663 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6664 if (method != super_method) {
6665 bool is_conflict_table = method->IsRuntimeMethod() &&
6666 method != unimplemented_method &&
6667 method != conflict_method;
6668 // Verify conflict contents.
6669 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6670 super_method != unimplemented_method &&
6671 super_method != conflict_method;
6672 if (!is_conflict_table || !super_conflict_table) {
6673 same = false;
6674 } else {
6675 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6676 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6677 same = same && table1->Equals(table2, image_pointer_size_);
6678 }
6679 }
6680 }
6681 if (same) {
6682 imt = super_imt;
6683 }
6684 }
6685 if (imt == nullptr) {
6686 imt = klass->GetImt(image_pointer_size_);
6687 DCHECK(imt != nullptr);
6688 imt->Populate(imt_data, image_pointer_size_);
6689 } else {
6690 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006691 }
6692}
6693
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006694ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6695 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006696 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006697 void* data = linear_alloc->Alloc(Thread::Current(),
6698 ImtConflictTable::ComputeSize(count,
6699 image_pointer_size));
6700 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6701}
6702
6703ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6704 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6705}
6706
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006707void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006708 ArtMethod* unimplemented_method,
6709 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006710 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006711 bool create_conflict_tables,
6712 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006713 /*out*/bool* new_conflict,
6714 /*out*/ArtMethod** imt) {
6715 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006716 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006717 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006718 const size_t num_virtuals = interface->NumVirtualMethods();
6719 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6720 // Virtual methods can be larger than the if table methods if there are default methods.
6721 DCHECK_GE(num_virtuals, method_array_count);
6722 if (kIsDebugBuild) {
6723 if (klass->IsInterface()) {
6724 DCHECK_EQ(method_array_count, 0u);
6725 } else {
6726 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6727 }
6728 }
6729 if (method_array_count == 0) {
6730 continue;
6731 }
6732 auto* method_array = if_table->GetMethodArray(i);
6733 for (size_t j = 0; j < method_array_count; ++j) {
6734 ArtMethod* implementation_method =
6735 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6736 if (ignore_copied_methods && implementation_method->IsCopied()) {
6737 continue;
6738 }
6739 DCHECK(implementation_method != nullptr);
6740 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6741 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6742 // or interface methods in the IMT here they will not create extra conflicts since we compare
6743 // names and signatures in SetIMTRef.
6744 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006745 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006746
6747 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6748 // the same implementation method, keep track of this to avoid creating a conflict table in
6749 // this case.
6750
6751 // Conflict table size for each IMT slot.
6752 ++conflict_counts[imt_index];
6753
6754 SetIMTRef(unimplemented_method,
6755 imt_conflict_method,
6756 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006757 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006758 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006759 }
6760 }
6761
6762 if (create_conflict_tables) {
6763 // Create the conflict tables.
6764 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006765 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006766 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006767 if (imt[i] == imt_conflict_method) {
6768 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6769 if (new_table != nullptr) {
6770 ArtMethod* new_conflict_method =
6771 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6772 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6773 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006774 } else {
6775 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006776 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006777 }
6778 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006779 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006780 }
6781 }
6782
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006783 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006784 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006785 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6786 // Virtual methods can be larger than the if table methods if there are default methods.
6787 if (method_array_count == 0) {
6788 continue;
6789 }
6790 auto* method_array = if_table->GetMethodArray(i);
6791 for (size_t j = 0; j < method_array_count; ++j) {
6792 ArtMethod* implementation_method =
6793 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6794 if (ignore_copied_methods && implementation_method->IsCopied()) {
6795 continue;
6796 }
6797 DCHECK(implementation_method != nullptr);
6798 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006799 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006800 if (!imt[imt_index]->IsRuntimeMethod() ||
6801 imt[imt_index] == unimplemented_method ||
6802 imt[imt_index] == imt_conflict_method) {
6803 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006804 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006805 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6806 const size_t num_entries = table->NumEntries(image_pointer_size_);
6807 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6808 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006809 }
6810 }
6811 }
6812}
6813
Alex Lighteb7c1442015-08-31 13:17:42 -07006814// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6815// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006816static bool NotSubinterfaceOfAny(
6817 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6818 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006819 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006820 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006821 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006822 for (ObjPtr<mirror::Class> c : classes) {
6823 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006824 return false;
6825 }
6826 }
6827 return true;
6828}
6829
6830// Fills in and flattens the interface inheritance hierarchy.
6831//
6832// By the end of this function all interfaces in the transitive closure of to_process are added to
6833// the iftable and every interface precedes all of its sub-interfaces in this list.
6834//
6835// all I, J: Interface | I <: J implies J precedes I
6836//
6837// (note A <: B means that A is a subtype of B)
6838//
6839// This returns the total number of items in the iftable. The iftable might be resized down after
6840// this call.
6841//
6842// We order this backwards so that we do not need to reorder superclass interfaces when new
6843// interfaces are added in subclass's interface tables.
6844//
6845// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6846// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6847// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6848// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006849static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006850 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006851 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006852 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006853 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006854 // This is the set of all class's already in the iftable. Used to make checking if a class has
6855 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006856 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006857 // The first super_ifcount elements are from the superclass. We note that they are already added.
6858 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006859 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006860 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6861 classes_in_iftable.insert(iface);
6862 }
6863 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006864 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006865 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6866 // At this point in the loop current-iface-list has the invariant that:
6867 // for every pair of interfaces I,J within it:
6868 // if index_of(I) < index_of(J) then I is not a subtype of J
6869
6870 // If we have already seen this element then all of its super-interfaces must already be in the
6871 // current-iface-list so we can skip adding it.
6872 if (!ContainsElement(classes_in_iftable, interface)) {
6873 // We haven't seen this interface so add all of its super-interfaces onto the
6874 // current-iface-list, skipping those already on it.
6875 int32_t ifcount = interface->GetIfTableCount();
6876 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006877 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006878 if (!ContainsElement(classes_in_iftable, super_interface)) {
6879 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6880 classes_in_iftable.insert(super_interface);
6881 iftable->SetInterface(filled_ifcount, super_interface);
6882 filled_ifcount++;
6883 }
6884 }
6885 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6886 // Place this interface onto the current-iface-list after all of its super-interfaces.
6887 classes_in_iftable.insert(interface);
6888 iftable->SetInterface(filled_ifcount, interface);
6889 filled_ifcount++;
6890 } else if (kIsDebugBuild) {
6891 // Check all super-interfaces are already in the list.
6892 int32_t ifcount = interface->GetIfTableCount();
6893 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006894 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006896 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6897 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006898 }
6899 }
6900 }
6901 if (kIsDebugBuild) {
6902 // Check that the iftable is ordered correctly.
6903 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006904 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006905 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006906 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006907 // !(if_a <: if_b)
6908 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006909 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6910 << ") extends "
6911 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006912 << "interface list.";
6913 }
6914 }
6915 }
6916 return filled_ifcount;
6917}
6918
6919bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6920 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6921 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006922 const bool has_superclass = klass->HasSuperClass();
6923 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006924 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006925 const size_t num_interfaces =
6926 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006927 if (num_interfaces == 0) {
6928 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006929 if (LIKELY(has_superclass)) {
6930 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6931 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006932 // Class implements no interfaces.
6933 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006934 return true;
6935 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006936 // Class implements same interfaces as parent, are any of these not marker interfaces?
6937 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006938 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006939 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006940 if (super_iftable->GetMethodArrayCount(i) > 0) {
6941 has_non_marker_interface = true;
6942 break;
6943 }
6944 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006945 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006946 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006947 klass->SetIfTable(super_iftable);
6948 return true;
6949 }
6950 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006951 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006952 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006953 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006954 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006955 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006956 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006957 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006958 if (UNLIKELY(!interface->IsInterface())) {
6959 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006960 ThrowIncompatibleClassChangeError(klass.Get(),
6961 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006962 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006963 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6964 return false;
6965 }
6966 ifcount += interface->GetIfTableCount();
6967 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006968 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006969 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006970 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006971 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006972 return false;
6973 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006974 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006975 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006976 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006977 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006978 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006979 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006980 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006981 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006982
6983 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6984 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6985 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006986 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006987
6988 size_t new_ifcount;
6989 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006990 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01006991 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07006992 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006993 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006994 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01006995 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006996 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006997
6998 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006999 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007000
Ian Rogers7b078e82014-09-10 14:44:24 -07007001 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007002
Ian Rogersb52b01a2012-01-12 17:01:38 -08007003 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007004 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007005 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007006 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007007 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007008 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007009 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007010 return false;
7011 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007012 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007013 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007014 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007015 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007016 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007017 return true;
7018}
7019
Alex Light1f3925d2016-09-07 12:04:20 -07007020// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7021// of methods must be unique.
7022static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7023 return nullptr;
7024}
7025
7026template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007027static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007028 const ScopedArenaVector<ArtMethod*>& list,
7029 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007030 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007031 for (ArtMethod* method : list) {
7032 if (cmp.HasSameNameAndSignature(method)) {
7033 return method;
7034 }
7035 }
Alex Light1f3925d2016-09-07 12:04:20 -07007036 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007037}
7038
Alex Light1f3925d2016-09-07 12:04:20 -07007039// Check that all vtable entries are present in this class's virtuals or are the same as a
7040// superclasses vtable entry.
7041static void CheckClassOwnsVTableEntries(Thread* self,
7042 Handle<mirror::Class> klass,
7043 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007044 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007045 StackHandleScope<2> hs(self);
7046 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007047 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007048 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007049 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007050 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7051 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7052 CHECK(m != nullptr);
7053
Alex Lighta41a30782017-03-29 11:33:19 -07007054 if (m->GetMethodIndexDuringLinking() != i) {
7055 LOG(WARNING) << m->PrettyMethod()
7056 << " has an unexpected method index for its spot in the vtable for class"
7057 << klass->PrettyClass();
7058 }
Alex Lighte64300b2015-12-15 15:02:47 -08007059 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7060 auto is_same_method = [m] (const ArtMethod& meth) {
7061 return &meth == m;
7062 };
Alex Light3f980532017-03-17 15:10:32 -07007063 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7064 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7065 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7066 << klass->PrettyClass() << " or any of its superclasses!";
7067 }
Alex Lighte64300b2015-12-15 15:02:47 -08007068 }
7069}
7070
Alex Light1f3925d2016-09-07 12:04:20 -07007071// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7072// method is overridden in a subclass.
7073static void CheckVTableHasNoDuplicates(Thread* self,
7074 Handle<mirror::Class> klass,
7075 PointerSize pointer_size)
7076 REQUIRES_SHARED(Locks::mutator_lock_) {
7077 StackHandleScope<1> hs(self);
7078 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7079 int32_t num_entries = vtable->GetLength();
7080 for (int32_t i = 0; i < num_entries; i++) {
7081 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7082 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
7083 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7084 vtable_entry->GetAccessFlags())) {
7085 continue;
7086 }
7087 MethodNameAndSignatureComparator name_comparator(
7088 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07007089 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07007090 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07007091 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
7092 other_entry->GetAccessFlags())) {
7093 continue;
7094 }
Alex Light3f980532017-03-17 15:10:32 -07007095 if (vtable_entry == other_entry ||
7096 name_comparator.HasSameNameAndSignature(
7097 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
7098 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7099 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
7100 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
7101 << other_entry->PrettyMethod() << " (0x" << std::hex
7102 << reinterpret_cast<uintptr_t>(other_entry) << ")";
7103 }
Alex Light1f3925d2016-09-07 12:04:20 -07007104 }
7105 }
7106}
7107
7108static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7109 REQUIRES_SHARED(Locks::mutator_lock_) {
7110 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7111 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7112}
7113
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007114void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7115 ArtMethod* unimplemented_method,
7116 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007117 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007118 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007119 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007120 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007121 if (super_class->ShouldHaveImt()) {
7122 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7123 for (size_t i = 0; i < ImTable::kSize; ++i) {
7124 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007125 }
7126 } else {
7127 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007128 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007129 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007130 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007131 FillIMTFromIfTable(if_table,
7132 unimplemented_method,
7133 imt_conflict_method,
7134 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007135 /*create_conflict_tables=*/false,
7136 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007137 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007138 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007139 }
7140 }
7141}
7142
Vladimir Marko921094a2017-01-12 18:37:06 +00007143class ClassLinker::LinkInterfaceMethodsHelper {
7144 public:
7145 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7146 Handle<mirror::Class> klass,
7147 Thread* self,
7148 Runtime* runtime)
7149 : class_linker_(class_linker),
7150 klass_(klass),
7151 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7152 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7153 self_(self),
7154 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7155 allocator_(&stack_),
7156 default_conflict_methods_(allocator_.Adapter()),
7157 overriding_default_conflict_methods_(allocator_.Adapter()),
7158 miranda_methods_(allocator_.Adapter()),
7159 default_methods_(allocator_.Adapter()),
7160 overriding_default_methods_(allocator_.Adapter()),
7161 move_table_(allocator_.Adapter()) {
7162 }
7163
7164 ArtMethod* FindMethod(ArtMethod* interface_method,
7165 MethodNameAndSignatureComparator& interface_name_comparator,
7166 ArtMethod* vtable_impl)
7167 REQUIRES_SHARED(Locks::mutator_lock_);
7168
7169 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7170 MethodNameAndSignatureComparator& interface_name_comparator)
7171 REQUIRES_SHARED(Locks::mutator_lock_);
7172
7173 bool HasNewVirtuals() const {
7174 return !(miranda_methods_.empty() &&
7175 default_methods_.empty() &&
7176 overriding_default_methods_.empty() &&
7177 overriding_default_conflict_methods_.empty() &&
7178 default_conflict_methods_.empty());
7179 }
7180
7181 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7182
7183 ObjPtr<mirror::PointerArray> UpdateVtable(
7184 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7185 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7186
7187 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7188
7189 void UpdateIMT(ArtMethod** out_imt);
7190
7191 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7192 if (kIsDebugBuild) {
7193 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7194 // Check that there are no stale methods are in the dex cache array.
7195 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7196 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007197 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7198 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007199 CHECK(move_table_.find(m) == move_table_.end() ||
7200 // The original versions of copied methods will still be present so allow those too.
7201 // Note that if the first check passes this might fail to GetDeclaringClass().
7202 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7203 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7204 [m] (ArtMethod& meth) {
7205 return &meth == m;
7206 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7207 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7208 }
7209 }
7210 }
7211
7212 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7213 LengthPrefixedArray<ArtMethod>* methods) {
7214 if (kIsDebugBuild) {
7215 CHECK(methods != nullptr);
7216 // Put some random garbage in old methods to help find stale pointers.
7217 if (methods != old_methods && old_methods != nullptr) {
7218 // Need to make sure the GC is not running since it could be scanning the methods we are
7219 // about to overwrite.
7220 ScopedThreadStateChange tsc(self_, kSuspended);
7221 gc::ScopedGCCriticalSection gcs(self_,
7222 gc::kGcCauseClassLinker,
7223 gc::kCollectorTypeClassLinker);
7224 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7225 method_size_,
7226 method_alignment_);
7227 memset(old_methods, 0xFEu, old_size);
7228 }
7229 }
7230 }
7231
7232 private:
7233 size_t NumberOfNewVirtuals() const {
7234 return miranda_methods_.size() +
7235 default_methods_.size() +
7236 overriding_default_conflict_methods_.size() +
7237 overriding_default_methods_.size() +
7238 default_conflict_methods_.size();
7239 }
7240
7241 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7242 return !klass_->IsInterface();
7243 }
7244
7245 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7246 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7247 << "Interfaces should only have default-conflict methods appended to them.";
7248 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7249 << miranda_methods_.size()
7250 << " default_methods=" << default_methods_.size()
7251 << " overriding_default_methods=" << overriding_default_methods_.size()
7252 << " default_conflict_methods=" << default_conflict_methods_.size()
7253 << " overriding_default_conflict_methods="
7254 << overriding_default_conflict_methods_.size();
7255 }
7256
7257 ClassLinker* class_linker_;
7258 Handle<mirror::Class> klass_;
7259 size_t method_alignment_;
7260 size_t method_size_;
7261 Thread* const self_;
7262
7263 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7264 // the virtual methods array.
7265 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7266 // during cross compilation.
7267 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7268 ArenaStack stack_;
7269 ScopedArenaAllocator allocator_;
7270
7271 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7272 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7273 ScopedArenaVector<ArtMethod*> miranda_methods_;
7274 ScopedArenaVector<ArtMethod*> default_methods_;
7275 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7276
7277 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7278};
7279
7280ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7281 ArtMethod* interface_method,
7282 MethodNameAndSignatureComparator& interface_name_comparator,
7283 ArtMethod* vtable_impl) {
7284 ArtMethod* current_method = nullptr;
7285 switch (class_linker_->FindDefaultMethodImplementation(self_,
7286 interface_method,
7287 klass_,
7288 /*out*/&current_method)) {
7289 case DefaultMethodSearchResult::kDefaultConflict: {
7290 // Default method conflict.
7291 DCHECK(current_method == nullptr);
7292 ArtMethod* default_conflict_method = nullptr;
7293 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7294 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7295 default_conflict_method = vtable_impl;
7296 } else {
7297 // See if we already have a conflict method for this method.
7298 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7299 interface_name_comparator,
7300 default_conflict_methods_,
7301 overriding_default_conflict_methods_);
7302 if (LIKELY(preexisting_conflict != nullptr)) {
7303 // We already have another conflict we can reuse.
7304 default_conflict_method = preexisting_conflict;
7305 } else {
7306 // Note that we do this even if we are an interface since we need to create this and
7307 // cannot reuse another classes.
7308 // Create a new conflict method for this to use.
7309 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7310 new(default_conflict_method) ArtMethod(interface_method,
7311 class_linker_->GetImagePointerSize());
7312 if (vtable_impl == nullptr) {
7313 // Save the conflict method. We need to add it to the vtable.
7314 default_conflict_methods_.push_back(default_conflict_method);
7315 } else {
7316 // Save the conflict method but it is already in the vtable.
7317 overriding_default_conflict_methods_.push_back(default_conflict_method);
7318 }
7319 }
7320 }
7321 current_method = default_conflict_method;
7322 break;
7323 } // case kDefaultConflict
7324 case DefaultMethodSearchResult::kDefaultFound: {
7325 DCHECK(current_method != nullptr);
7326 // Found a default method.
7327 if (vtable_impl != nullptr &&
7328 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7329 // We found a default method but it was the same one we already have from our
7330 // superclass. Don't bother adding it to our vtable again.
7331 current_method = vtable_impl;
7332 } else if (LIKELY(FillTables())) {
7333 // Interfaces don't need to copy default methods since they don't have vtables.
7334 // Only record this default method if it is new to save space.
7335 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7336 // would make lookup for interface super much faster. (We would only need to scan
7337 // the iftable to find if there is a NSME or AME.)
7338 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7339 default_methods_,
7340 overriding_default_methods_);
7341 if (old == nullptr) {
7342 // We found a default method implementation and there were no conflicts.
7343 if (vtable_impl == nullptr) {
7344 // Save the default method. We need to add it to the vtable.
7345 default_methods_.push_back(current_method);
7346 } else {
7347 // Save the default method but it is already in the vtable.
7348 overriding_default_methods_.push_back(current_method);
7349 }
7350 } else {
7351 CHECK(old == current_method) << "Multiple default implementations selected!";
7352 }
7353 }
7354 break;
7355 } // case kDefaultFound
7356 case DefaultMethodSearchResult::kAbstractFound: {
7357 DCHECK(current_method == nullptr);
7358 // Abstract method masks all defaults.
7359 if (vtable_impl != nullptr &&
7360 vtable_impl->IsAbstract() &&
7361 !vtable_impl->IsDefaultConflicting()) {
7362 // We need to make this an abstract method but the version in the vtable already is so
7363 // don't do anything.
7364 current_method = vtable_impl;
7365 }
7366 break;
7367 } // case kAbstractFound
7368 }
7369 return current_method;
7370}
7371
7372ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7373 ArtMethod* interface_method,
7374 MethodNameAndSignatureComparator& interface_name_comparator) {
7375 // Find out if there is already a miranda method we can use.
7376 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7377 miranda_methods_);
7378 if (miranda_method == nullptr) {
7379 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7380 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7381 CHECK(miranda_method != nullptr);
7382 // Point the interface table at a phantom slot.
7383 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7384 miranda_methods_.push_back(miranda_method);
7385 }
7386 return miranda_method;
7387}
7388
7389void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7390 LogNewVirtuals();
7391
7392 const size_t old_method_count = klass_->NumMethods();
7393 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7394 DCHECK_NE(old_method_count, new_method_count);
7395
7396 // Attempt to realloc to save RAM if possible.
7397 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7398 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7399 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7400 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7401 // CopyFrom has internal read barriers.
7402 //
7403 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7404 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7405 method_size_,
7406 method_alignment_);
7407 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7408 method_size_,
7409 method_alignment_);
7410 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7411 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007412 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007413 self_, old_methods, old_methods_ptr_size, new_size));
7414 CHECK(methods != nullptr); // Native allocation failure aborts.
7415
7416 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7417 if (methods != old_methods) {
7418 // Maps from heap allocated miranda method to linear alloc miranda method.
7419 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7420 // Copy over the old methods.
7421 for (auto& m : klass_->GetMethods(pointer_size)) {
7422 move_table_.emplace(&m, &*out);
7423 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7424 // barriers when it copies.
7425 out->CopyFrom(&m, pointer_size);
7426 ++out;
7427 }
7428 }
7429 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7430 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7431 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007432 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7433 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007434 ArtMethod& new_method = *out;
7435 new_method.CopyFrom(mir_method, pointer_size);
7436 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7437 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7438 << "Miranda method should be abstract!";
7439 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007440 // Update the entry in the method array, as the array will be used for future lookups,
7441 // where thread suspension is allowed.
7442 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7443 // would not see them.
7444 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007445 ++out;
7446 }
7447 // We need to copy the default methods into our own method table since the runtime requires that
7448 // every method on a class's vtable be in that respective class's virtual method table.
7449 // NOTE This means that two classes might have the same implementation of a method from the same
7450 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7451 // default method found on a class with one found on the declaring interface directly and must
7452 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007453 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7454 &overriding_default_methods_}) {
7455 for (size_t i = 0; i < methods_vec->size(); ++i) {
7456 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007457 ArtMethod& new_method = *out;
7458 new_method.CopyFrom(def_method, pointer_size);
7459 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7460 // verified yet it shouldn't have methods that are skipping access checks.
7461 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7462 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007463 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007464 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7465 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7466 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7467 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007468 // Update the entry in the method array, as the array will be used for future lookups,
7469 // where thread suspension is allowed.
7470 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7471 // would not see them.
7472 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007473 ++out;
7474 }
7475 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007476 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7477 &overriding_default_conflict_methods_}) {
7478 for (size_t i = 0; i < methods_vec->size(); ++i) {
7479 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007480 ArtMethod& new_method = *out;
7481 new_method.CopyFrom(conf_method, pointer_size);
7482 // This is a type of default method (there are default method impls, just a conflict) so
7483 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7484 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7485 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007486 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7487 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007488 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007489 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007490 constexpr uint32_t kMaskFlags =
7491 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007492 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7493 DCHECK(new_method.IsDefaultConflicting());
7494 // The actual method might or might not be marked abstract since we just copied it from a
7495 // (possibly default) interface method. We need to set it entry point to be the bridge so
7496 // that the compiler will not invoke the implementation of whatever method we copied from.
7497 EnsureThrowsInvocationError(class_linker_, &new_method);
7498 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007499 // Update the entry in the method array, as the array will be used for future lookups,
7500 // where thread suspension is allowed.
7501 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7502 // would not see them.
7503 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007504 ++out;
7505 }
7506 }
7507 methods->SetSize(new_method_count);
7508 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7509}
7510
7511ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7512 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7513 ObjPtr<mirror::PointerArray> old_vtable) {
7514 // Update the vtable to the new method structures. We can skip this for interfaces since they
7515 // do not have vtables.
7516 const size_t old_vtable_count = old_vtable->GetLength();
7517 const size_t new_vtable_count = old_vtable_count +
7518 miranda_methods_.size() +
7519 default_methods_.size() +
7520 default_conflict_methods_.size();
7521
7522 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007523 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007524 if (UNLIKELY(vtable == nullptr)) {
7525 self_->AssertPendingOOMException();
7526 return nullptr;
7527 }
7528
7529 size_t vtable_pos = old_vtable_count;
7530 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7531 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7532 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7533 default_conflict_methods_,
7534 miranda_methods_}) {
7535 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007536 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007537 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7538 // fields are references into the dex file the method was defined in. Since the ArtMethod
7539 // does not store that information it uses declaring_class_->dex_cache_.
7540 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7541 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7542 ++vtable_pos;
7543 }
7544 }
7545 DCHECK_EQ(vtable_pos, new_vtable_count);
7546
7547 // Update old vtable methods. We use the default_translations map to figure out what each
7548 // vtable entry should be updated to, if they need to be at all.
7549 for (size_t i = 0; i < old_vtable_count; ++i) {
7550 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7551 // Try and find what we need to change this method to.
7552 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007553 if (translation_it != default_translations.end()) {
7554 if (translation_it->second.IsInConflict()) {
7555 // Find which conflict method we are to use for this method.
7556 MethodNameAndSignatureComparator old_method_comparator(
7557 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7558 // We only need to look through overriding_default_conflict_methods since this is an
7559 // overridden method we are fixing up here.
7560 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7561 old_method_comparator, overriding_default_conflict_methods_);
7562 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7563 translated_method = new_conflict_method;
7564 } else if (translation_it->second.IsAbstract()) {
7565 // Find which miranda method we are to use for this method.
7566 MethodNameAndSignatureComparator old_method_comparator(
7567 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7568 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7569 miranda_methods_);
7570 DCHECK(miranda_method != nullptr);
7571 translated_method = miranda_method;
7572 } else {
7573 // Normal default method (changed from an older default or abstract interface method).
7574 DCHECK(translation_it->second.IsTranslation());
7575 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007576 auto it = move_table_.find(translated_method);
7577 DCHECK(it != move_table_.end());
7578 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007579 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007580 } else {
7581 auto it = move_table_.find(translated_method);
7582 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007583 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007584
7585 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007586 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007587 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007588 if (kIsDebugBuild) {
7589 auto* methods = klass_->GetMethodsPtr();
7590 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007591 reinterpret_cast<uintptr_t>(translated_method));
7592 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007593 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7594 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007595 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007596 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007597 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007598 }
7599 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007600 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007601 return vtable;
7602}
7603
7604void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7605 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7606 const size_t ifcount = klass_->GetIfTableCount();
7607 // Go fix up all the stale iftable pointers.
7608 for (size_t i = 0; i < ifcount; ++i) {
7609 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7610 auto* method_array = iftable->GetMethodArray(i);
7611 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7612 DCHECK(m != nullptr) << klass_->PrettyClass();
7613 auto it = move_table_.find(m);
7614 if (it != move_table_.end()) {
7615 auto* new_m = it->second;
7616 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7617 method_array->SetElementPtrSize(j, new_m, pointer_size);
7618 }
7619 }
7620 }
7621}
7622
7623void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7624 // Fix up IMT next.
7625 for (size_t i = 0; i < ImTable::kSize; ++i) {
7626 auto it = move_table_.find(out_imt[i]);
7627 if (it != move_table_.end()) {
7628 out_imt[i] = it->second;
7629 }
7630 }
7631}
7632
Alex Light705ad492015-09-21 11:36:30 -07007633// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007634bool ClassLinker::LinkInterfaceMethods(
7635 Thread* self,
7636 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007637 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007638 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007639 ArtMethod** out_imt) {
7640 StackHandleScope<3> hs(self);
7641 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007642
7643 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007644 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007645 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007646 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007647 const size_t ifcount = klass->GetIfTableCount();
7648
Vladimir Marko921094a2017-01-12 18:37:06 +00007649 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007650
7651 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7652 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007653 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007654 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007655 const bool extend_super_iftable = has_superclass;
7656 if (has_superclass && fill_tables) {
7657 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007658 unimplemented_method,
7659 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007660 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007661 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007662 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007663 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7664 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007665 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007666 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7667 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007668 }
7669 }
7670
Vladimir Marko921094a2017-01-12 18:37:06 +00007671 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7672
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007673 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007674 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007675 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7676 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7677 // they will already be null. This has the additional benefit that the declarer of a miranda
7678 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007679 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007680 --i;
Alex Light9139e002015-10-09 15:59:48 -07007681 DCHECK_LT(i, ifcount);
7682
Alex Light705ad492015-09-21 11:36:30 -07007683 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007684 if (num_methods > 0) {
7685 StackHandleScope<2> hs2(self);
7686 const bool is_super = i < super_ifcount;
7687 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007688 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7689 // conflict methods. Just set this as nullptr in those cases.
7690 Handle<mirror::PointerArray> method_array(fill_tables
7691 ? hs2.NewHandle(iftable->GetMethodArray(i))
7692 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007693
Alex Lighte64300b2015-12-15 15:02:47 -08007694 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007695 ScopedNullHandle<mirror::PointerArray> null_handle;
7696 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007697 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007698
Alex Light9139e002015-10-09 15:59:48 -07007699 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7700 // and confusing. Default methods should always look through all the superclasses
7701 // because they are the last choice of an implementation. We get around this by looking
7702 // at the super-classes iftable methods (copied into method_array previously) when we are
7703 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007704 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007705 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007706 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007707 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007708 using_virtuals = true;
7709 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7710 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007711 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007712 // For a new interface, however, we need the whole vtable in case a new
7713 // interface method is implemented in the whole superclass.
7714 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007715 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007716 input_vtable_array = vtable;
7717 input_array_length = input_vtable_array->GetLength();
7718 }
Alex Lighte64300b2015-12-15 15:02:47 -08007719
Alex Lighteb7c1442015-08-31 13:17:42 -07007720 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007721 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007722 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007723 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007724 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007725 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007726 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007727 // For each method listed in the interface's method list, find the
7728 // matching method in our class's method list. We want to favor the
7729 // subclass over the superclass, which just requires walking
7730 // back from the end of the vtable. (This only matters if the
7731 // superclass defines a private method and this class redefines
7732 // it -- otherwise it would use the same vtable slot. In .dex files
7733 // those don't end up in the virtual method table, so it shouldn't
7734 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007735 //
7736 // To find defaults we need to do the same but also go over interfaces.
7737 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007738 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007739 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007740 ArtMethod* vtable_method = using_virtuals ?
7741 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007742 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7743 ArtMethod* vtable_method_for_name_comparison =
7744 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007745 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007746 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007747 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007748 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7749 // allocations.
7750 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007751 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007752 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007753 vtable_method->PrettyMethod().c_str(),
7754 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007755 return false;
Alex Light9139e002015-10-09 15:59:48 -07007756 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007757 // We might have a newer, better, default method for this, so we just skip it. If we
7758 // are still using this we will select it again when scanning for default methods. To
7759 // obviate the need to copy the method again we will make a note that we already found
7760 // a default here.
7761 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007762 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007763 break;
7764 } else {
7765 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007766 if (LIKELY(fill_tables)) {
7767 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7768 // Place method in imt if entry is empty, place conflict otherwise.
7769 SetIMTRef(unimplemented_method,
7770 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007771 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007772 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007773 /*out*/imt_ptr);
7774 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007775 break;
7776 }
7777 }
Alex Light9139e002015-10-09 15:59:48 -07007778 }
7779 // Continue on to the next method if we are done.
7780 if (LIKELY(found_impl)) {
7781 continue;
7782 } else if (LIKELY(super_interface)) {
7783 // Don't look for a default implementation when the super-method is implemented directly
7784 // by the class.
7785 //
7786 // See if we can use the superclasses method and skip searching everything else.
7787 // Note: !found_impl && super_interface
7788 CHECK(extend_super_iftable);
7789 // If this is a super_interface method it is possible we shouldn't override it because a
7790 // superclass could have implemented it directly. We get the method the superclass used
7791 // to implement this to know if we can override it with a default method. Doing this is
7792 // safe since we know that the super_iftable is filled in so we can simply pull it from
7793 // there. We don't bother if this is not a super-classes interface since in that case we
7794 // have scanned the entire vtable anyway and would have found it.
7795 // TODO This is rather dirty but it is faster than searching through the entire vtable
7796 // every time.
7797 ArtMethod* supers_method =
7798 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7799 DCHECK(supers_method != nullptr);
7800 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007801 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007802 // The method is not overridable by a default method (i.e. it is directly implemented
7803 // in some class). Therefore move onto the next interface method.
7804 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007805 } else {
7806 // If the super-classes method is override-able by a default method we need to keep
7807 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7808 // 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 -07007809 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7810 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7811 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007812 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007813 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7814 << " and not 'nullptr' or "
7815 << supers_method->PrettyMethod()
7816 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007817 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007818 }
7819 }
7820 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007821 ArtMethod* current_method = helper.FindMethod(interface_method,
7822 interface_name_comparator,
7823 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007824 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007825 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007826 // We could not find an implementation for this method and since it is a brand new
7827 // interface we searched the entire vtable (and all default methods) for an
7828 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007829 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7830 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007831 }
7832
7833 if (current_method != nullptr) {
7834 // We found a default method implementation. Record it in the iftable and IMT.
7835 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7836 SetIMTRef(unimplemented_method,
7837 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007838 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007839 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007840 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007841 }
7842 }
Alex Light705ad492015-09-21 11:36:30 -07007843 } // For each method in interface end.
7844 } // if (num_methods > 0)
7845 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007846 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007847 if (helper.HasNewVirtuals()) {
7848 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7849 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7850 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7851
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007852 // 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 -07007853 // suspension assert.
7854 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007855
Alex Light705ad492015-09-21 11:36:30 -07007856 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007857 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007858 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007859 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007860 return false;
7861 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007862 helper.UpdateIfTable(iftable);
7863 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007864 }
Alex Light705ad492015-09-21 11:36:30 -07007865
Vladimir Marko921094a2017-01-12 18:37:06 +00007866 helper.CheckNoStaleMethodsInDexCache();
7867 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007868 } else {
7869 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007870 }
Alex Light705ad492015-09-21 11:36:30 -07007871 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007872 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007873 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007874 return true;
7875}
7876
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007877bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007878 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007879 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007880}
7881
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007882bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007883 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007884 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007885}
7886
Brian Carlstromdbc05252011-09-09 01:59:59 -07007887struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007888 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007889 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007890 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007891 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007892 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007893 // 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 -07007894 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7895 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007896 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007897 if (type1 == Primitive::kPrimNot) {
7898 // Reference always goes first.
7899 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007900 }
Vladimir Markod5777482014-11-12 17:02:02 +00007901 if (type2 == Primitive::kPrimNot) {
7902 // Reference always goes first.
7903 return false;
7904 }
7905 size_t size1 = Primitive::ComponentSize(type1);
7906 size_t size2 = Primitive::ComponentSize(type2);
7907 if (size1 != size2) {
7908 // Larger primitive types go first.
7909 return size1 > size2;
7910 }
7911 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7912 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007913 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007914 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7915 // by name and for equal names by type id index.
7916 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7917 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007918 }
7919};
7920
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007921bool ClassLinker::LinkFields(Thread* self,
7922 Handle<mirror::Class> klass,
7923 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007924 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007925 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007926 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007927 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7928 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007929
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007930 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007931 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007932 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007933 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007934 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007935 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007936 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007937 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007938 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007939 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007940 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007941 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007942
David Sehr709b0702016-10-13 09:12:37 -07007943 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007944
Brian Carlstromdbc05252011-09-09 01:59:59 -07007945 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007946 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007947 //
7948 // The overall sort order order is:
7949 // 1) All object reference fields, sorted alphabetically.
7950 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7951 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7952 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7953 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7954 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7955 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7956 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7957 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7958 //
7959 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7960 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007961 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007962 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007963 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007964 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007965 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007966 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007967 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7968 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007969
Fred Shih381e4ca2014-08-25 17:24:27 -07007970 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007971 size_t current_field = 0;
7972 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007973 FieldGaps gaps;
7974
Brian Carlstromdbc05252011-09-09 01:59:59 -07007975 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007976 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007977 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007978 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007979 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007980 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007981 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007982 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7983 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007984 MemberOffset old_offset = field_offset;
7985 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7986 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7987 }
Roland Levillain14d90572015-07-16 10:52:26 +01007988 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007989 grouped_and_sorted_fields.pop_front();
7990 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007991 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007992 field_offset = MemberOffset(field_offset.Uint32Value() +
7993 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007994 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007995 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7996 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007997 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7998 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7999 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8000 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008001 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8002 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008003 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008004
Elliott Hughesadb460d2011-10-05 17:02:34 -07008005 // 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 -07008006 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008007 // We know there are no non-reference fields in the Reference classes, and we know
8008 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008009 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008010 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008011 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008012 --num_reference_fields;
8013 }
8014
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008015 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008016 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008017 if (is_static) {
8018 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008019 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008020 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008021 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008022 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008023 if (num_reference_fields == 0 || super_class == nullptr) {
8024 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008025 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008026 if (super_class == nullptr ||
8027 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8028 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008029 }
8030 }
8031 if (kIsDebugBuild) {
8032 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8033 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008034 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008035 while (cur_super != nullptr) {
8036 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8037 cur_super = cur_super->GetSuperClass();
8038 }
8039 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008040 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008041 } else {
8042 // Check that there is at least num_reference_fields other than Object.class.
8043 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008044 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008045 }
8046 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008047 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008048 std::string temp;
8049 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8050 size_t previous_size = klass->GetObjectSize();
8051 if (previous_size != 0) {
8052 // Make sure that we didn't originally have an incorrect size.
8053 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008054 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008055 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008056 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008057 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008058
8059 if (kIsDebugBuild) {
8060 // Make sure that the fields array is ordered by name but all reference
8061 // offsets are at the beginning as far as alignment allows.
8062 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008063 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008064 : klass->GetFirstReferenceInstanceFieldOffset();
8065 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8066 num_reference_fields *
8067 sizeof(mirror::HeapReference<mirror::Object>));
8068 MemberOffset current_ref_offset = start_ref_offset;
8069 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008070 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008071 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008072 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8073 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008074 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008075 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008076 // NOTE: The field names can be the same. This is not possible in the Java language
8077 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008078 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008079 }
8080 Primitive::Type type = field->GetTypeAsPrimitiveType();
8081 bool is_primitive = type != Primitive::kPrimNot;
8082 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8083 strcmp("referent", field->GetName()) == 0) {
8084 is_primitive = true; // We lied above, so we have to expect a lie here.
8085 }
8086 MemberOffset offset = field->GetOffsetDuringLinking();
8087 if (is_primitive) {
8088 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8089 // Shuffled before references.
8090 size_t type_size = Primitive::ComponentSize(type);
8091 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8092 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8093 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8094 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8095 }
8096 } else {
8097 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8098 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8099 sizeof(mirror::HeapReference<mirror::Object>));
8100 }
8101 }
8102 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8103 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008104 return true;
8105}
8106
Vladimir Marko76649e82014-11-10 18:32:59 +00008107// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008108void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008109 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008110 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008111 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008112 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008113 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008114 // Compute reference offsets unless our superclass overflowed.
8115 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8116 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008117 if (num_reference_fields != 0u) {
8118 // All of the fields that contain object references are guaranteed be grouped in memory
8119 // starting at an appropriately aligned address after super class object data.
8120 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8121 sizeof(mirror::HeapReference<mirror::Object>));
8122 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008123 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008124 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008125 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008126 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008127 reference_offsets |= (0xffffffffu << start_bit) &
8128 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008129 }
8130 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008131 }
8132 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008133 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008134}
8135
Vladimir Marko18090d12018-06-01 16:53:12 +01008136ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8137 ObjPtr<mirror::DexCache> dex_cache) {
8138 StackHandleScope<1> hs(Thread::Current());
8139 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8140 return DoResolveString(string_idx, h_dex_cache);
8141}
8142
8143ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8144 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008145 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008146 uint32_t utf16_length;
8147 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008148 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008149 if (string != nullptr) {
8150 dex_cache->SetResolvedString(string_idx, string);
8151 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008152 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008153}
8154
Vladimir Marko18090d12018-06-01 16:53:12 +01008155ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8156 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008157 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008158 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008159 uint32_t utf16_length;
8160 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008161 ObjPtr<mirror::String> string =
8162 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008163 if (string != nullptr) {
8164 dex_cache->SetResolvedString(string_idx, string);
8165 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008166 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008167}
8168
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008169ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008170 ObjPtr<mirror::Class> referrer) {
8171 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8172}
8173
8174ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008175 ObjPtr<mirror::DexCache> dex_cache,
8176 ObjPtr<mirror::ClassLoader> class_loader) {
8177 const DexFile& dex_file = *dex_cache->GetDexFile();
8178 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8179 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8180 ObjPtr<mirror::Class> type = nullptr;
8181 if (descriptor[1] == '\0') {
8182 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8183 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008184 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008185 } else {
8186 Thread* const self = Thread::Current();
8187 DCHECK(self != nullptr);
8188 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8189 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008190 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008191 }
8192 if (type != nullptr) {
8193 if (type->IsResolved()) {
8194 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008195 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008196 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008197 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008198 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008199 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008200}
8201
Andreas Gampe4835d212018-11-21 14:55:10 -08008202template <typename T>
8203ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008204 StackHandleScope<2> hs(Thread::Current());
8205 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8206 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8207 return DoResolveType(type_idx, dex_cache, class_loader);
8208}
8209
Andreas Gampe4835d212018-11-21 14:55:10 -08008210// Instantiate the above.
8211template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8212 ArtField* referrer);
8213template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8214 ArtMethod* referrer);
8215template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8216 ObjPtr<mirror::Class> referrer);
8217
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008218ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008219 Handle<mirror::DexCache> dex_cache,
8220 Handle<mirror::ClassLoader> class_loader) {
8221 Thread* self = Thread::Current();
8222 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8223 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8224 if (resolved != nullptr) {
8225 // TODO: we used to throw here if resolved's class loader was not the
8226 // boot class loader. This was to permit different classes with the
8227 // same name to be loaded simultaneously by different loaders
8228 dex_cache->SetResolvedType(type_idx, resolved);
8229 } else {
8230 CHECK(self->IsExceptionPending())
8231 << "Expected pending exception for failed resolution of: " << descriptor;
8232 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8233 StackHandleScope<1> hs(self);
8234 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008235 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008236 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8237 self->ClearException();
8238 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8239 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008240 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008241 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008242 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008243 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008244 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008245}
8246
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008247ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8248 ObjPtr<mirror::DexCache> dex_cache,
8249 ObjPtr<mirror::ClassLoader> class_loader,
8250 uint32_t method_idx) {
8251 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8252 // functions can optimize the search if the dex_cache is the same as the DexCache
8253 // of the class, with fall-back to name and signature search otherwise.
8254 ArtMethod* resolved = nullptr;
8255 if (klass->IsInterface()) {
8256 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8257 } else {
8258 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8259 }
8260 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008261 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008262 hiddenapi::ShouldDenyAccessToMember(resolved,
8263 hiddenapi::AccessContext(class_loader, dex_cache),
8264 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008265 resolved = nullptr;
8266 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008267 if (resolved != nullptr) {
8268 // In case of jmvti, the dex file gets verified before being registered, so first
8269 // check if it's registered before checking class tables.
8270 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008271 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8272 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008273 << "DexFile referrer: " << dex_file.GetLocation()
8274 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8275 // Be a good citizen and update the dex cache to speed subsequent calls.
8276 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008277 // Disable the following invariant check as the verifier breaks it. b/73760543
8278 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8279 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8280 // << "Method: " << resolved->PrettyMethod() << ", "
8281 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8282 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008283 }
8284 return resolved;
8285}
8286
David Brazdil4525e0b2018-04-05 16:57:32 +01008287// Returns true if `method` is either null or hidden.
8288// Does not print any warnings if it is hidden.
8289static bool CheckNoSuchMethod(ArtMethod* method,
8290 ObjPtr<mirror::DexCache> dex_cache,
8291 ObjPtr<mirror::ClassLoader> class_loader)
8292 REQUIRES_SHARED(Locks::mutator_lock_) {
8293 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008294 hiddenapi::ShouldDenyAccessToMember(method,
8295 hiddenapi::AccessContext(class_loader, dex_cache),
8296 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008297}
8298
8299ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8300 ObjPtr<mirror::DexCache> dex_cache,
8301 ObjPtr<mirror::ClassLoader> class_loader,
8302 uint32_t method_idx) {
8303 if (klass->IsInterface()) {
8304 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8305 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8306 } else {
8307 // If there was an interface method with the same signature, we would have
8308 // found it in the "copied" methods. Only DCHECK that the interface method
8309 // really does not exist.
8310 if (kIsDebugBuild) {
8311 ArtMethod* method =
8312 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8313 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8314 }
8315 return nullptr;
8316 }
8317}
8318
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008319template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008320ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008321 Handle<mirror::DexCache> dex_cache,
8322 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008323 ArtMethod* referrer,
8324 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008325 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008326 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008327 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008328 PointerSize pointer_size = image_pointer_size_;
8329 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008330 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008331 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8332 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008333 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8334 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008335 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008336 return resolved;
8337 }
Vladimir Marko89011192017-12-11 13:45:05 +00008338 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008339 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008340 ObjPtr<mirror::Class> klass = nullptr;
8341 if (valid_dex_cache_method) {
8342 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8343 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008344 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008345 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008346 // We normaly should not end up here. However the verifier currently doesn't guarantee
8347 // the invariant of having the klass in the class table. b/73760543
8348 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008349 }
Vladimir Markoba118822017-06-12 15:41:56 +01008350 } else {
8351 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008352 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008353 if (klass == nullptr) {
8354 DCHECK(Thread::Current()->IsExceptionPending());
8355 return nullptr;
8356 }
8357 }
8358
8359 // Check if the invoke type matches the class type.
8360 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008361 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008362 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008363 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008364 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008365 }
Vladimir Markoba118822017-06-12 15:41:56 +01008366
8367 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008368 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008369 }
Vladimir Markoba118822017-06-12 15:41:56 +01008370
8371 // Note: We can check for IllegalAccessError only if we have a referrer.
8372 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8373 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8374 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8375 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8376 resolved,
8377 dex_cache.Get(),
8378 method_idx,
8379 type)) {
8380 DCHECK(Thread::Current()->IsExceptionPending());
8381 return nullptr;
8382 }
8383 }
8384
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008385 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008386 if (LIKELY(resolved != nullptr) &&
8387 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8388 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008389 return resolved;
8390 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008391 // If we had a method, or if we can find one with another lookup type,
8392 // it's an incompatible-class-change error.
8393 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008394 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008395 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008396 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008397 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008398 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008399 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008400 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8401 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008402 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008403 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008404 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008405 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008406 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008407}
8408
Vladimir Marko89011192017-12-11 13:45:05 +00008409ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008410 Handle<mirror::DexCache> dex_cache,
8411 Handle<mirror::ClassLoader> class_loader) {
8412 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008413 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008414 if (resolved != nullptr) {
8415 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008416 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8417 return resolved;
8418 }
8419 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008420 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
8421 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008422 if (klass == nullptr) {
8423 Thread::Current()->AssertPendingException();
8424 return nullptr;
8425 }
8426 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008427 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8428 } else {
8429 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008430 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008431 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008432 hiddenapi::ShouldDenyAccessToMember(
8433 resolved,
8434 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8435 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008436 resolved = nullptr;
8437 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008438 return resolved;
8439}
8440
Vladimir Markof44d36c2017-03-14 14:18:46 +00008441ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8442 ObjPtr<mirror::DexCache> dex_cache,
8443 ObjPtr<mirror::ClassLoader> class_loader,
8444 bool is_static) {
8445 const DexFile& dex_file = *dex_cache->GetDexFile();
8446 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8447 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8448 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008449 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008450 }
8451 if (klass == nullptr) {
8452 // The class has not been resolved yet, so the field is also unresolved.
8453 return nullptr;
8454 }
8455 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008456
David Brazdil1ab0fa82018-05-04 11:28:03 +01008457 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008458}
8459
Vladimir Markoe11dd502017-12-08 14:09:45 +00008460ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008461 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008462 Handle<mirror::ClassLoader> class_loader,
8463 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008464 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008465 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008466 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008467 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008468 return resolved;
8469 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008470 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008471 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008472 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008473 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008474 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008475 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008476 }
8477
David Brazdil1ab0fa82018-05-04 11:28:03 +01008478 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008479 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008480 const char* name = dex_file.GetFieldName(field_id);
8481 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008482 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008483 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008484 return resolved;
8485}
8486
Vladimir Markoe11dd502017-12-08 14:09:45 +00008487ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008488 Handle<mirror::DexCache> dex_cache,
8489 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008490 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008491 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008492 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008493 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008494 return resolved;
8495 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008496 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008497 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008498 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008499 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008500 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008501 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008502 }
8503
David Brazdil1ab0fa82018-05-04 11:28:03 +01008504 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8505 if (resolved == nullptr) {
8506 const char* name = dex_file.GetFieldName(field_id);
8507 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008508 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008509 }
8510 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008511}
8512
David Brazdil1ab0fa82018-05-04 11:28:03 +01008513ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8514 ObjPtr<mirror::DexCache> dex_cache,
8515 ObjPtr<mirror::ClassLoader> class_loader,
8516 uint32_t field_idx,
8517 bool is_static) {
8518 ArtField* resolved = nullptr;
8519 Thread* self = is_static ? Thread::Current() : nullptr;
8520 const DexFile& dex_file = *dex_cache->GetDexFile();
8521
8522 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8523 : klass->FindInstanceField(dex_cache, field_idx);
8524
8525 if (resolved == nullptr) {
8526 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8527 const char* name = dex_file.GetFieldName(field_id);
8528 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8529 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8530 : klass->FindInstanceField(name, type);
8531 }
8532
8533 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008534 hiddenapi::ShouldDenyAccessToMember(resolved,
8535 hiddenapi::AccessContext(class_loader, dex_cache),
8536 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008537 resolved = nullptr;
8538 }
8539
8540 if (resolved != nullptr) {
8541 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8542 }
8543
8544 return resolved;
8545}
8546
8547ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8548 ObjPtr<mirror::DexCache> dex_cache,
8549 ObjPtr<mirror::ClassLoader> class_loader,
8550 uint32_t field_idx) {
8551 ArtField* resolved = nullptr;
8552 Thread* self = Thread::Current();
8553 const DexFile& dex_file = *dex_cache->GetDexFile();
8554 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8555
8556 const char* name = dex_file.GetFieldName(field_id);
8557 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8558 resolved = mirror::Class::FindField(self, klass, name, type);
8559
8560 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008561 hiddenapi::ShouldDenyAccessToMember(resolved,
8562 hiddenapi::AccessContext(class_loader, dex_cache),
8563 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008564 resolved = nullptr;
8565 }
8566
8567 if (resolved != nullptr) {
8568 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8569 }
8570
8571 return resolved;
8572}
8573
Vladimir Markoaf940202017-12-08 15:01:18 +00008574ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8575 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008576 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008577 Handle<mirror::DexCache> dex_cache,
8578 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008579 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008580 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008581
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008582 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008583 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008584 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008585 }
8586
Narayan Kamath25352fc2016-08-03 12:46:58 +01008587 StackHandleScope<4> hs(self);
8588
8589 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008590 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008591 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8592 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008593 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008594 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008595 DCHECK(self->IsExceptionPending());
8596 return nullptr;
8597 }
8598
8599 // Then resolve the argument types.
8600 //
8601 // TODO: Is there a better way to figure out the number of method arguments
8602 // other than by looking at the shorty ?
8603 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8604
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008605 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008606 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8607 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008608 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008609 DCHECK(self->IsExceptionPending());
8610 return nullptr;
8611 }
8612
8613 DexFileParameterIterator it(dex_file, proto_id);
8614 int32_t i = 0;
8615 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8616 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008617 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008618 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008619 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008620 DCHECK(self->IsExceptionPending());
8621 return nullptr;
8622 }
8623
8624 method_params->Set(i++, param_class.Get());
8625 }
8626
8627 DCHECK(!it.HasNext());
8628
8629 Handle<mirror::MethodType> type = hs.NewHandle(
8630 mirror::MethodType::Create(self, return_type, method_params));
8631 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8632
8633 return type.Get();
8634}
8635
Vladimir Markoaf940202017-12-08 15:01:18 +00008636ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008637 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008638 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008639 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008640 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8641 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008642 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008643}
8644
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008645mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8646 Thread* self,
8647 const DexFile::MethodHandleItem& method_handle,
8648 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008649 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008650 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8651 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008652 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008653 bool is_static;
8654 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008655 switch (handle_type) {
8656 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008657 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008658 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008659 is_static = true;
8660 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008661 break;
8662 }
8663 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008664 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008665 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008666 is_static = true;
8667 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008668 break;
8669 }
8670 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008671 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008672 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008673 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008674 num_params = 2;
8675 break;
8676 }
8677 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008678 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008679 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008680 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008681 num_params = 1;
8682 break;
8683 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008684 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008685 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008686 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008687 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008688 case DexFile::MethodHandleType::kInvokeInterface:
8689 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008690 }
8691
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008692 ArtField* target_field =
8693 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8694 if (LIKELY(target_field != nullptr)) {
8695 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8696 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8697 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8698 ThrowIllegalAccessErrorField(referring_class, target_field);
8699 return nullptr;
8700 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008701 if (UNLIKELY(is_put && target_field->IsFinal())) {
8702 ThrowIllegalAccessErrorField(referring_class, target_field);
8703 return nullptr;
8704 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008705 } else {
8706 DCHECK(Thread::Current()->IsExceptionPending());
8707 return nullptr;
8708 }
8709
8710 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008711 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008712 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8713 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008714 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008715 DCHECK(self->IsExceptionPending());
8716 return nullptr;
8717 }
8718
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008719 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008720 Handle<mirror::Class> return_type;
8721 switch (handle_type) {
8722 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008723 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008724 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008725 break;
8726 }
8727 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008728 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008729 break;
8730 }
8731 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008732 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008733 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008734 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008735 break;
8736 }
8737 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008738 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008739 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008740 break;
8741 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008742 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008743 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008744 case DexFile::MethodHandleType::kInvokeConstructor:
8745 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008746 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008747 UNREACHABLE();
8748 }
8749
8750 for (int32_t i = 0; i < num_params; ++i) {
8751 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8752 DCHECK(self->IsExceptionPending());
8753 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008754 }
8755 }
8756
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008757 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008758 DCHECK(self->IsExceptionPending());
8759 return nullptr;
8760 }
8761
8762 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008763 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8764 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008765 DCHECK(self->IsExceptionPending());
8766 return nullptr;
8767 }
Orion Hodson631827d2017-04-10 14:53:47 +01008768
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008769 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8770 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8771}
8772
8773mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8774 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008775 const DexFile::MethodHandleItem& method_handle,
8776 ArtMethod* referrer) {
8777 DexFile::MethodHandleType handle_type =
8778 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8779 mirror::MethodHandle::Kind kind;
8780 uint32_t receiver_count = 0;
8781 ArtMethod* target_method = nullptr;
8782 switch (handle_type) {
8783 case DexFile::MethodHandleType::kStaticPut:
8784 case DexFile::MethodHandleType::kStaticGet:
8785 case DexFile::MethodHandleType::kInstancePut:
8786 case DexFile::MethodHandleType::kInstanceGet:
8787 UNREACHABLE();
8788 case DexFile::MethodHandleType::kInvokeStatic: {
8789 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8790 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008791 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8792 method_handle.field_or_method_idx_,
8793 referrer,
8794 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008795 break;
8796 }
8797 case DexFile::MethodHandleType::kInvokeInstance: {
8798 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8799 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008800 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8801 method_handle.field_or_method_idx_,
8802 referrer,
8803 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008804 break;
8805 }
8806 case DexFile::MethodHandleType::kInvokeConstructor: {
8807 // Constructors are currently implemented as a transform. They
8808 // are special cased later in this method.
8809 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8810 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008811 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8812 method_handle.field_or_method_idx_,
8813 referrer,
8814 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008815 break;
8816 }
8817 case DexFile::MethodHandleType::kInvokeDirect: {
8818 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8819 receiver_count = 1;
8820 StackHandleScope<2> hs(self);
8821 // A constant method handle with type kInvokeDirect can refer to
8822 // a method that is private or to a method in a super class. To
8823 // disambiguate the two options, we resolve the method ignoring
8824 // the invocation type to determine if the method is private. We
8825 // then resolve again specifying the intended invocation type to
8826 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008827 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008828 hs.NewHandle(referrer->GetDexCache()),
8829 hs.NewHandle(referrer->GetClassLoader()));
8830 if (UNLIKELY(target_method == nullptr)) {
8831 break;
8832 }
8833
8834 if (target_method->IsPrivate()) {
8835 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008836 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8837 method_handle.field_or_method_idx_,
8838 referrer,
8839 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008840 } else {
8841 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008842 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8843 method_handle.field_or_method_idx_,
8844 referrer,
8845 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008846 if (UNLIKELY(target_method == nullptr)) {
8847 break;
8848 }
8849 // Find the method specified in the parent in referring class
8850 // so invoke-super invokes the method in the parent of the
8851 // referrer.
8852 target_method =
8853 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8854 kRuntimePointerSize);
8855 }
8856 break;
8857 }
8858 case DexFile::MethodHandleType::kInvokeInterface: {
8859 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8860 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008861 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8862 method_handle.field_or_method_idx_,
8863 referrer,
8864 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008865 break;
8866 }
Orion Hodson631827d2017-04-10 14:53:47 +01008867 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008868
8869 if (UNLIKELY(target_method == nullptr)) {
8870 DCHECK(Thread::Current()->IsExceptionPending());
8871 return nullptr;
8872 }
8873
8874 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8875 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8876 uint32_t access_flags = target_method->GetAccessFlags();
8877 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8878 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8879 return nullptr;
8880 }
8881
8882 // Calculate the number of parameters from the method shorty. We add the
8883 // receiver count (0 or 1) and deduct one for the return value.
8884 uint32_t shorty_length;
8885 target_method->GetShorty(&shorty_length);
8886 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8887
Orion Hodsonecd58562018-09-24 11:27:33 +01008888 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008889 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008890 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8891 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8892 if (method_params.Get() == nullptr) {
8893 DCHECK(self->IsExceptionPending());
8894 return nullptr;
8895 }
8896
Orion Hodsonecd58562018-09-24 11:27:33 +01008897 const DexFile* dex_file = referrer->GetDexFile();
8898 const DexFile::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008899 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008900 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01008901 // Insert receiver. Use the class identified in the method handle rather than the declaring
8902 // class of the resolved method which may be super class or default interface method
8903 // (b/115964401).
8904 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
8905 // receiver_class should have been resolved when resolving the target method.
8906 DCHECK(receiver_class != nullptr);
8907 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008908 }
Orion Hodsonecd58562018-09-24 11:27:33 +01008909
8910 const DexFile::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
8911 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008912 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008913 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008914 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01008915 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008916 if (nullptr == klass) {
8917 DCHECK(self->IsExceptionPending());
8918 return nullptr;
8919 }
8920 method_params->Set(index++, klass);
8921 it.Next();
8922 }
8923
Orion Hodsonecd58562018-09-24 11:27:33 +01008924 Handle<mirror::Class> return_type =
8925 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008926 if (UNLIKELY(return_type.IsNull())) {
8927 DCHECK(self->IsExceptionPending());
8928 return nullptr;
8929 }
8930
8931 Handle<mirror::MethodType>
8932 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8933 if (UNLIKELY(method_type.IsNull())) {
8934 DCHECK(self->IsExceptionPending());
8935 return nullptr;
8936 }
8937
8938 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8939 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8940 Handle<mirror::MethodHandlesLookup> lookup =
8941 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8942 return lookup->FindConstructor(self, constructor_class, method_type);
8943 }
8944
8945 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8946 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8947}
8948
Vladimir Markoaf940202017-12-08 15:01:18 +00008949ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8950 uint32_t method_handle_idx,
8951 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008952 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008953 const DexFile* const dex_file = referrer->GetDexFile();
8954 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8955 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8956 case DexFile::MethodHandleType::kStaticPut:
8957 case DexFile::MethodHandleType::kStaticGet:
8958 case DexFile::MethodHandleType::kInstancePut:
8959 case DexFile::MethodHandleType::kInstanceGet:
8960 return ResolveMethodHandleForField(self, method_handle, referrer);
8961 case DexFile::MethodHandleType::kInvokeStatic:
8962 case DexFile::MethodHandleType::kInvokeInstance:
8963 case DexFile::MethodHandleType::kInvokeConstructor:
8964 case DexFile::MethodHandleType::kInvokeDirect:
8965 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008966 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008967 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008968}
8969
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008970bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8971 return (entry_point == GetQuickResolutionStub()) ||
8972 (quick_resolution_trampoline_ == entry_point);
8973}
8974
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008975bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8976 return (entry_point == GetQuickToInterpreterBridge()) ||
8977 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8978}
8979
8980bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8981 return (entry_point == GetQuickGenericJniStub()) ||
8982 (quick_generic_jni_trampoline_ == entry_point);
8983}
8984
David Sehra49e0532017-08-25 08:05:29 -07008985bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8986 return entry_point == GetJniDlsymLookupStub();
8987}
8988
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008989const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8990 return GetQuickGenericJniStub();
8991}
8992
Mathieu Chartiere401d142015-04-22 13:56:20 -07008993void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008994 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008995 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8996 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008997 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008998 }
8999}
9000
Alex Lightdb01a092017-04-03 15:39:55 -07009001void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9002 DCHECK(method->IsObsolete());
9003 // We cannot mess with the entrypoints of native methods because they are used to determine how
9004 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9005 if (!method->IsNative()) {
9006 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9007 }
9008}
9009
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009010void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009011 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009012 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009013 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9014 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009015 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9016 os << "Dumping registered class loaders\n";
9017 size_t class_loader_index = 0;
9018 for (const ClassLoaderData& class_loader : class_loaders_) {
9019 ObjPtr<mirror::ClassLoader> loader =
9020 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9021 if (loader != nullptr) {
9022 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9023 bool saw_one_dex_file = false;
9024 for (const DexCacheData& dex_cache : dex_caches_) {
9025 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9026 if (saw_one_dex_file) {
9027 os << ":";
9028 }
9029 saw_one_dex_file = true;
9030 os << dex_cache.dex_file->GetLocation();
9031 }
9032 }
9033 os << "]";
9034 bool found_parent = false;
9035 if (loader->GetParent() != nullptr) {
9036 size_t parent_index = 0;
9037 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9038 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9039 soa.Self()->DecodeJObject(class_loader2.weak_root));
9040 if (loader2 == loader->GetParent()) {
9041 os << ", parent #" << parent_index;
9042 found_parent = true;
9043 break;
9044 }
9045 parent_index++;
9046 }
9047 if (!found_parent) {
9048 os << ", unregistered parent of type "
9049 << loader->GetParent()->GetClass()->PrettyDescriptor();
9050 }
9051 } else {
9052 os << ", no parent";
9053 }
9054 os << "\n";
9055 }
9056 }
9057 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009058}
9059
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009060class CountClassesVisitor : public ClassLoaderVisitor {
9061 public:
9062 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9063
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009064 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009065 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009066 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009067 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009068 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9069 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009070 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009071 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009072
9073 size_t num_zygote_classes;
9074 size_t num_non_zygote_classes;
9075};
9076
9077size_t ClassLinker::NumZygoteClasses() const {
9078 CountClassesVisitor visitor;
9079 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009080 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009081}
9082
9083size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009084 CountClassesVisitor visitor;
9085 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009086 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009087}
9088
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009089size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009090 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009091 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009092 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009093}
9094
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009095pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009096 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009097}
9098
9099pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009100 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009101}
9102
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009103void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009104 DCHECK(!init_done_);
9105
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009106 DCHECK(klass != nullptr);
9107 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009108
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009109 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009110 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009111 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9112 int32_t index = static_cast<int32_t>(class_root);
9113 DCHECK(class_roots->Get(index) == nullptr);
9114 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009115}
9116
Roland Levillain0e840272018-08-23 19:55:30 +01009117void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9118 ObjPtr<mirror::Class> java_lang_Class,
9119 ClassRoot primitive_array_class_root,
9120 ClassRoot primitive_class_root,
9121 const char* descriptor) {
9122 StackHandleScope<1> hs(self);
9123 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9124 AllocPrimitiveArrayClass(self, java_lang_Class)));
9125 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9126 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9127 CheckSystemClass(self, primitive_array_class, descriptor);
9128}
9129
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009130ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9131 Thread* self,
9132 const std::vector<const DexFile*>& dex_files,
9133 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009134 Handle<mirror::ClassLoader> parent_loader,
9135 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009136
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009137 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009138
Mathieu Chartierc7853442015-03-27 14:35:38 -07009139 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009140 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009141
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009142 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009143 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009144 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009145 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009146 mirror::ObjectArray<mirror::Object>::Alloc(self,
9147 dex_elements_class.Get(),
9148 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009149 Handle<mirror::Class> h_dex_element_class =
9150 hs.NewHandle(dex_elements_class->GetComponentType());
9151
Mathieu Chartierc7853442015-03-27 14:35:38 -07009152 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009153 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009154 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009155
Andreas Gampe08883de2016-11-08 13:20:52 -08009156 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009157 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009158
Andreas Gampe08883de2016-11-08 13:20:52 -08009159 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009160 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009161
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009162 // Fill the elements array.
9163 int32_t index = 0;
9164 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009165 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009166
Calin Juravle7865ac72017-06-28 11:03:12 -07009167 // CreateWellKnownClassLoader is only used by gtests and compiler.
9168 // 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 -07009169 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9170 self,
9171 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009172 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009173 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009174
Mathieu Chartier3738e982017-05-12 16:07:28 -07009175 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9176 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009177 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009178 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009179 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009180 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009181
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009182 Handle<mirror::String> h_file_name = hs2.NewHandle(
9183 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009184 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009185 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9186
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009187 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009188 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009189 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009190
9191 h_dex_elements->Set(index, h_element.Get());
9192 index++;
9193 }
9194 DCHECK_EQ(index, h_dex_elements->GetLength());
9195
9196 // Create DexPathList.
9197 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009198 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009199 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009200 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009201 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009202 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9203 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9204 // elements.
9205 {
9206 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9207 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9208 DCHECK(native_lib_dirs != nullptr);
9209 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9210 DCHECK(list_class != nullptr);
9211 {
9212 StackHandleScope<1> h_list_scope(self);
9213 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9214 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9215 DCHECK(list_init);
9216 list_class = h_list_class.Get();
9217 }
9218 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9219 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9220 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9221 // normally never null), as long as one does not try to add elements, this will still
9222 // work.
9223 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9224 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009225
Calin Juravle7865ac72017-06-28 11:03:12 -07009226 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009227 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9228 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009229 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009230 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009231 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009232 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009233 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009234 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009235
9236 // Make a pretend boot-classpath.
9237 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009238 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009239 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009240 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009241 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009242 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009243 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009244 if (parent_loader.Get() == nullptr) {
9245 ScopedObjectAccessUnchecked soa(self);
9246 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9247 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9248 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9249 } else {
9250 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9251 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009252
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009253 ArtField* shared_libraries_field =
9254 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9255 DCHECK(shared_libraries_field != nullptr);
9256 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9257
9258 return h_class_loader.Get();
9259}
9260
9261jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9262 const std::vector<const DexFile*>& dex_files,
9263 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009264 jobject parent_loader,
9265 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009266 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9267 WellKnownClasses::dalvik_system_PathClassLoader) ||
9268 self->GetJniEnv()->IsSameObject(loader_class,
9269 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
9270
9271 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9272 // We could move the jobject to the callers, but all call-sites do this...
9273 ScopedObjectAccessUnchecked soa(self);
9274
9275 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009276 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009277
9278 Handle<mirror::Class> h_loader_class =
9279 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009280 Handle<mirror::ClassLoader> h_parent =
9281 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9282 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9283 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009284
9285 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9286 self,
9287 dex_files,
9288 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009289 h_parent,
9290 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009291
9292 // Make it a global ref and return.
9293 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009294 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009295 return soa.Env()->NewGlobalRef(local_ref.get());
9296}
9297
Calin Juravle7865ac72017-06-28 11:03:12 -07009298jobject ClassLinker::CreatePathClassLoader(Thread* self,
9299 const std::vector<const DexFile*>& dex_files) {
9300 return CreateWellKnownClassLoader(self,
9301 dex_files,
9302 WellKnownClasses::dalvik_system_PathClassLoader,
9303 nullptr);
9304}
9305
Andreas Gampe8ac75952015-06-02 21:01:45 -07009306void ClassLinker::DropFindArrayClassCache() {
9307 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9308 find_array_class_cache_next_victim_ = 0;
9309}
9310
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009311void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009312 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009313 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009314 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009315 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9316 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009317 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009318 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009319 }
9320 }
9321}
9322
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009323void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9324 for (const ClassLoaderData& data : class_loaders_) {
9325 LinearAlloc* alloc = data.allocator;
9326 if (alloc != nullptr && !visitor->Visit(alloc)) {
9327 break;
9328 }
9329 }
9330}
9331
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009332void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9333 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009334 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009335 Thread* const self = Thread::Current();
9336 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009337 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009338 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009339 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009340 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9341 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009342 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009343 }
9344}
9345
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009346void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009347 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009348 std::vector<ClassLoaderData> to_delete;
9349 // Do the delete outside the lock to avoid lock violation in jit code cache.
9350 {
9351 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9352 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9353 const ClassLoaderData& data = *it;
9354 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009355 ObjPtr<mirror::ClassLoader> class_loader =
9356 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009357 if (class_loader != nullptr) {
9358 ++it;
9359 } else {
9360 VLOG(class_linker) << "Freeing class loader";
9361 to_delete.push_back(data);
9362 it = class_loaders_.erase(it);
9363 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009364 }
9365 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009366 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009367 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009368 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009369 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009370}
9371
Vladimir Marko21300532017-01-24 18:06:55 +00009372class GetResolvedClassesVisitor : public ClassVisitor {
9373 public:
9374 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9375 : result_(result),
9376 ignore_boot_classes_(ignore_boot_classes),
9377 last_resolved_classes_(result->end()),
9378 last_dex_file_(nullptr),
9379 vlog_is_on_(VLOG_IS_ON(class_linker)),
9380 extra_stats_(),
9381 last_extra_stats_(extra_stats_.end()) { }
9382
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009383 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009384 if (!klass->IsProxyClass() &&
9385 !klass->IsArrayClass() &&
9386 klass->IsResolved() &&
9387 !klass->IsErroneousResolved() &&
9388 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9389 const DexFile& dex_file = klass->GetDexFile();
9390 if (&dex_file != last_dex_file_) {
9391 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009392 DexCacheResolvedClasses resolved_classes(
9393 dex_file.GetLocation(),
9394 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9395 dex_file.GetLocationChecksum(),
9396 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009397 last_resolved_classes_ = result_->find(resolved_classes);
9398 if (last_resolved_classes_ == result_->end()) {
9399 last_resolved_classes_ = result_->insert(resolved_classes).first;
9400 }
9401 }
9402 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9403 if (UNLIKELY(vlog_is_on_) && added) {
9404 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9405 if (last_extra_stats_ == extra_stats_.end() ||
9406 last_extra_stats_->first != resolved_classes) {
9407 last_extra_stats_ = extra_stats_.find(resolved_classes);
9408 if (last_extra_stats_ == extra_stats_.end()) {
9409 last_extra_stats_ =
9410 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9411 }
9412 }
9413 }
9414 }
9415 return true;
9416 }
9417
9418 void PrintStatistics() const {
9419 if (vlog_is_on_) {
9420 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9421 auto it = extra_stats_.find(std::addressof(resolved_classes));
9422 DCHECK(it != extra_stats_.end());
9423 const ExtraStats& extra_stats = it->second;
9424 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9425 << " has " << resolved_classes.GetClasses().size() << " / "
9426 << extra_stats.number_of_class_defs_ << " resolved classes";
9427 }
9428 }
9429 }
9430
9431 private:
9432 struct ExtraStats {
9433 explicit ExtraStats(uint32_t number_of_class_defs)
9434 : number_of_class_defs_(number_of_class_defs) {}
9435 uint32_t number_of_class_defs_;
9436 };
9437
9438 std::set<DexCacheResolvedClasses>* result_;
9439 bool ignore_boot_classes_;
9440 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9441 const DexFile* last_dex_file_;
9442
9443 // Statistics.
9444 bool vlog_is_on_;
9445 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9446 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9447};
9448
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009449std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009450 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009451 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009452 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009453 std::set<DexCacheResolvedClasses> ret;
9454 VLOG(class_linker) << "Collecting resolved classes";
9455 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009456 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9457 VisitClasses(&visitor);
9458 if (VLOG_IS_ON(class_linker)) {
9459 visitor.PrintStatistics();
9460 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009461 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009462 return ret;
9463}
9464
Mathieu Chartier65975772016-08-05 10:46:36 -07009465class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9466 public:
9467 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9468 : method_(method),
9469 pointer_size_(pointer_size) {}
9470
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009471 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009472 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9473 holder_ = klass;
9474 }
9475 // Return false to stop searching if holder_ is not null.
9476 return holder_ == nullptr;
9477 }
9478
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009479 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009480 const ArtMethod* const method_;
9481 const PointerSize pointer_size_;
9482};
9483
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009484ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009485 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9486 CHECK(method->IsCopied());
9487 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9488 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009489 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009490}
9491
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009492ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9493 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009494 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009495 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009496 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009497}
9498
Roland Levillain0e840272018-08-23 19:55:30 +01009499// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009500template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009501 uint32_t method_idx,
9502 Handle<mirror::DexCache> dex_cache,
9503 Handle<mirror::ClassLoader> class_loader,
9504 ArtMethod* referrer,
9505 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009506template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009507 uint32_t method_idx,
9508 Handle<mirror::DexCache> dex_cache,
9509 Handle<mirror::ClassLoader> class_loader,
9510 ArtMethod* referrer,
9511 InvokeType type);
9512
Roland Levillain0e840272018-08-23 19:55:30 +01009513// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009514template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009515 Thread* self,
9516 ObjPtr<mirror::Class> java_lang_Class,
9517 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009518template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009519 Thread* self,
9520 ObjPtr<mirror::Class> java_lang_Class,
9521 uint32_t class_size);
9522
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009523} // namespace art