blob: a2e26866d11277b80d7a6654c04392e3808d7cff [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"
David Sehrb2ec9f52018-02-21 13:20:31 -080059#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080060#include "dex/dex_file-inl.h"
61#include "dex/dex_file_exception_helpers.h"
62#include "dex/dex_file_loader.h"
David Sehr0225f8e2018-01-31 08:52:24 +000063#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070064#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070065#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070066#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070067#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080068#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000069#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070070#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070071#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070072#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070073#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000074#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070075#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070076#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070077#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080078#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070079#include "imt_conflict_table.h"
80#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070081#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070082#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000083#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080084#include "jit/jit.h"
85#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010086#include "jni/java_vm_ext.h"
87#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070088#include "linear_alloc.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000089#include "mirror/call_site.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080090#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070091#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070092#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080093#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070094#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070095#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +010096#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070097#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080098#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070099#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100100#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000101#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700102#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800103#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000104#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700105#include "mirror/object_array-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800106#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700107#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800108#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700109#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100110#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700111#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700112#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700113#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700114#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700115#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700116#include "oat_file_assistant.h"
117#include "oat_file_manager.h"
118#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700119#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700120#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800121#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700122#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700123#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700124#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700125#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100126#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800127#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700128#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700129
130namespace art {
131
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800132using android::base::StringPrintf;
133
Mathieu Chartierc7853442015-03-27 14:35:38 -0700134static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700135static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700136
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137static void ThrowNoClassDefFoundError(const char* fmt, ...)
138 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700139 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700140static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700141 va_list args;
142 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000144 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800145 va_end(args);
146}
147
Andreas Gampe99babb62015-11-02 16:20:00 -0800148static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700149 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700150 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700151 StackHandleScope<1> hs(self);
152 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700153 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700154 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700155
156 if (exception_class == nullptr) {
157 // No exc class ~ no <init>-with-string.
158 CHECK(self->IsExceptionPending());
159 self->ClearException();
160 return false;
161 }
162
Vladimir Markoba118822017-06-12 15:41:56 +0100163 ArtMethod* exception_init_method = exception_class->FindConstructor(
164 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700165 return exception_init_method != nullptr;
166}
167
Alex Lightd6251582016-10-31 11:12:30 -0700168static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700169 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700170 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
171 if (ext == nullptr) {
172 return nullptr;
173 } else {
174 return ext->GetVerifyError();
175 }
176}
177
178// Helper for ThrowEarlierClassFailure. Throws the stored error.
179static void HandleEarlierVerifyError(Thread* self,
180 ClassLinker* class_linker,
181 ObjPtr<mirror::Class> c)
182 REQUIRES_SHARED(Locks::mutator_lock_) {
183 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800184 DCHECK(obj != nullptr);
185 self->AssertNoPendingException();
186 if (obj->IsClass()) {
187 // Previous error has been stored as class. Create a new exception of that type.
188
189 // It's possible the exception doesn't have a <init>(String).
190 std::string temp;
191 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
192
193 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700194 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800195 } else {
196 self->ThrowNewException(descriptor, nullptr);
197 }
198 } else {
199 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700200 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800201 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700202 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800203 CHECK(throwable_class->IsAssignableFrom(error_class));
204 self->SetException(obj->AsThrowable());
205 }
206 self->AssertPendingException();
207}
208
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700209void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700210 // The class failed to initialize on a previous attempt, so we want to throw
211 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
212 // failed in verification, in which case v2 5.4.1 says we need to re-throw
213 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800214 Runtime* const runtime = Runtime::Current();
215 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700216 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700217 if (GetVerifyError(c) != nullptr) {
218 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800219 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700220 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800221 } else {
222 extra = verify_error->AsThrowable()->Dump();
223 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700224 }
David Sehr709b0702016-10-13 09:12:37 -0700225 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
226 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700227 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700228
David Sehr709b0702016-10-13 09:12:37 -0700229 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800230 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800231 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700232 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700233 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000234 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700235 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700236 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800237 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800238 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800239 }
Alex Lightd6251582016-10-31 11:12:30 -0700240 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
241 // might have meant to go down the earlier if statement with the original error but it got
242 // swallowed by the OOM so we end up here.
243 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800244 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
245 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
246 // exception will be a cause.
247 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700248 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700249 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700250 }
251}
252
Brian Carlstromb23eab12014-10-08 17:55:21 -0700253static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700254 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700255 if (VLOG_IS_ON(class_linker)) {
256 std::string temp;
257 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000258 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700259 }
260}
261
262static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700263 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700264 Thread* self = Thread::Current();
265 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700266
267 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700268 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700269
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800270 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
271 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
272 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800273 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800274 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
275 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
276 // could have caused the error.
277 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
278 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
279 << " failed initialization: "
280 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800281 }
282
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700283 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700284 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
285 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700286
Elliott Hughesa4f94742012-05-29 16:28:38 -0700287 // We only wrap non-Error exceptions; an Error can just be used as-is.
288 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000289 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700290 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700291 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700292}
293
Fred Shih381e4ca2014-08-25 17:24:27 -0700294// Gap between two fields in object layout.
295struct FieldGap {
296 uint32_t start_offset; // The offset from the start of the object.
297 uint32_t size; // The gap size of 1, 2, or 4 bytes.
298};
299struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800300 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700301 }
302 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
303 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800304 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700305 // Note that the priority queue returns the largest element, so operator()
306 // should return true if lhs is less than rhs.
307 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700308 }
309};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700310typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700311
312// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800313static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700314 DCHECK(gaps != nullptr);
315
316 uint32_t current_offset = gap_start;
317 while (current_offset != gap_end) {
318 size_t remaining = gap_end - current_offset;
319 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
320 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
321 current_offset += sizeof(uint32_t);
322 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
323 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
324 current_offset += sizeof(uint16_t);
325 } else {
326 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
327 current_offset += sizeof(uint8_t);
328 }
329 DCHECK_LE(current_offset, gap_end) << "Overran gap";
330 }
331}
332// Shuffle fields forward, making use of gaps whenever possible.
333template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000334static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700335 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700336 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700337 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700338 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700339 DCHECK(current_field_idx != nullptr);
340 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700341 DCHECK(gaps != nullptr);
342 DCHECK(field_offset != nullptr);
343
344 DCHECK(IsPowerOfTwo(n));
345 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700346 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700347 Primitive::Type type = field->GetTypeAsPrimitiveType();
348 if (Primitive::ComponentSize(type) < n) {
349 break;
350 }
351 if (!IsAligned<n>(field_offset->Uint32Value())) {
352 MemberOffset old_offset = *field_offset;
353 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
354 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
355 }
David Sehr709b0702016-10-13 09:12:37 -0700356 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700357 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700358 if (!gaps->empty() && gaps->top().size >= n) {
359 FieldGap gap = gaps->top();
360 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100361 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700362 field->SetOffset(MemberOffset(gap.start_offset));
363 if (gap.size > n) {
364 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
365 }
366 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100367 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700368 field->SetOffset(*field_offset);
369 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
370 }
371 ++(*current_field_idx);
372 }
373}
374
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800375ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700376 : boot_class_table_(new ClassTable()),
377 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800378 class_roots_(nullptr),
379 array_iftable_(nullptr),
380 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700381 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000382 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700383 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800384 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800385 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100386 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800387 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700388 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700389 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
390 // For CHA disabled during Aot, see b/34193647.
391
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700392 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700393 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
394 "Array cache size wrong.");
395 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700396}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700397
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800398void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700399 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800400 if (c2 == nullptr) {
401 LOG(FATAL) << "Could not find class " << descriptor;
402 UNREACHABLE();
403 }
404 if (c1.Get() != c2) {
405 std::ostringstream os1, os2;
406 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
407 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
408 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
409 << ". This is most likely the result of a broken build. Make sure that "
410 << "libcore and art projects match.\n\n"
411 << os1.str() << "\n\n" << os2.str();
412 UNREACHABLE();
413 }
414}
415
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800416bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
417 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800418 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700419
Mathieu Chartiere401d142015-04-22 13:56:20 -0700420 Thread* const self = Thread::Current();
421 Runtime* const runtime = Runtime::Current();
422 gc::Heap* const heap = runtime->GetHeap();
423
Jeff Haodcdc85b2015-12-04 14:06:18 -0800424 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700425 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700426
Mathieu Chartiere401d142015-04-22 13:56:20 -0700427 // Use the pointer size from the runtime since we are probably creating the image.
428 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
429
Elliott Hughes30646832011-10-13 16:59:46 -0700430 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700431 // 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 -0800432 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700433 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700434 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700435 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700436 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800437 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700438 mirror::Class::SetClassClass(java_lang_Class.Get());
439 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700440 if (kUseBakerReadBarrier) {
441 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800442 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700443 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700444 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800445 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700446 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700447
Elliott Hughes418d20f2011-09-22 14:00:39 -0700448 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700449 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700450 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700451 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700453
Ian Rogers23435d02012-09-24 11:23:12 -0700454 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700455 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700456 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800457 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700458 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700459 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000460 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700461
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700462 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800463 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
464 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
465 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
466 java_lang_Object.Get(),
467 java_lang_Object->GetObjectSize(),
468 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700469
Igor Murashkin86083f72017-10-27 10:59:04 -0700470 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000471 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700472 // It might seem the lock here is unnecessary, however all the SubtypeCheck
473 // functions are annotated to require locks all the way down.
474 //
475 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
476 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000477 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
478 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700479 }
480
Ian Rogers23435d02012-09-24 11:23:12 -0700481 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700482 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700483 AllocClass(self, java_lang_Class.Get(),
484 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700486
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700487 // Setup the char (primitive) class to be used for char[].
488 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700489 AllocClass(self, java_lang_Class.Get(),
490 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700491 // The primitive char class won't be initialized by
492 // InitializePrimitiveClass until line 459, but strings (and
493 // internal char arrays) will be allocated before that and the
494 // component size, which is computed from the primitive type, needs
495 // to be set here.
496 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700497
Ian Rogers23435d02012-09-24 11:23:12 -0700498 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700499 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700500 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700501 char_array_class->SetComponentType(char_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700502
Ian Rogers23435d02012-09-24 11:23:12 -0700503 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700504 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700505 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700506 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 mirror::String::SetClass(java_lang_String.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000508 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400509
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700510 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700511 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700512 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700513 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000514 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700515
Ian Rogers23435d02012-09-24 11:23:12 -0700516 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700517 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100518 mirror::ObjectArray<mirror::Class>::Alloc(self,
519 object_array_class.Get(),
520 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700521 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100522 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
523 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
524 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
525 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
526 SetClassRoot(ClassRoot::kCharArrayClass, char_array_class.Get());
527 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
528 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529
Mathieu Chartier6beced42016-11-15 15:51:31 -0800530 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
531 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
532
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700533 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100534 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
535 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
536 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
537 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
538 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
539 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
540 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
541 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542
Ian Rogers23435d02012-09-24 11:23:12 -0700543 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700544 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545
Ian Rogers23435d02012-09-24 11:23:12 -0700546 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700547 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700548 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100549 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100550 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700551
Mathieu Chartierc7853442015-03-27 14:35:38 -0700552 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
553 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700554 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100555 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100556 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700557
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700558 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700559
Ian Rogers52813c92012-10-11 11:50:38 -0700560 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700561 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700562 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100563 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100564 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700565 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000566 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567
Alex Lightd6251582016-10-31 11:12:30 -0700568
569 // Setup dalvik.system.ClassExt
570 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
571 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100572 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Alex Lightd6251582016-10-31 11:12:30 -0700573 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000574 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700575
Mathieu Chartier66f19252012-09-18 08:57:04 -0700576 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700577 Handle<mirror::Class> object_array_string(hs.NewHandle(
578 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700579 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700580 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100581 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700582
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000583 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700584 // Create runtime resolution and imt conflict methods.
585 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000586 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
587 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700588
Ian Rogers23435d02012-09-24 11:23:12 -0700589 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
590 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
591 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800592 if (boot_class_path.empty()) {
593 *error_msg = "Boot classpath is empty.";
594 return false;
595 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800596 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800597 if (dex_file.get() == nullptr) {
598 *error_msg = "Null dex file.";
599 return false;
600 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700601 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800602 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700603 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604
605 // now we can use FindSystemClass
606
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700607 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700608 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100609 SetClassRoot(ClassRoot::kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700610
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700611 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
612 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700613 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800614 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700615 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700616 quick_resolution_trampoline_ = GetQuickResolutionStub();
617 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
618 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700619 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700620
Alex Lightd6251582016-10-31 11:12:30 -0700621 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000622 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800623 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700624 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000625 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800626 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000627 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800628 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700629 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000630 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700631 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
632 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633
Ian Rogers23435d02012-09-24 11:23:12 -0700634 // Setup the primitive array type classes - can't be done until Object has a vtable.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100635 SetClassRoot(ClassRoot::kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700636
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100637 SetClassRoot(ClassRoot::kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700638
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800639 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700640
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100641 SetClassRoot(ClassRoot::kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800643 CheckSystemClass(self, int_array_class, "[I");
644 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700645
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100646 SetClassRoot(ClassRoot::kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700647
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100648 SetClassRoot(ClassRoot::kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800650 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
651 // in class_table_.
652 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700653
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800654 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
655 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656
Ian Rogers23435d02012-09-24 11:23:12 -0700657 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700658 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800659 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700660 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800661 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700662 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
663 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700664 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
665 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700667 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
668 // suspension.
669 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000670 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700671 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000672 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700673 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000674 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700675 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000676 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700677
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700678 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100679 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700680
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800681 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700682
Ian Rogers23435d02012-09-24 11:23:12 -0700683 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100684 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
685 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700686
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700687 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700688 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
689 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100690 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700691
692 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700693 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
694 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100695 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700696
697 // Create java.lang.reflect.Constructor.class root and array root.
698 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
699 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100700 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700701 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
702 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100703 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700704
705 // Create java.lang.reflect.Method.class root and array root.
706 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
707 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100708 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700709 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
710 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100711 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700712
Orion Hodson005ac512017-10-24 15:43:43 +0100713 // Create java.lang.invoke.CallSite.class root
714 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
715 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100716 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100717
Narayan Kamathafa48272016-08-03 12:46:58 +0100718 // Create java.lang.invoke.MethodType.class root
719 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
720 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100721 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100722
723 // Create java.lang.invoke.MethodHandleImpl.class root
724 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
725 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100726 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100727 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100728
Orion Hodsonc069a302017-01-18 09:23:12 +0000729 // Create java.lang.invoke.MethodHandles.Lookup.class root
730 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
731 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100732 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000733
Orion Hodson005ac512017-10-24 15:43:43 +0100734 // Create java.lang.invoke.VarHandle.class root
735 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000736 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100737 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100738
739 // Create java.lang.invoke.FieldVarHandle.class root
740 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
741 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100742 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100743
744 // Create java.lang.invoke.ArrayElementVarHandle.class root
745 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
746 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100747 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100748
749 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
750 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
751 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100752 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100753
754 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
755 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
756 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100757 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000758
Narayan Kamath000e1882016-10-24 17:14:25 +0100759 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
760 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100761 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100762 mirror::EmulatedStackFrame::SetClass(class_root);
763
Brian Carlstrom1f870082011-08-23 16:02:11 -0700764 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700765 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000766 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800767 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700768 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700769 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
770 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700771 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700772 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700773 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700774 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700775 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700776 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700777 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700778 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700779 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700780 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700781 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700782 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700783
Ian Rogers23435d02012-09-24 11:23:12 -0700784 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700785 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700786 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700787 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100788 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700789
jeffhao8cd6dda2012-02-22 10:15:34 -0800790 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700791 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100792 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
793 mirror::Throwable::SetClass(GetClassRoot(ClassRoot::kJavaLangThrowable, this));
794 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700795 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100796 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
797 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
798 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700799 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100800 mirror::StackTraceElement::SetClass(GetClassRoot(ClassRoot::kJavaLangStackTraceElement, this));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700801
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700802 // Create conflict tables that depend on the class linker.
803 runtime->FixupConflictTables();
804
Ian Rogers98379392014-02-24 16:53:16 -0800805 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700806
Brian Carlstroma004aa92012-02-08 18:05:09 -0800807 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800808
809 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700810}
811
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700812static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
813 REQUIRES_SHARED(Locks::mutator_lock_) {
814 // Find String.<init> -> StringFactory bindings.
815 ObjPtr<mirror::Class> string_factory_class =
816 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
817 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100818 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700819 WellKnownClasses::InitStringInit(string_class, string_factory_class);
820 // Update the primordial thread.
821 self->InitStringEntryPoints();
822}
823
Ian Rogers98379392014-02-24 16:53:16 -0800824void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800825 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700826
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700827 CreateStringInitBindings(self, this);
828
Brian Carlstrom16192862011-09-12 17:50:06 -0700829 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700830 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700831 // as the types of the field can't be resolved prior to the runtime being
832 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700833 StackHandleScope<2> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100834 Handle<mirror::Class> java_lang_ref_Reference =
835 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700836 Handle<mirror::Class> java_lang_ref_FinalizerReference =
837 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800838
Mathieu Chartierc7853442015-03-27 14:35:38 -0700839 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700840 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
841 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700842
Mathieu Chartierc7853442015-03-27 14:35:38 -0700843 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700844 CHECK_STREQ(queue->GetName(), "queue");
845 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700846
Mathieu Chartierc7853442015-03-27 14:35:38 -0700847 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700848 CHECK_STREQ(queueNext->GetName(), "queueNext");
849 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700850
Mathieu Chartierc7853442015-03-27 14:35:38 -0700851 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700852 CHECK_STREQ(referent->GetName(), "referent");
853 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700854
Mathieu Chartierc7853442015-03-27 14:35:38 -0700855 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700856 CHECK_STREQ(zombie->GetName(), "zombie");
857 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700858
Brian Carlstroma663ea52011-08-19 23:33:41 -0700859 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100860 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700861 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700862 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700863 CHECK(klass != nullptr);
864 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700865 // note SetClassRoot does additional validation.
866 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700867 }
868
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700869 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700870
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700871 // disable the slow paths in FindClass and CreatePrimitiveClass now
872 // that Object, Class, and Object[] are setup
873 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700874
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800875 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700876}
877
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700878void ClassLinker::RunRootClinits() {
879 Thread* self = Thread::Current();
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100880 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
881 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700882 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700883 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100884 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700885 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700886 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700887 }
888 }
889}
890
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200891// Set image methods' entry point to interpreter.
892class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
893 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700894 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200895 : image_pointer_size_(image_pointer_size) {}
896
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700897 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200898 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
899 CHECK(method->GetDeclaringClass() != nullptr);
900 }
901 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
902 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
903 image_pointer_size_);
904 }
905 }
906
907 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700908 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200909
910 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
911};
912
Jeff Haodcdc85b2015-12-04 14:06:18 -0800913struct TrampolineCheckData {
914 const void* quick_resolution_trampoline;
915 const void* quick_imt_conflict_trampoline;
916 const void* quick_generic_jni_trampoline;
917 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700918 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800919 ArtMethod* m;
920 bool error;
921};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800922
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800923bool ClassLinker::InitFromBootImage(std::string* error_msg) {
924 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700925 CHECK(!init_done_);
926
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700927 Runtime* const runtime = Runtime::Current();
928 Thread* const self = Thread::Current();
929 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800930 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
931 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700932 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
933 if (!ValidPointerSize(pointer_size_unchecked)) {
934 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800935 return false;
936 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700937 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800938 if (!runtime->IsAotCompiler()) {
939 // Only the Aot compiler supports having an image with a different pointer size than the
940 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
941 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700942 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800943 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700944 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800945 sizeof(void*));
946 return false;
947 }
948 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800949 std::vector<const OatFile*> oat_files =
950 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
951 DCHECK(!oat_files.empty());
952 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800953 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
954 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700955 GetStoreValueByKey(OatHeader::kImageLocationKey);
956 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800957 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
958 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
959 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
960 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
961 if (kIsDebugBuild) {
962 // Check that the other images use the same trampoline.
963 for (size_t i = 1; i < oat_files.size(); ++i) {
964 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
965 const void* ith_quick_resolution_trampoline =
966 ith_oat_header.GetQuickResolutionTrampoline();
967 const void* ith_quick_imt_conflict_trampoline =
968 ith_oat_header.GetQuickImtConflictTrampoline();
969 const void* ith_quick_generic_jni_trampoline =
970 ith_oat_header.GetQuickGenericJniTrampoline();
971 const void* ith_quick_to_interpreter_bridge_trampoline =
972 ith_oat_header.GetQuickToInterpreterBridge();
973 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
974 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
975 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
976 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
977 // Make sure that all methods in this image do not contain those trampolines as
978 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
979 TrampolineCheckData data;
980 data.error = false;
981 data.pointer_size = GetImagePointerSize();
982 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
983 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
984 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
985 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
986 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700987 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
988 if (obj->IsClass()) {
989 ObjPtr<mirror::Class> klass = obj->AsClass();
990 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
991 const void* entrypoint =
992 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
993 if (entrypoint == data.quick_resolution_trampoline ||
994 entrypoint == data.quick_imt_conflict_trampoline ||
995 entrypoint == data.quick_generic_jni_trampoline ||
996 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
997 data.m = &m;
998 data.error = true;
999 return;
1000 }
1001 }
1002 }
1003 };
1004 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001005 if (data.error) {
1006 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001007 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001008 *error_msg = "Found an ArtMethod with a bad entrypoint";
1009 return false;
1010 }
1011 }
1012 }
1013 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001014
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001015 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1016 down_cast<mirror::ObjectArray<mirror::Class>*>(
1017 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001018 mirror::Class::SetClassClass(GetClassRoot(ClassRoot::kJavaLangClass, this));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001019
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001020 // Special case of setting up the String class early so that we can test arbitrary objects
1021 // as being Strings or not
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001022 mirror::String::SetClass(GetClassRoot<mirror::String>(this));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001023
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001024 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001025 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001026 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1027 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001028 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1029 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001030
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001031 // reinit array_iftable_ from any array class instance, they should be ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001032 array_iftable_ =
1033 GcRoot<mirror::IfTable>(GetClassRoot(ClassRoot::kObjectArrayClass, this)->GetIfTable());
1034 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(ClassRoot::kBooleanArrayClass, this)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001035 // String class root was set above
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001036 mirror::Throwable::SetClass(GetClassRoot(ClassRoot::kJavaLangThrowable, this));
1037 mirror::StackTraceElement::SetClass(GetClassRoot(ClassRoot::kJavaLangStackTraceElement, this));
1038 mirror::EmulatedStackFrame::SetClass(
1039 GetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, this).Ptr());
1040 mirror::ClassExt::SetClass(GetClassRoot(ClassRoot::kDalvikSystemClassExt, this));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001041
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001042 for (gc::space::ImageSpace* image_space : spaces) {
1043 // Boot class loader, use a null handle.
1044 std::vector<std::unique_ptr<const DexFile>> dex_files;
1045 if (!AddImageSpace(image_space,
1046 ScopedNullHandle<mirror::ClassLoader>(),
1047 /*dex_elements*/nullptr,
1048 /*dex_location*/nullptr,
1049 /*out*/&dex_files,
1050 error_msg)) {
1051 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001052 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001053 // Append opened dex files at the end.
1054 boot_dex_files_.insert(boot_dex_files_.end(),
1055 std::make_move_iterator(dex_files.begin()),
1056 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001057 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001058 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1059 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1060 }
Ian Rogers98379392014-02-24 16:53:16 -08001061 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001062
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001063 VLOG(startup) << __FUNCTION__ << " exiting";
1064 return true;
1065}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001066
Jeff Hao5872d7c2016-04-27 11:07:41 -07001067bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001068 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001069 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001070 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1071 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072}
1073
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001074static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1075 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001076 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001077 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001078 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001079 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001080 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001081 DCHECK(dex_file_field != nullptr);
1082 DCHECK(dex_file_name_field != nullptr);
1083 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001084 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001085 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001086 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001087 // Null dex file means it was probably a jar with no dex files, return a null string.
1088 *out_name = nullptr;
1089 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001090 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001091 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001092 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001093 *out_name = name_object->AsString();
1094 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001095 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001096 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001097}
1098
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001099static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001100 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001101 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001102 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001103 DCHECK(out_dex_file_names != nullptr);
1104 DCHECK(error_msg != nullptr);
1105 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001106 StackHandleScope<1> hs(soa.Self());
1107 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Jeff Hao5872d7c2016-04-27 11:07:41 -07001108 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001109 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1110 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001111 *error_msg = StringPrintf("Unknown class loader type %s",
1112 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001113 // Unsupported class loader.
1114 return false;
1115 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001116 // Get element names. Sets error to true on failure.
1117 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1118 REQUIRES_SHARED(Locks::mutator_lock_) {
1119 if (element == nullptr) {
1120 *error_msg = "Null dex element";
1121 *error = true; // Null element is a critical error.
1122 return false; // Had an error, stop the visit.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001123 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001124 ObjPtr<mirror::String> name;
1125 if (!GetDexPathListElementName(element, &name)) {
1126 *error_msg = "Invalid dex path list element";
1127 *error = false; // Invalid element is not a critical error.
1128 return false; // Stop the visit.
1129 }
1130 if (name != nullptr) {
1131 out_dex_file_names->push_front(name.Ptr());
1132 }
1133 return true; // Continue with the next Element.
1134 };
1135 bool error = VisitClassLoaderDexElements(soa, handle, add_element_names, /* error */ false);
1136 if (error) {
1137 // An error occurred during DexPathList Element visiting.
1138 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001139 }
1140 class_loader = class_loader->GetParent();
1141 }
1142 return true;
1143}
1144
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001145class CHAOnDeleteUpdateClassVisitor {
1146 public:
1147 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1148 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1149 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1150 self_(Thread::Current()) {}
1151
1152 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1153 // This class is going to be unloaded. Tell CHA about it.
1154 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1155 return true;
1156 }
1157 private:
1158 const LinearAlloc* allocator_;
1159 const ClassHierarchyAnalysis* cha_;
1160 const PointerSize pointer_size_;
1161 const Thread* self_;
1162};
1163
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001164class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1165 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001166 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001167 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1168
1169 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001170 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001171 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001172 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001173 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001174 }
1175 }
1176
1177 private:
1178 gc::accounting::HeapBitmap* const live_bitmap_;
1179};
1180
Chang Xingba17dbd2017-06-28 21:27:56 +00001181class FixupInternVisitor {
1182 public:
1183 ALWAYS_INLINE ObjPtr<mirror::Object> TryInsertIntern(mirror::Object* obj) const
1184 REQUIRES_SHARED(Locks::mutator_lock_) {
1185 if (obj != nullptr && obj->IsString()) {
1186 const auto intern = Runtime::Current()->GetInternTable()->InternStrong(obj->AsString());
1187 return intern;
1188 }
1189 return obj;
1190 }
1191
1192 ALWAYS_INLINE void VisitRootIfNonNull(
1193 mirror::CompressedReference<mirror::Object>* root) const
1194 REQUIRES_SHARED(Locks::mutator_lock_) {
1195 if (!root->IsNull()) {
1196 VisitRoot(root);
1197 }
1198 }
1199
1200 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1201 REQUIRES_SHARED(Locks::mutator_lock_) {
1202 root->Assign(TryInsertIntern(root->AsMirrorPtr()));
1203 }
1204
1205 // Visit Class Fields
1206 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1207 MemberOffset offset,
1208 bool is_static ATTRIBUTE_UNUSED) const
1209 REQUIRES_SHARED(Locks::mutator_lock_) {
1210 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1211 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1212 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1213 // Updating images, don't do a read barrier.
1214 // Only string fields are fixed, don't do a verify.
1215 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1216 offset);
1217 obj->SetFieldObject<false, false>(offset, TryInsertIntern(ref));
1218 }
1219 }
1220
1221 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1222 ObjPtr<mirror::Reference> ref) const
1223 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1224 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1225 }
1226
1227 void operator()(mirror::Object* obj) const
1228 REQUIRES_SHARED(Locks::mutator_lock_) {
1229 if (obj->IsDexCache()) {
1230 obj->VisitReferences<true, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1231 } else {
1232 // Don't visit native roots for non-dex-cache
1233 obj->VisitReferences<false, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1234 }
1235 }
1236};
1237
Andreas Gampe2af99022017-04-25 08:32:59 -07001238// new_class_set is the set of classes that were read from the class table section in the image.
1239// If there was no class table section, it is null.
1240// Note: using a class here to avoid having to make ClassLinker internals public.
1241class AppImageClassLoadersAndDexCachesHelper {
1242 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001243 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001244 ClassLinker* class_linker,
1245 gc::space::ImageSpace* space,
1246 Handle<mirror::ClassLoader> class_loader,
1247 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001248 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001249 REQUIRES(!Locks::dex_lock_)
1250 REQUIRES_SHARED(Locks::mutator_lock_);
1251};
1252
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001253void AppImageClassLoadersAndDexCachesHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001254 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001255 gc::space::ImageSpace* space,
1256 Handle<mirror::ClassLoader> class_loader,
1257 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001258 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001259 REQUIRES(!Locks::dex_lock_)
1260 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001261 Thread* const self = Thread::Current();
1262 gc::Heap* const heap = Runtime::Current()->GetHeap();
1263 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001264 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001265 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001266 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001267 const size_t num_dex_caches = dex_caches->GetLength();
1268 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001269 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001270 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001271 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001272 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001273 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1274 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001275 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001276 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001277 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001278 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001279 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001280 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001281 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001282 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001283 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001284 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001285 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001286 DCHECK(it != new_class_set->end());
1287 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001288 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001289 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001290 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001291 DCHECK(it2 != new_class_set->end());
1292 DCHECK_EQ(it2->Read(), super_class);
1293 }
1294 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1295 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001296 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1297 if (!class_linker->IsQuickResolutionStub(code) &&
1298 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001299 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001300 !m.IsNative()) {
1301 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001302 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001303 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001304 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1305 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001306 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1307 if (!class_linker->IsQuickResolutionStub(code) &&
1308 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001309 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001310 !m.IsNative()) {
1311 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001312 }
1313 }
1314 }
1315 }
1316 }
1317 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001318 }
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001319 if (ClassLinker::kAppImageMayContainStrings) {
Chang Xingba17dbd2017-06-28 21:27:56 +00001320 // Fixup all the literal strings happens at app images which are supposed to be interned.
1321 ScopedTrace timing("Fixup String Intern in image and dex_cache");
1322 const auto& image_header = space->GetImageHeader();
1323 const auto bitmap = space->GetMarkBitmap(); // bitmap of objects
1324 const uint8_t* target_base = space->GetMemMap()->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001325 const ImageSection& objects_section = image_header.GetObjectsSection();
Chang Xingba17dbd2017-06-28 21:27:56 +00001326
1327 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1328 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1329
1330 FixupInternVisitor fixup_intern_visitor;
1331 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_intern_visitor);
1332 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001333 if (kVerifyArtMethodDeclaringClasses) {
1334 ScopedTrace timing("Verify declaring classes");
1335 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1336 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001337 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001338 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001339}
1340
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001341// Update the class loader. Should only be used on classes in the image space.
1342class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001343 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001344 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001345 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001346 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001347
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001348 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001349 // Do not update class loader for boot image classes where the app image
1350 // class loader is only the initiating loader but not the defining loader.
1351 if (klass->GetClassLoader() != nullptr) {
1352 klass->SetClassLoader(class_loader_);
1353 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001354 return true;
1355 }
1356
1357 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001358 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001359};
1360
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001361static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1362 const char* location,
1363 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001364 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001365 DCHECK(error_msg != nullptr);
1366 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001367 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001368 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001369 return std::unique_ptr<const DexFile>();
1370 }
1371 std::string inner_error_msg;
1372 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1373 if (dex_file == nullptr) {
1374 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1375 location,
1376 oat_file->GetLocation().c_str(),
1377 inner_error_msg.c_str());
1378 return std::unique_ptr<const DexFile>();
1379 }
1380
1381 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1382 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1383 location,
1384 dex_file->GetLocationChecksum(),
1385 oat_dex_file->GetDexFileLocationChecksum());
1386 return std::unique_ptr<const DexFile>();
1387 }
1388 return dex_file;
1389}
1390
1391bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1392 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1393 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001394 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001395 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001396 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001397 DCHECK(dex_caches_object != nullptr);
1398 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1399 dex_caches_object->AsObjectArray<mirror::DexCache>();
1400 const OatFile* oat_file = space->GetOatFile();
1401 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001402 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001403 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1404 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1405 dex_file_location.c_str(),
1406 error_msg);
1407 if (dex_file == nullptr) {
1408 return false;
1409 }
1410 dex_cache->SetDexFile(dex_file.get());
1411 out_dex_files->push_back(std::move(dex_file));
1412 }
1413 return true;
1414}
1415
Andreas Gampe0793bec2016-12-01 11:37:33 -08001416// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1417// together and caches some intermediate results.
1418class ImageSanityChecks FINAL {
1419 public:
1420 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1421 REQUIRES_SHARED(Locks::mutator_lock_) {
1422 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001423 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1424 DCHECK(obj != nullptr);
1425 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1426 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1427 if (obj->IsClass()) {
1428 auto klass = obj->AsClass();
1429 for (ArtField& field : klass->GetIFields()) {
1430 CHECK_EQ(field.GetDeclaringClass(), klass);
1431 }
1432 for (ArtField& field : klass->GetSFields()) {
1433 CHECK_EQ(field.GetDeclaringClass(), klass);
1434 }
1435 const auto pointer_size = isc.pointer_size_;
1436 for (auto& m : klass->GetMethods(pointer_size)) {
1437 isc.SanityCheckArtMethod(&m, klass);
1438 }
1439 auto* vtable = klass->GetVTable();
1440 if (vtable != nullptr) {
1441 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1442 }
1443 if (klass->ShouldHaveImt()) {
1444 ImTable* imt = klass->GetImt(pointer_size);
1445 for (size_t i = 0; i < ImTable::kSize; ++i) {
1446 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1447 }
1448 }
1449 if (klass->ShouldHaveEmbeddedVTable()) {
1450 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1451 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1452 }
1453 }
1454 mirror::IfTable* iftable = klass->GetIfTable();
1455 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1456 if (iftable->GetMethodArrayCount(i) > 0) {
1457 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1458 }
1459 }
1460 }
1461 };
1462 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001463 }
1464
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001465 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1466 ClassLinker* class_linker,
1467 mirror::MethodDexCacheType* arr,
1468 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001469 REQUIRES_SHARED(Locks::mutator_lock_) {
1470 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001471 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001472 }
1473
Andreas Gampe0793bec2016-12-01 11:37:33 -08001474 private:
1475 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1476 : spaces_(heap->GetBootImageSpaces()),
1477 pointer_size_(class_linker->GetImagePointerSize()) {
1478 space_begin_.reserve(spaces_.size());
1479 method_sections_.reserve(spaces_.size());
1480 runtime_method_sections_.reserve(spaces_.size());
1481 for (gc::space::ImageSpace* space : spaces_) {
1482 space_begin_.push_back(space->Begin());
1483 auto& header = space->GetImageHeader();
1484 method_sections_.push_back(&header.GetMethodsSection());
1485 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1486 }
1487 }
1488
1489 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1490 REQUIRES_SHARED(Locks::mutator_lock_) {
1491 if (m->IsRuntimeMethod()) {
1492 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1493 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1494 } else if (m->IsCopied()) {
1495 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1496 } else if (expected_class != nullptr) {
1497 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1498 }
1499 if (!spaces_.empty()) {
1500 bool contains = false;
1501 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1502 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1503 contains = method_sections_[i]->Contains(offset) ||
1504 runtime_method_sections_[i]->Contains(offset);
1505 }
1506 CHECK(contains) << m << " not found";
1507 }
1508 }
1509
1510 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1511 ObjPtr<mirror::Class> expected_class)
1512 REQUIRES_SHARED(Locks::mutator_lock_) {
1513 CHECK(arr != nullptr);
1514 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1515 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1516 // expected_class == null means we are a dex cache.
1517 if (expected_class != nullptr) {
1518 CHECK(method != nullptr);
1519 }
1520 if (method != nullptr) {
1521 SanityCheckArtMethod(method, expected_class);
1522 }
1523 }
1524 }
1525
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001526 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001527 REQUIRES_SHARED(Locks::mutator_lock_) {
1528 CHECK_EQ(arr != nullptr, size != 0u);
1529 if (arr != nullptr) {
1530 bool contains = false;
1531 for (auto space : spaces_) {
1532 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001533 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001534 contains = true;
1535 break;
1536 }
1537 }
1538 CHECK(contains);
1539 }
1540 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001541 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1542 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001543 // expected_class == null means we are a dex cache.
1544 if (method != nullptr) {
1545 SanityCheckArtMethod(method, nullptr);
1546 }
1547 }
1548 }
1549
1550 const std::vector<gc::space::ImageSpace*>& spaces_;
1551 const PointerSize pointer_size_;
1552
1553 // Cached sections from the spaces.
1554 std::vector<const uint8_t*> space_begin_;
1555 std::vector<const ImageSection*> method_sections_;
1556 std::vector<const ImageSection*> runtime_method_sections_;
1557};
1558
Andreas Gampebe7af222017-07-25 09:57:28 -07001559static void VerifyAppImage(const ImageHeader& header,
1560 const Handle<mirror::ClassLoader>& class_loader,
1561 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1562 ClassTable* class_table, gc::space::ImageSpace* space)
1563 REQUIRES_SHARED(Locks::mutator_lock_) {
1564 {
1565 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1566 public:
1567 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1568
1569 virtual void Visit(ArtMethod* method)
1570 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1571 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1572 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1573 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1574 }
1575 }
1576
1577 private:
1578 ClassTable* const table_;
1579 };
1580 VerifyClassInTableArtMethodVisitor visitor(class_table);
1581 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1582 }
1583 {
1584 // Verify that all direct interfaces of classes in the class table are also resolved.
1585 std::vector<ObjPtr<mirror::Class>> classes;
1586 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1587 REQUIRES_SHARED(Locks::mutator_lock_) {
1588 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1589 classes.push_back(klass);
1590 }
1591 return true;
1592 };
1593 class_table->Visit(verify_direct_interfaces_in_table);
1594 Thread* self = Thread::Current();
1595 for (ObjPtr<mirror::Class> klass : classes) {
1596 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1597 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1598 << klass->PrettyDescriptor() << " iface #" << i;
1599 }
1600 }
1601 }
1602 // Check that all non-primitive classes in dex caches are also in the class table.
1603 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1604 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1605 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1606 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1607 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1608 if (klass != nullptr && !klass->IsPrimitive()) {
1609 CHECK(class_table->Contains(klass))
1610 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1611 }
1612 }
1613 }
1614}
1615
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001616bool ClassLinker::AddImageSpace(
1617 gc::space::ImageSpace* space,
1618 Handle<mirror::ClassLoader> class_loader,
1619 jobjectArray dex_elements,
1620 const char* dex_location,
1621 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1622 std::string* error_msg) {
1623 DCHECK(out_dex_files != nullptr);
1624 DCHECK(error_msg != nullptr);
1625 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001626 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001627 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001628 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001629 DCHECK(dex_caches_object != nullptr);
1630 Runtime* const runtime = Runtime::Current();
1631 gc::Heap* const heap = runtime->GetHeap();
1632 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001633 // Check that the image is what we are expecting.
1634 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1635 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1636 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1637 image_pointer_size_);
1638 return false;
1639 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001640 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1641 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1642 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1643 expected_image_roots,
1644 header.GetImageRoots()->GetLength());
1645 return false;
1646 }
1647 StackHandleScope<3> hs(self);
1648 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1649 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1650 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1651 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1652 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1653 "Class loader should be the last image root.");
1654 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1655 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001656 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001657 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001658 *error_msg = StringPrintf("Expected %d class roots but got %d",
1659 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001660 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001661 return false;
1662 }
1663 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001664 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1665 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1666 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001667 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1668 return false;
1669 }
1670 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001671 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001672 if (oat_file->GetOatHeader().GetDexFileCount() !=
1673 static_cast<uint32_t>(dex_caches->GetLength())) {
1674 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1675 "image";
1676 return false;
1677 }
1678
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001679 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001680 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1681 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001682 // TODO: Only store qualified paths.
1683 // If non qualified, qualify it.
1684 if (dex_file_location.find('/') == std::string::npos) {
1685 std::string dex_location_path = dex_location;
1686 const size_t pos = dex_location_path.find_last_of('/');
1687 CHECK_NE(pos, std::string::npos);
1688 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1689 dex_file_location = dex_location_path + dex_file_location;
1690 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001691 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1692 dex_file_location.c_str(),
1693 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001694 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001695 return false;
1696 }
1697
1698 if (app_image) {
1699 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1700 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001701 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001702 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001703 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001704 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001705 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001706 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001707 }
1708 }
1709 } else {
1710 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001711 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
1712 this,
1713 dex_cache->GetResolvedMethods(),
1714 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001715 }
1716 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001717 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001718 }
1719 out_dex_files->push_back(std::move(dex_file));
1720 }
1721
1722 if (app_image) {
1723 ScopedObjectAccessUnchecked soa(Thread::Current());
1724 // Check that the class loader resolves the same way as the ones in the image.
1725 // Image class loader [A][B][C][image dex files]
1726 // Class loader = [???][dex_elements][image dex files]
1727 // Need to ensure that [???][dex_elements] == [A][B][C].
1728 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1729 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1730 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1731 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001732 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1733 *error_msg = "Unexpected BootClassLoader in app image";
1734 return false;
1735 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001736 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001737 std::string temp_error_msg;
1738 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1739 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1740 temp_error_msg.c_str());
1741 return false;
1742 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001743 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001744 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1745 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1746 temp_error_msg.c_str());
1747 return false;
1748 }
1749 // Add the temporary dex path list elements at the end.
1750 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1751 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1752 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1753 if (element != nullptr) {
1754 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001755 ObjPtr<mirror::String> name;
1756 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1757 loader_dex_file_names.push_back(name);
1758 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001759 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001760 }
1761 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1762 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1763 static_cast<size_t>(dex_caches->GetLength()));
1764 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1765 // Check that the dex file names match.
1766 bool equal = image_count == loader_dex_file_names.size();
1767 if (equal) {
1768 auto it1 = image_dex_file_names.begin();
1769 auto it2 = loader_dex_file_names.begin();
1770 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1771 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001772 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001773 }
1774 if (!equal) {
1775 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1776 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1777 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001778 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001779 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1780 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1781 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001782 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001783 *error_msg = "Rejecting application image due to class loader mismatch";
1784 // Ignore class loader mismatch for now since these would just use possibly incorrect
1785 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001786 }
1787 }
1788
1789 if (kSanityCheckObjects) {
1790 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1791 auto* dex_cache = dex_caches->Get(i);
1792 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1793 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1794 if (field != nullptr) {
1795 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1796 }
1797 }
1798 }
1799 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001800 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001801 }
1802 }
1803
1804 // Set entry point to interpreter if in InterpretOnly mode.
1805 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001806 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001807 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001808 }
1809
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001810 ClassTable* class_table = nullptr;
1811 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001812 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001813 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001814 }
1815 // If we have a class table section, read it and use it for verification in
1816 // UpdateAppImageClassLoadersAndDexCaches.
1817 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001818 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001819 const bool added_class_table = class_table_section.Size() > 0u;
1820 if (added_class_table) {
1821 const uint64_t start_time2 = NanoTime();
1822 size_t read_count = 0;
1823 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1824 /*make copy*/false,
1825 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001826 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001827 }
1828 if (app_image) {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001829 AppImageClassLoadersAndDexCachesHelper::Update(this,
1830 space,
1831 class_loader,
1832 dex_caches,
1833 &temp_set);
Mathieu Chartier69731002016-03-02 16:08:31 -08001834 // Update class loader and resolved strings. If added_class_table is false, the resolved
1835 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001836 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1837 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001838 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001839 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001840
Vladimir Marko305c38b2018-02-14 11:50:07 +00001841 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07001842 // Every class in the app image has initially SubtypeCheckInfo in the
1843 // Uninitialized state.
1844 //
1845 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
1846 // after class initialization is complete. The app image ClassStatus as-is
1847 // are almost all ClassStatus::Initialized, and being in the
1848 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
1849 //
1850 // Force every app image class's SubtypeCheck to be at least kIninitialized.
1851 //
1852 // See also ImageWriter::FixupClass.
1853 ScopedTrace trace("Recalculate app image SubtypeCheck bitstrings");
1854 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
1855 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00001856 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07001857 }
1858 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001859 }
1860 if (!oat_file->GetBssGcRoots().empty()) {
1861 // Insert oat file to class table for visiting .bss GC roots.
1862 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001863 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001864
Mathieu Chartier69731002016-03-02 16:08:31 -08001865 if (added_class_table) {
1866 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1867 class_table->AddClassSet(std::move(temp_set));
1868 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001869
Mathieu Chartier69731002016-03-02 16:08:31 -08001870 if (kIsDebugBuild && app_image) {
1871 // This verification needs to happen after the classes have been added to the class loader.
1872 // Since it ensures classes are in the class table.
Andreas Gampeacbd98b2017-10-12 10:44:11 -07001873 ScopedTrace trace("VerifyAppImage");
Andreas Gampebe7af222017-07-25 09:57:28 -07001874 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08001875 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001876
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001877 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001878 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001879}
1880
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001881bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001882 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1883 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001884}
1885
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001886void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001887 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1888 // enabling tracing requires the mutator lock, there are no race conditions here.
1889 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001890 Thread* const self = Thread::Current();
1891 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001892 if (kUseReadBarrier) {
1893 // We do not track new roots for CC.
1894 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1895 kVisitRootFlagClearRootLog |
1896 kVisitRootFlagStartLoggingNewRoots |
1897 kVisitRootFlagStopLoggingNewRoots));
1898 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001899 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001900 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1901 // There is 3 GC cases to handle:
1902 // Non moving concurrent:
1903 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001904 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001905 //
1906 // Moving non-concurrent:
1907 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1908 // To prevent missing roots, this case needs to ensure that there is no
1909 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1910 // class which is in the class table.
1911 //
1912 // Moving concurrent:
1913 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1914 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001915 //
1916 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1917 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1918 // these objects.
1919 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07001920 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001921 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001922 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001923 for (const ClassLoaderData& data : class_loaders_) {
1924 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1925 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1926 }
1927 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001928 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001929 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001930 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001931 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001932 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001933 // Concurrent moving GC marked new roots through the to-space invariant.
1934 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001935 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001936 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1937 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1938 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1939 if (old_ref != nullptr) {
1940 DCHECK(old_ref->IsClass());
1941 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1942 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1943 // Concurrent moving GC marked new roots through the to-space invariant.
1944 CHECK_EQ(new_ref, old_ref);
1945 }
1946 }
1947 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001948 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001949 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001950 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00001951 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001952 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001953 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001954 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001955 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001956 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001957 }
1958 // We deliberately ignore the class roots in the image since we
1959 // handle image roots by using the MS/CMS rescanning of dirty cards.
1960}
1961
Brian Carlstroma663ea52011-08-19 23:33:41 -07001962// Keep in sync with InitCallback. Anything we visit, we need to
1963// reinit references to when reinitializing a ClassLinker from a
1964// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001965void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001966 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001967 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001968 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001969 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1970 // unloading if we are marking roots.
1971 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001972}
1973
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001974class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1975 public:
1976 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1977 : visitor_(visitor),
1978 done_(false) {}
1979
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001980 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001981 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001982 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001983 if (!done_ && class_table != nullptr) {
1984 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
1985 if (!class_table->Visit(visitor)) {
1986 // If the visitor ClassTable returns false it means that we don't need to continue.
1987 done_ = true;
1988 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001989 }
1990 }
1991
1992 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001993 // Class visitor that limits the class visits from a ClassTable to the classes with
1994 // the provided defining class loader. This filter is used to avoid multiple visits
1995 // of the same class which can be recorded for multiple initiating class loaders.
1996 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
1997 public:
1998 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
1999 ClassVisitor* visitor)
2000 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2001
2002 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2003 if (klass->GetClassLoader() != defining_class_loader_) {
2004 return true;
2005 }
2006 return (*visitor_)(klass);
2007 }
2008
2009 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2010 ClassVisitor* const visitor_;
2011 };
2012
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002013 ClassVisitor* const visitor_;
2014 // If done is true then we don't need to do any more visiting.
2015 bool done_;
2016};
2017
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002018void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002019 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002020 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2021 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002022 }
2023}
2024
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002025void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002026 Thread* const self = Thread::Current();
2027 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2028 // Not safe to have thread suspension when we are holding a lock.
2029 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002030 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002031 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002032 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002033 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002034 }
2035}
2036
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002037class GetClassesInToVector : public ClassVisitor {
2038 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002039 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002040 classes_.push_back(klass);
2041 return true;
2042 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002043 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002044};
2045
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002046class GetClassInToObjectArray : public ClassVisitor {
2047 public:
2048 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2049 : arr_(arr), index_(0) {}
2050
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002051 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002052 ++index_;
2053 if (index_ <= arr_->GetLength()) {
2054 arr_->Set(index_ - 1, klass);
2055 return true;
2056 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002057 return false;
2058 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002059
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002060 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002061 return index_ <= arr_->GetLength();
2062 }
2063
2064 private:
2065 mirror::ObjectArray<mirror::Class>* const arr_;
2066 int32_t index_;
2067};
2068
2069void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002070 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2071 // is avoiding duplicates.
2072 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002073 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002074 GetClassesInToVector accumulator;
2075 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002076 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002077 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002078 return;
2079 }
2080 }
2081 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002082 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002083 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002084 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002085 // We size the array assuming classes won't be added to the class table during the visit.
2086 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002087 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002088 size_t class_table_size;
2089 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002090 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002091 // Add 100 in case new classes get loaded when we are filling in the object array.
2092 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002093 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002094 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002095 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002096 classes.Assign(
2097 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002098 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002099 GetClassInToObjectArray accumulator(classes.Get());
2100 VisitClasses(&accumulator);
2101 if (accumulator.Succeeded()) {
2102 break;
2103 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002104 }
2105 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2106 // If the class table shrank during creation of the clases array we expect null elements. If
2107 // the class table grew then the loop repeats. If classes are created after the loop has
2108 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002109 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002110 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002111 return;
2112 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002113 }
2114 }
2115}
2116
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002117ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002118 mirror::Class::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002119 mirror::StackTraceElement::ResetClass();
2120 mirror::String::ResetClass();
2121 mirror::Throwable::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002122 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002123 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002124 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002125 // CHA unloading analysis is not needed. No negative consequences are expected because
2126 // all the classloaders are deleted at the same time.
2127 DeleteClassLoader(self, data, false /*cleanup_cha*/);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002128 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002129 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002130}
2131
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002132void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002133 Runtime* const runtime = Runtime::Current();
2134 JavaVMExt* const vm = runtime->GetJavaVM();
2135 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002136 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002137 if (runtime->GetJit() != nullptr) {
2138 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2139 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002140 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002141 code_cache->RemoveMethodsIn(self, *data.allocator);
2142 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002143 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002144 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002145 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002146 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002147 // Cleanup references to single implementation ArtMethods that will be deleted.
2148 if (cleanup_cha) {
2149 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2150 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2151 }
2152
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002153 delete data.allocator;
2154 delete data.class_table;
2155}
2156
Mathieu Chartiere401d142015-04-22 13:56:20 -07002157mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002158 return down_cast<mirror::PointerArray*>(
2159 image_pointer_size_ == PointerSize::k64
2160 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2161 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002162}
2163
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002164mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002165 Thread* self,
2166 const DexFile& dex_file) {
2167 StackHandleScope<1> hs(self);
2168 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002169 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002170 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002171 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002172 self->AssertPendingOOMException();
2173 return nullptr;
2174 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002175 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002176 if (location == nullptr) {
2177 self->AssertPendingOOMException();
2178 return nullptr;
2179 }
2180 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002181 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002182}
2183
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002184mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2185 const DexFile& dex_file,
2186 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002187 ObjPtr<mirror::String> location = nullptr;
2188 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002189 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002190 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002191 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002192 mirror::DexCache::InitializeDexCache(self,
2193 dex_cache,
2194 location,
2195 &dex_file,
2196 linear_alloc,
2197 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002198 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002199 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002200}
2201
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002202mirror::Class* ClassLinker::AllocClass(Thread* self,
2203 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002204 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002205 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002206 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002207 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002208 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002209 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2210 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002211 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002212 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002213 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002214 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002215 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002216}
2217
Ian Rogers6fac4472014-02-25 17:01:10 -08002218mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002219 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002220}
2221
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002222mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002223 Thread* self,
2224 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002225 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002226 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002227}
2228
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002229mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2230 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002231 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002232 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002233 if (kIsDebugBuild) {
2234 StackHandleScope<1> hs(self);
2235 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2236 Thread::PoisonObjectPointersIfDebug();
2237 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002238
2239 // For temporary classes we must wait for them to be retired.
2240 if (init_done_ && klass->IsTemp()) {
2241 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002242 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002243 ThrowEarlierClassFailure(klass);
2244 return nullptr;
2245 }
2246 StackHandleScope<1> hs(self);
2247 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2248 ObjectLock<mirror::Class> lock(self, h_class);
2249 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002250 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002251 lock.WaitIgnoringInterrupts();
2252 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002253 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002254 ThrowEarlierClassFailure(h_class.Get());
2255 return nullptr;
2256 }
2257 CHECK(h_class->IsRetired());
2258 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002259 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002260 }
2261
Brian Carlstromaded5f72011-10-07 17:15:04 -07002262 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002263 size_t index = 0;
2264 // Maximum number of yield iterations until we start sleeping.
2265 static const size_t kNumYieldIterations = 1000;
2266 // How long each sleep is in us.
2267 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002268 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002269 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002270 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002271 {
2272 ObjectTryLock<mirror::Class> lock(self, h_class);
2273 // Can not use a monitor wait here since it may block when returning and deadlock if another
2274 // thread has locked klass.
2275 if (lock.Acquired()) {
2276 // Check for circular dependencies between classes, the lock is required for SetStatus.
2277 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2278 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002279 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002280 return nullptr;
2281 }
2282 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002284 {
2285 // Handle wrapper deals with klass moving.
2286 ScopedThreadSuspension sts(self, kSuspended);
2287 if (index < kNumYieldIterations) {
2288 sched_yield();
2289 } else {
2290 usleep(kSleepDurationUS);
2291 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002292 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002293 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002295
Vladimir Marko72ab6842017-01-20 19:32:50 +00002296 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002297 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002298 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 }
2300 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002301 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002302 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002303 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002304}
2305
Ian Rogers68b56852014-08-29 20:19:11 -07002306typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2307
2308// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002309ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002310 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002311 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002312 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002313 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002314 return ClassPathEntry(dex_file, dex_class_def);
2315 }
2316 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002317 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002318}
2319
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002320bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2321 Thread* self,
2322 const char* descriptor,
2323 size_t hash,
2324 Handle<mirror::ClassLoader> class_loader,
2325 ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002326 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002327 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002328 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002329 return true;
2330 }
2331
Calin Juravlecdd49122017-07-05 20:09:53 -07002332 if (IsPathOrDexClassLoader(soa, class_loader)) {
2333 // For regular path or dex class loader the search order is:
2334 // - parent
2335 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002336
Calin Juravlecdd49122017-07-05 20:09:53 -07002337 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2338 StackHandleScope<1> hs(self);
2339 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2340 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2341 return false; // One of the parents is not supported.
2342 }
2343 if (*result != nullptr) {
2344 return true; // Found the class up the chain.
2345 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002346
Calin Juravlecdd49122017-07-05 20:09:53 -07002347 // Search the current class loader classpath.
2348 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002349 return true;
2350 }
2351
Calin Juravlecdd49122017-07-05 20:09:53 -07002352 if (IsDelegateLastClassLoader(soa, class_loader)) {
2353 // For delegate last, the search order is:
2354 // - boot class path
2355 // - class loader dex files
2356 // - parent
2357 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2358 if (*result != nullptr) {
2359 return true; // The class is part of the boot class path.
2360 }
2361
2362 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2363 if (*result != nullptr) {
2364 return true; // Found the class in the current class loader
2365 }
2366
2367 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2368 StackHandleScope<1> hs(self);
2369 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2370 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2371 }
2372
2373 // Unsupported class loader.
2374 *result = nullptr;
2375 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002376}
2377
2378// Finds the class in the boot class loader.
2379// If the class is found the method returns the resolved class. Otherwise it returns null.
2380ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2381 const char* descriptor,
2382 size_t hash) {
2383 ObjPtr<mirror::Class> result = nullptr;
2384 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2385 if (pair.second != nullptr) {
2386 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2387 if (klass != nullptr) {
2388 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002389 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002390 result = DefineClass(self,
2391 descriptor,
2392 hash,
2393 ScopedNullHandle<mirror::ClassLoader>(),
2394 *pair.first,
2395 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002396 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002397 if (result == nullptr) {
2398 CHECK(self->IsExceptionPending()) << descriptor;
2399 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002400 }
2401 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002402 return result;
2403}
Andreas Gampef865ea92015-04-13 22:14:19 -07002404
Calin Juravle415dc3d2017-06-28 11:03:12 -07002405ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2406 ScopedObjectAccessAlreadyRunnable& soa,
2407 const char* descriptor,
2408 size_t hash,
2409 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002410 DCHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002411 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002412
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002413 ObjPtr<mirror::Class> ret;
2414 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2415 const DexFile::ClassDef* dex_class_def =
2416 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2417 if (dex_class_def != nullptr) {
2418 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2419 descriptor,
2420 hash,
2421 class_loader,
2422 *cp_dex_file,
2423 *dex_class_def);
2424 if (klass == nullptr) {
2425 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2426 soa.Self()->ClearException();
2427 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002428 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002429 ret = klass;
2430 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002431 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002432 return true; // Continue with the next DexFile.
2433 };
2434
2435 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2436 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002437}
2438
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002439mirror::Class* ClassLinker::FindClass(Thread* self,
2440 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002441 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002442 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002443 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002444 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002445 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002446 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002447 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2448 // for primitive classes that aren't backed by dex files.
2449 return FindPrimitiveClass(descriptor[0]);
2450 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002451 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002452 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002453 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002454 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002455 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002456 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002457 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002458 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002459 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002460 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002461 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002462 return DefineClass(self,
2463 descriptor,
2464 hash,
2465 ScopedNullHandle<mirror::ClassLoader>(),
2466 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002467 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002468 } else {
2469 // The boot class loader is searched ahead of the application class loader, failures are
2470 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2471 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002472 ObjPtr<mirror::Throwable> pre_allocated =
2473 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002474 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002475 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002476 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002477 }
2478 ObjPtr<mirror::Class> result_ptr;
2479 bool descriptor_equals;
2480 if (descriptor[0] == '[') {
2481 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2482 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2483 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2484 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002485 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002486 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002487 bool known_hierarchy =
2488 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2489 if (result_ptr != nullptr) {
2490 // The chain was understood and we found the class. We still need to add the class to
2491 // the class table to protect from racy programs that can try and redefine the path list
2492 // which would change the Class<?> returned for subsequent evaluation of const-class.
2493 DCHECK(known_hierarchy);
2494 DCHECK(result_ptr->DescriptorEquals(descriptor));
2495 descriptor_equals = true;
2496 } else {
2497 // Either the chain wasn't understood or the class wasn't found.
2498 //
2499 // If the chain was understood but we did not find the class, let the Java-side
2500 // rediscover all this and throw the exception with the right stack trace. Note that
2501 // the Java-side could still succeed for racy programs if another thread is actively
2502 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002503
Calin Juravleccd56952016-12-15 17:57:38 +00002504 if (!self->CanCallIntoJava()) {
2505 // Oops, we can't call into java so we can't run actual class-loader code.
2506 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002507 ObjPtr<mirror::Throwable> pre_allocated =
2508 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2509 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002510 return nullptr;
2511 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002512
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002513 // Inlined DescriptorToDot(descriptor) with extra validation.
2514 //
2515 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2516 // the DescriptorEquals() check below and give a confusing error message. For example,
2517 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2518 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2519 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2520 size_t descriptor_length = strlen(descriptor);
2521 if (UNLIKELY(descriptor[0] != 'L') ||
2522 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2523 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2524 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2525 return nullptr;
2526 }
2527 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2528 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2529
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002530 ScopedLocalRef<jobject> class_loader_object(
2531 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002532 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2533 {
2534 ScopedThreadStateChange tsc(self, kNative);
2535 ScopedLocalRef<jobject> class_name_object(
2536 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2537 if (class_name_object.get() == nullptr) {
2538 DCHECK(self->IsExceptionPending()); // OOME.
2539 return nullptr;
2540 }
2541 CHECK(class_loader_object.get() != nullptr);
2542 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2543 WellKnownClasses::java_lang_ClassLoader_loadClass,
2544 class_name_object.get()));
2545 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002546 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002547 // broken loader - throw NPE to be compatible with Dalvik
2548 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2549 class_name_string.c_str()).c_str());
2550 return nullptr;
2551 }
2552 result_ptr = soa.Decode<mirror::Class>(result.get());
2553 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002554 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002555 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002556 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002557
2558 if (self->IsExceptionPending()) {
2559 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2560 // However, to comply with the RI behavior, first check if another thread succeeded.
2561 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2562 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2563 self->ClearException();
2564 return EnsureResolved(self, descriptor, result_ptr);
2565 }
2566 return nullptr;
2567 }
2568
2569 // Try to insert the class to the class table, checking for mismatch.
2570 ObjPtr<mirror::Class> old;
2571 {
2572 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2573 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2574 old = class_table->Lookup(descriptor, hash);
2575 if (old == nullptr) {
2576 old = result_ptr; // For the comparison below, after releasing the lock.
2577 if (descriptor_equals) {
2578 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2579 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2580 } // else throw below, after releasing the lock.
2581 }
2582 }
2583 if (UNLIKELY(old != result_ptr)) {
2584 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2585 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2586 mirror::Class* loader_class = class_loader->GetClass();
2587 const char* loader_class_name =
2588 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2589 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2590 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2591 << DescriptorToDot(descriptor) << "\").";
2592 return EnsureResolved(self, descriptor, old);
2593 }
2594 if (UNLIKELY(!descriptor_equals)) {
2595 std::string result_storage;
2596 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2597 std::string loader_storage;
2598 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2599 ThrowNoClassDefFoundError(
2600 "Initiating class loader of type %s returned class %s instead of %s.",
2601 DescriptorToDot(loader_class_name).c_str(),
2602 DescriptorToDot(result_name).c_str(),
2603 DescriptorToDot(descriptor).c_str());
2604 return nullptr;
2605 }
2606 // success, return mirror::Class*
2607 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002608}
2609
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002610mirror::Class* ClassLinker::DefineClass(Thread* self,
2611 const char* descriptor,
2612 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002613 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002614 const DexFile& dex_file,
2615 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002616 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002617 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002618
Brian Carlstromaded5f72011-10-07 17:15:04 -07002619 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002620 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002621 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002622 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002623 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002624 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002625 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002626 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002627 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07002628 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002629 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002630 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002631 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07002632 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002633 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002634 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002635 }
2636
Andreas Gampefa4333d2017-02-14 11:10:34 -08002637 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002638 // Allocate a class with the status of not ready.
2639 // Interface object should get the right size here. Regular class will
2640 // figure out the right size later and be replaced with one of the right
2641 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002642 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002643 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002644 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002645 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002646 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002647 }
Alex Lightb0f11922017-01-23 14:25:17 -08002648 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2649 // nothing.
2650 DexFile const* new_dex_file = nullptr;
2651 DexFile::ClassDef const* new_class_def = nullptr;
2652 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2653 // will only be called once.
2654 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2655 klass,
2656 class_loader,
2657 dex_file,
2658 dex_class_def,
2659 &new_dex_file,
2660 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002661 // Check to see if an exception happened during runtime callbacks. Return if so.
2662 if (self->IsExceptionPending()) {
2663 return nullptr;
2664 }
Alex Lightb0f11922017-01-23 14:25:17 -08002665 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002666 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002667 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002668 return nullptr;
2669 }
2670 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002671 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002672
Jeff Hao848f70a2014-01-15 13:49:50 -08002673 // Mark the string class by setting its access flag.
2674 if (UNLIKELY(!init_done_)) {
2675 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2676 klass->SetStringClass();
2677 }
2678 }
2679
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002680 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002681 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002682 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002683 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002684
Mathieu Chartier590fee92013-09-13 13:46:47 -07002685 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002686 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002687 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002688 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2689 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002690 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002691 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002692
Mathieu Chartierc7853442015-03-27 14:35:38 -07002693 // Load the fields and other things after we are inserted in the table. This is so that we don't
2694 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2695 // other reason is that the field roots are only visited from the class table. So we need to be
2696 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002697 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002698 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002699 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002700 // An exception occured during load, set status to erroneous while holding klass' lock in case
2701 // notification is necessary.
2702 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002703 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002704 }
2705 return nullptr;
2706 }
2707
Brian Carlstromaded5f72011-10-07 17:15:04 -07002708 // Finish loading (if necessary) by finding parents
2709 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002710 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002711 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002712 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002713 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002714 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002715 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002716 }
2717 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002718
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002719 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002720 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002721 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002722
Brian Carlstromaded5f72011-10-07 17:15:04 -07002723 // Link the class (if necessary)
2724 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002725 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002726 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002727
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002728 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002729 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002730 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002731 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002732 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002733 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002734 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002735 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002736 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002737 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002738 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002739
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002740 // Instrumentation may have updated entrypoints for all methods of all
2741 // classes. However it could not update methods of this class while we
2742 // were loading it. Now the class is resolved, we can update entrypoints
2743 // as required by instrumentation.
2744 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2745 // We must be in the kRunnable state to prevent instrumentation from
2746 // suspending all threads to update entrypoints while we are doing it
2747 // for this class.
2748 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002749 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002750 }
2751
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002752 /*
2753 * We send CLASS_PREPARE events to the debugger from here. The
2754 * definition of "preparation" is creating the static fields for a
2755 * class and initializing them to the standard default values, but not
2756 * executing any code (that comes later, during "initialization").
2757 *
2758 * We did the static preparation in LinkClass.
2759 *
2760 * The class has been prepared and resolved but possibly not yet verified
2761 * at this point.
2762 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002763 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002764
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002765 // Notify native debugger of the new class and its layout.
2766 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2767
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002768 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002769}
2770
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002771uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2772 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002773 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002774 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002775 size_t num_8 = 0;
2776 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002777 size_t num_32 = 0;
2778 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002779 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002780 // We allow duplicate definitions of the same field in a class_data_item
2781 // but ignore the repeated indexes here, b/21868015.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002782 uint32_t last_field_idx = dex::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002783 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002784 uint32_t field_idx = it.GetMemberIndex();
2785 // Ordering enforced by DexFileVerifier.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002786 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
Vladimir Marko879d27b2016-03-15 20:31:50 +00002787 if (UNLIKELY(field_idx == last_field_idx)) {
2788 continue;
2789 }
2790 last_field_idx = field_idx;
2791 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002792 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002793 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002794 switch (c) {
2795 case 'L':
2796 case '[':
2797 num_ref++;
2798 break;
2799 case 'J':
2800 case 'D':
2801 num_64++;
2802 break;
2803 case 'I':
2804 case 'F':
2805 num_32++;
2806 break;
2807 case 'S':
2808 case 'C':
2809 num_16++;
2810 break;
2811 case 'B':
2812 case 'Z':
2813 num_8++;
2814 break;
2815 default:
2816 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002817 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002818 }
2819 }
2820 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002821 return mirror::Class::ComputeClassSize(false,
2822 0,
2823 num_8,
2824 num_16,
2825 num_32,
2826 num_64,
2827 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002828 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002829}
2830
Alex Lightfc49fec2018-01-16 22:28:36 +00002831// Special case to get oat code without overwriting a trampoline.
2832const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002833 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002834 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002835 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002836 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002837 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2838 if (code != nullptr) {
2839 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002840 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002841 if (method->IsNative()) {
2842 // No code and native? Use generic trampoline.
2843 return GetQuickGenericJniStub();
2844 }
2845 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002846}
2847
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002848bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2849 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2850 return false;
2851 }
2852
Elliott Hughes956af0f2014-12-11 14:34:28 -08002853 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002854 return true;
2855 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002856
2857 Runtime* runtime = Runtime::Current();
2858 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2859 if (instr->InterpretOnly()) {
2860 return true;
2861 }
2862
2863 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2864 // Doing this check avoids doing compiled/interpreter transitions.
2865 return true;
2866 }
2867
2868 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2869 // Force the use of interpreter when it is required by the debugger.
2870 return true;
2871 }
2872
Alex Light8f34aba2017-10-09 13:46:32 -07002873 if (Thread::Current()->IsAsyncExceptionPending()) {
2874 // Force use of interpreter to handle async-exceptions
2875 return true;
2876 }
2877
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002878 if (runtime->IsJavaDebuggable()) {
2879 // For simplicity, we ignore precompiled code and go to the interpreter
2880 // assuming we don't already have jitted code.
2881 // We could look at the oat file where `quick_code` is being defined,
2882 // and check whether it's been compiled debuggable, but we decided to
2883 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002884 jit::Jit* jit = Runtime::Current()->GetJit();
2885 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2886 }
2887
David Srbeckyf4480162016-03-16 00:06:24 +00002888 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002889 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002890 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002891 // since we want to JIT it (at first use) with extra stackmaps for native
2892 // debugging. We keep however all AOT code from the boot image,
2893 // since the JIT-at-first-use is blocking and would result in non-negligible
2894 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002895 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002896 }
2897
2898 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002899}
2900
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002901void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002902 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002903 if (klass->NumDirectMethods() == 0) {
2904 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002905 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002906 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002907 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002908 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002909 return; // OAT file unavailable.
2910 }
Ian Rogers19846512012-02-24 11:42:47 -08002911 }
Alex Light64ad14d2014-08-19 14:23:13 -07002912
Mathieu Chartierf8322842014-05-16 10:59:25 -07002913 const DexFile& dex_file = klass->GetDexFile();
2914 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002915 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002916 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002917 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002918 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002919 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002920 it.SkipAllFields();
Ian Rogers97b52f82014-08-14 11:34:07 -07002921 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002922 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2923 klass->GetDexClassDefIndex(),
2924 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002925 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002926 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002927 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002928 if (!method->IsStatic()) {
2929 // Only update static methods.
2930 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002931 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002932 const void* quick_code = nullptr;
2933 if (has_oat_class) {
2934 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002935 quick_code = oat_method.GetQuickCode();
2936 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002937 // Check whether the method is native, in which case it's generic JNI.
2938 if (quick_code == nullptr && method->IsNative()) {
2939 quick_code = GetQuickGenericJniStub();
2940 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002941 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002942 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002943 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002944 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002945 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002946 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002947}
2948
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002949// Does anything needed to make sure that the compiler will not generate a direct invoke to this
2950// method. Should only be called on non-invokable methods.
2951inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002952 DCHECK(method != nullptr);
2953 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002954 method->SetEntryPointFromQuickCompiledCodePtrSize(
2955 class_linker->GetQuickToInterpreterBridgeTrampoline(),
2956 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07002957}
2958
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002959static void LinkCode(ClassLinker* class_linker,
2960 ArtMethod* method,
2961 const OatFile::OatClass* oat_class,
2962 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002963 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002964 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002965 // The following code only applies to a non-compiler runtime.
2966 return;
2967 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002968 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002969 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002970 if (oat_class != nullptr) {
2971 // Every kind of method should at least get an invoke stub from the oat_method.
2972 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002973 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002974 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002975 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002976
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002977 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002978 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002979 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07002980
Alex Light9139e002015-10-09 15:59:48 -07002981 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002982 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002983 return;
2984 }
Ian Rogers19846512012-02-24 11:42:47 -08002985
2986 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002987 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002988 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2989 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002990 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002991 } else if (quick_code == nullptr && method->IsNative()) {
2992 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002993 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002994 // Set entry point from compiled code if there's no code or in interpreter only mode.
2995 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002996 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002997
Ian Rogers62d6c772013-02-27 08:32:07 -08002998 if (method->IsNative()) {
2999 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003000 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003001
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003002 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003003 // We have a native method here without code. Then it should have either the generic JNI
3004 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3005 // TODO: this doesn't handle all the cases where trampolines may be installed.
3006 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003007 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3008 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003009 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003010 }
3011}
3012
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003013void ClassLinker::SetupClass(const DexFile& dex_file,
3014 const DexFile::ClassDef& dex_class_def,
3015 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003016 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003017 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003018 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003019 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003020 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003021 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003022
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003023 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003024 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003025 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003026 klass->SetAccessFlags(access_flags);
3027 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003028 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003029 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003030
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003031 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003032 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003033}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003034
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003035void ClassLinker::LoadClass(Thread* self,
3036 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003037 const DexFile::ClassDef& dex_class_def,
3038 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003039 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003040 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003041 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003042 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003043 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003044}
3045
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003046LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3047 LinearAlloc* allocator,
3048 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003049 if (length == 0) {
3050 return nullptr;
3051 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003052 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3053 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3054 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003055 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003056 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003057 CHECK(ret != nullptr);
3058 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3059 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003060}
3061
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003062LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3063 LinearAlloc* allocator,
3064 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003065 if (length == 0) {
3066 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003067 }
Vladimir Marko14632852015-08-17 12:07:23 +01003068 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3069 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003070 const size_t storage_size =
3071 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003072 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003073 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003074 CHECK(ret != nullptr);
3075 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003076 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003077 }
3078 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003079}
3080
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003081LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003082 if (class_loader == nullptr) {
3083 return Runtime::Current()->GetLinearAlloc();
3084 }
3085 LinearAlloc* allocator = class_loader->GetAllocator();
3086 DCHECK(allocator != nullptr);
3087 return allocator;
3088}
3089
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003090LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003091 if (class_loader == nullptr) {
3092 return Runtime::Current()->GetLinearAlloc();
3093 }
3094 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3095 LinearAlloc* allocator = class_loader->GetAllocator();
3096 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003097 RegisterClassLoader(class_loader);
3098 allocator = class_loader->GetAllocator();
3099 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003100 }
3101 return allocator;
3102}
3103
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003104void ClassLinker::LoadClassMembers(Thread* self,
3105 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003106 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003107 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003108 {
3109 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3110 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003111 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003112 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003113 // We allow duplicate definitions of the same field in a class_data_item
3114 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003115 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003116 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003117 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3118 allocator,
3119 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003120 size_t num_sfields = 0;
3121 uint32_t last_field_idx = 0u;
3122 for (; it.HasNextStaticField(); it.Next()) {
3123 uint32_t field_idx = it.GetMemberIndex();
3124 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3125 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3126 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003127 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003128 ++num_sfields;
3129 last_field_idx = field_idx;
3130 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003131 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003132
Mathieu Chartiere401d142015-04-22 13:56:20 -07003133 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003134 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3135 allocator,
3136 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003137 size_t num_ifields = 0u;
3138 last_field_idx = 0u;
3139 for (; it.HasNextInstanceField(); it.Next()) {
3140 uint32_t field_idx = it.GetMemberIndex();
3141 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3142 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3143 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003144 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003145 ++num_ifields;
3146 last_field_idx = field_idx;
3147 }
3148 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003149
Vladimir Marko23682bf2015-06-24 14:28:03 +01003150 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3151 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003152 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003153 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3154 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003155 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3156 if (sfields != nullptr) {
3157 sfields->SetSize(num_sfields);
3158 }
3159 if (ifields != nullptr) {
3160 ifields->SetSize(num_ifields);
3161 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003162 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003163 // Set the field arrays.
3164 klass->SetSFieldsPtr(sfields);
3165 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003166 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003167 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3168 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003169 bool has_oat_class = false;
3170 const OatFile::OatClass oat_class =
3171 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3172 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3173 : OatFile::OatClass::Invalid();
3174 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003175 klass->SetMethodsPtr(
3176 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3177 it.NumDirectMethods(),
3178 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003179 size_t class_def_method_index = 0;
Andreas Gampee2abbc62017-09-15 11:59:26 -07003180 uint32_t last_dex_method_index = dex::kDexNoIndex;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003181 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003182 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003183 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3184 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003185 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003186 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003187 uint32_t it_method_index = it.GetMemberIndex();
3188 if (last_dex_method_index == it_method_index) {
3189 // duplicate case
3190 method->SetMethodIndex(last_class_def_method_index);
3191 } else {
3192 method->SetMethodIndex(class_def_method_index);
3193 last_dex_method_index = it_method_index;
3194 last_class_def_method_index = class_def_method_index;
3195 }
3196 class_def_method_index++;
3197 }
3198 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3199 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003200 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003201 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003202 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003203 class_def_method_index++;
3204 }
3205 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003206 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003207 // Ensure that the card is marked so that remembered sets pick up native roots.
3208 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003209 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003210}
3211
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003212void ClassLinker::LoadField(const ClassDataItemIterator& it,
3213 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003214 ArtField* dst) {
3215 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003216 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003217 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003218
3219 // Get access flags from the DexFile. If this is a boot class path class,
3220 // also set its runtime hidden API access flags.
3221 uint32_t access_flags = it.GetFieldAccessFlags();
3222 if (klass->IsBootStrapClassLoaded()) {
3223 access_flags =
3224 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3225 }
3226 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003227}
3228
Mathieu Chartier268764d2016-09-13 12:09:38 -07003229void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003230 const ClassDataItemIterator& it,
3231 Handle<mirror::Class> klass,
3232 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003233 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003234 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003235 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003236
Mathieu Chartier268764d2016-09-13 12:09:38 -07003237 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003238 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003239 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003240 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003241
David Brazdilf6a8a552018-01-15 18:10:50 +00003242 // Get access flags from the DexFile. If this is a boot class path class,
3243 // also set its runtime hidden API access flags.
Andreas Gampe51829322014-08-25 15:05:04 -07003244 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003245
David Brazdilf6a8a552018-01-15 18:10:50 +00003246 if (klass->IsBootStrapClassLoaded()) {
3247 access_flags =
3248 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3249 }
3250
Ian Rogersdfb325e2013-10-30 01:00:44 -07003251 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003252 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003253 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3254 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003255 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003256 klass->SetFinalizable();
3257 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003258 std::string temp;
3259 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003260 // The Enum class declares a "final" finalize() method to prevent subclasses from
3261 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3262 // subclasses, so we exclude it here.
3263 // We also want to avoid setting the flag on Object, where we know that finalize() is
3264 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003265 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3266 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003267 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003268 }
3269 }
3270 }
3271 } else if (method_name[0] == '<') {
3272 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003273 bool is_init = (strcmp("<init>", method_name) == 0);
3274 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003275 if (UNLIKELY(!is_init && !is_clinit)) {
3276 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3277 } else {
3278 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3279 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003280 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003281 access_flags |= kAccConstructor;
3282 }
3283 }
3284 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003285 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3286 // Check if the native method is annotated with @FastNative or @CriticalNative.
3287 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3288 dex_file, dst->GetClassDef(), dex_method_idx);
3289 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003290 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003291}
3292
Ian Rogers7b078e82014-09-10 14:44:24 -07003293void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003294 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003295 self,
3296 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003297 Runtime::Current()->GetLinearAlloc());
3298 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003299 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003300}
3301
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003302void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003303 ObjPtr<mirror::DexCache> dex_cache) {
3304 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003305 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003306 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
3307 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003308}
3309
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003310void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003311 ObjPtr<mirror::DexCache> dex_cache,
3312 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003313 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003314 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003315 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003316 // For app images, the dex cache location may be a suffix of the dex file location since the
3317 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003318 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3319 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003320 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3321 std::string dex_file_location = dex_file.GetLocation();
3322 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003323 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003324 // Take suffix.
3325 const std::string dex_file_suffix = dex_file_location.substr(
3326 dex_file_location.length() - dex_cache_length,
3327 dex_cache_length);
3328 // Example dex_cache location is SettingsProvider.apk and
3329 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003330 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003331 const OatFile* oat_file =
3332 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003333 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3334 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3335 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3336 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003337 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003338 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3339 DexCacheData data = *it;
3340 if (self->IsJWeakCleared(data.weak_root)) {
3341 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003342 it = dex_caches_.erase(it);
3343 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003344 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003345 it->dex_file->GetOatDexFile() != nullptr &&
3346 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003347 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003348 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003349 ++it;
3350 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003351 }
Vladimir Markob066d432018-01-03 13:14:37 +00003352 if (initialize_oat_file_data) {
3353 // Initialize the .data.bimg.rel.ro section.
3354 if (!oat_file->GetBootImageRelocations().empty()) {
3355 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3356 CheckedCall(mprotect,
3357 "un-protect boot image relocations",
3358 reloc_begin,
3359 oat_file->DataBimgRelRoSize(),
3360 PROT_READ | PROT_WRITE);
3361 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3362 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3363 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3364 const_cast<uint32_t&>(relocation) += boot_image_begin;
3365 }
3366 CheckedCall(mprotect,
3367 "protect boot image relocations",
3368 reloc_begin,
3369 oat_file->DataBimgRelRoSize(),
3370 PROT_READ);
3371 }
3372
3373 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003374 // TODO: Pre-initialize from boot/app image?
3375 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3376 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3377 entry = resolution_method;
3378 }
3379 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003380 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003381 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003382 DexCacheData data;
3383 data.weak_root = dex_cache_jweak;
3384 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003385 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky440a9b32018-02-15 17:47:29 +00003386 AddNativeDebugInfoForDex(self, ArrayRef<const uint8_t>(data.dex_file->Begin(),
3387 data.dex_file->Size()));
Vladimir Markocd556b02017-02-03 11:47:34 +00003388 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003389 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3390 // path dex caches without an image.
3391 data.class_table->InsertStrongRoot(dex_cache);
3392 if (class_loader != nullptr) {
3393 // Since we added a strong root to the class table, do the write barrier as required for
3394 // remembered sets and generational GCs.
3395 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3396 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003397 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003398}
3399
Vladimir Markocd556b02017-02-03 11:47:34 +00003400ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3401 return data.IsValid()
3402 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3403 : nullptr;
3404}
3405
3406ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3407 Thread* self,
3408 ObjPtr<mirror::DexCache> dex_cache,
3409 const DexCacheData& data,
3410 ObjPtr<mirror::ClassLoader> class_loader) {
3411 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3412 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3413 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3414 "Attempt to register dex file %s with multiple class loaders",
3415 data.dex_file->GetLocation().c_str());
3416 return nullptr;
3417 }
3418 return dex_cache;
3419}
3420
Alex Light07f06212017-06-01 14:01:43 -07003421void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3422 ObjPtr<mirror::ClassLoader> class_loader) {
3423 Thread* self = Thread::Current();
3424 StackHandleScope<2> hs(self);
3425 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3426 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3427 const DexFile* dex_file = dex_cache->GetDexFile();
3428 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3429 if (kIsDebugBuild) {
3430 DexCacheData old_data;
3431 {
3432 ReaderMutexLock mu(self, *Locks::dex_lock_);
3433 old_data = FindDexCacheDataLocked(*dex_file);
3434 }
3435 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3436 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3437 << "been registered on dex file " << dex_file->GetLocation();
3438 }
3439 ClassTable* table;
3440 {
3441 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3442 table = InsertClassTableForClassLoader(h_class_loader.Get());
3443 }
3444 WriterMutexLock mu(self, *Locks::dex_lock_);
3445 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3446 table->InsertStrongRoot(h_dex_cache.Get());
3447 if (h_class_loader.Get() != nullptr) {
3448 // Since we added a strong root to the class table, do the write barrier as required for
3449 // remembered sets and generational GCs.
3450 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3451 }
3452}
3453
Vladimir Markocd556b02017-02-03 11:47:34 +00003454ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3455 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003456 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003457 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003458 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003459 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003460 old_data = FindDexCacheDataLocked(dex_file);
3461 }
3462 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3463 if (old_dex_cache != nullptr) {
3464 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003465 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003466 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3467 DCHECK(linear_alloc != nullptr);
3468 ClassTable* table;
3469 {
3470 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3471 table = InsertClassTableForClassLoader(class_loader);
3472 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003473 // Don't alloc while holding the lock, since allocation may need to
3474 // suspend all threads and another thread may need the dex_lock_ to
3475 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003476 StackHandleScope<3> hs(self);
3477 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003478 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003479 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3480 self,
3481 dex_file)));
3482 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003483 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003484 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003485 old_data = FindDexCacheDataLocked(dex_file);
3486 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003487 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003488 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3489 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3490 // that the arrays are null.
3491 mirror::DexCache::InitializeDexCache(self,
3492 h_dex_cache.Get(),
3493 h_location.Get(),
3494 &dex_file,
3495 linear_alloc,
3496 image_pointer_size_);
3497 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003498 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003499 }
3500 if (old_dex_cache != nullptr) {
3501 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3502 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003503 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003504 self->ClearException();
3505 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3506 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3507 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003508 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003509 self->AssertPendingOOMException();
3510 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003511 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003512 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003513 if (h_class_loader.Get() != nullptr) {
3514 // Since we added a strong root to the class table, do the write barrier as required for
3515 // remembered sets and generational GCs.
3516 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3517 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003518 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003519}
3520
Vladimir Markocd556b02017-02-03 11:47:34 +00003521bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003522 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003523 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003524}
3525
Vladimir Markocd556b02017-02-03 11:47:34 +00003526ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3527 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003528 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3529 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003530 if (dex_cache != nullptr) {
3531 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003532 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003533 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003534 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003535 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003536 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003537 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003538 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003539 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3540 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003541 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003542}
3543
Vladimir Markocd556b02017-02-03 11:47:34 +00003544ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3545 const DexFile* dex_file = dex_cache->GetDexFile();
3546 DCHECK(dex_file != nullptr);
3547 ReaderMutexLock mu(self, *Locks::dex_lock_);
3548 // Search assuming unique-ness of dex file.
3549 for (const DexCacheData& data : dex_caches_) {
3550 // Avoid decoding (and read barriers) other unrelated dex caches.
3551 if (data.dex_file == dex_file) {
3552 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3553 if (registered_dex_cache != nullptr) {
3554 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3555 return data.class_table;
3556 }
3557 }
3558 }
3559 return nullptr;
3560}
3561
3562ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3563 // Search assuming unique-ness of dex file.
3564 for (const DexCacheData& data : dex_caches_) {
3565 // Avoid decoding (and read barriers) other unrelated dex caches.
3566 if (data.dex_file == &dex_file) {
3567 return data;
3568 }
3569 }
3570 return DexCacheData();
3571}
3572
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003573mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003574 ObjPtr<mirror::Class> klass =
3575 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003576 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003577 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003578 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003579 }
3580 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003581}
3582
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003583mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003584 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003585 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003586 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003587 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003588 StackHandleScope<1> hs(self);
3589 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003590 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003591 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3592 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003593 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00003594 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003595 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003596 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3597 h_class.Get(),
3598 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003599 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003600 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003601}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003602
Brian Carlstrombe977852011-07-19 14:54:54 -07003603// Create an array class (i.e. the class object for the array, not the
3604// array itself). "descriptor" looks like "[C" or "[[[[B" or
3605// "[Ljava/lang/String;".
3606//
3607// If "descriptor" refers to an array of primitives, look up the
3608// primitive type's internally-generated class object.
3609//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003610// "class_loader" is the class loader of the class that's referring to
3611// us. It's used to ensure that we're looking for the element type in
3612// the right context. It does NOT become the class loader for the
3613// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003614//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003615// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003616mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003617 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003618 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003619 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003620 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003621 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3622 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003623 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003624 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003625 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003626 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3627 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003628 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003629 DCHECK(self->IsExceptionPending());
3630 return nullptr;
3631 } else {
3632 self->ClearException();
3633 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003634 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003635 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3636 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3637 return nullptr;
3638 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003639 // See if the component type is already loaded. Array classes are
3640 // always associated with the class loader of their underlying
3641 // element type -- an array of Strings goes with the loader for
3642 // java/lang/String -- so we need to look for it there. (The
3643 // caller should have checked for the existence of the class
3644 // before calling here, but they did so with *their* class loader,
3645 // not the component type's loader.)
3646 //
3647 // If we find it, the caller adds "loader" to the class' initiating
3648 // loader list, which should prevent us from going through this again.
3649 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003650 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003651 // are the same, because our caller (FindClass) just did the
3652 // lookup. (Even if we get this wrong we still have correct behavior,
3653 // because we effectively do this lookup again when we add the new
3654 // class to the hash table --- necessary because of possible races with
3655 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003656 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003657 ObjPtr<mirror::Class> new_class =
3658 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003659 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003660 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003661 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003662 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003663
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003664 // Fill out the fields in the Class.
3665 //
3666 // It is possible to execute some methods against arrays, because
3667 // all arrays are subclasses of java_lang_Object_, so we need to set
3668 // up a vtable. We can just point at the one in java_lang_Object_.
3669 //
3670 // Array classes are simple enough that we don't need to do a full
3671 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003672 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003673 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003674 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003675 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003676 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003677 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003678 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
3679 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
3680 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003681 } else if (strcmp(descriptor, "[C") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003682 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003683 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003684 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003685 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003686 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003687 }
3688 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003689 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003690 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003691 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003692 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003693 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003694 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003695 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003696 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003697 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003698 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003699 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003700 new_class->SetSuperClass(java_lang_Object);
3701 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003702 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003703 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003704 if (component_type->IsPrimitive()) {
3705 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3706 } else {
3707 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3708 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00003709 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003710 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3711 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3712 new_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003713 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003714 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003715 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003716
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003717 // All arrays have java/lang/Cloneable and java/io/Serializable as
3718 // interfaces. We need to set that up here, so that stuff like
3719 // "instanceof" works right.
3720 //
3721 // Note: The GC could run during the call to FindSystemClass,
3722 // so we need to make sure the class object is GC-valid while we're in
3723 // there. Do this by clearing the interface list so the GC will just
3724 // think that the entries are null.
3725
3726
3727 // Use the single, global copies of "interfaces" and "iftable"
3728 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003729 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003730 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003731 CHECK(array_iftable != nullptr);
3732 new_class->SetIfTable(array_iftable);
3733 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003734
Elliott Hughes00626c22013-06-14 15:04:14 -07003735 // Inherit access flags from the component type.
3736 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3737 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3738 access_flags &= kAccJavaFlagsMask;
3739 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003740 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003741 access_flags |= kAccAbstract | kAccFinal;
3742 access_flags &= ~kAccInterface;
3743
3744 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003745
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003746 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003747 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003748 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3749 // duplicate events in case of races. Array classes don't really follow dedicated
3750 // load and prepare, anyways.
3751 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3752 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3753
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003754 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003755 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003756 }
3757 // Another thread must have loaded the class after we
3758 // started but before we finished. Abandon what we've
3759 // done.
3760 //
3761 // (Yes, this happens.)
3762
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003763 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003764}
3765
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003766mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003767 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassRoots();
Ian Rogers62f05122014-03-21 11:21:29 -07003768 switch (type) {
3769 case 'B':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003770 return GetClassRoot(ClassRoot::kPrimitiveByte, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003771 case 'C':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003772 return GetClassRoot(ClassRoot::kPrimitiveChar, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003773 case 'D':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003774 return GetClassRoot(ClassRoot::kPrimitiveDouble, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003775 case 'F':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003776 return GetClassRoot(ClassRoot::kPrimitiveFloat, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003777 case 'I':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003778 return GetClassRoot(ClassRoot::kPrimitiveInt, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003779 case 'J':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003780 return GetClassRoot(ClassRoot::kPrimitiveLong, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003781 case 'S':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003782 return GetClassRoot(ClassRoot::kPrimitiveShort, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003783 case 'Z':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003784 return GetClassRoot(ClassRoot::kPrimitiveBoolean, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003785 case 'V':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003786 return GetClassRoot(ClassRoot::kPrimitiveVoid, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003787 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003788 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003789 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003790 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003791 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003792 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003793}
3794
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003795mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003796 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003797 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003798 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003799 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003800 source += " from ";
3801 source += dex_cache->GetLocation()->ToModifiedUtf8();
3802 }
3803 LOG(INFO) << "Loaded class " << descriptor << source;
3804 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003805 {
3806 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003807 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003808 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003809 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003810 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003811 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003812 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003813 VerifyObject(klass);
3814 class_table->InsertWithHash(klass, hash);
3815 if (class_loader != nullptr) {
3816 // This is necessary because we need to have the card dirtied for remembered sets.
3817 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3818 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003819 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003820 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003821 }
3822 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003823 if (kIsDebugBuild) {
3824 // Test that copied methods correctly can find their holder.
3825 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3826 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3827 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003828 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003829 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003830}
3831
Vladimir Marko1998cd02017-01-13 13:02:58 +00003832void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003833 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3834 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3835 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3836 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003837 }
3838}
3839
Alex Lighte64300b2015-12-15 15:02:47 -08003840// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003841void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003842 LengthPrefixedArray<ArtMethod>* new_methods) {
3843 klass->SetMethodsPtrUnchecked(new_methods,
3844 klass->NumDirectMethods(),
3845 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003846 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003847 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003848}
3849
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003850mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003851 const char* descriptor,
3852 ObjPtr<mirror::ClassLoader> class_loader) {
3853 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3854}
3855
3856mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003857 const char* descriptor,
3858 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003859 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003860 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3861 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3862 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003863 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003864 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003865 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003866 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003867 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003868 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003869}
3870
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003871class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3872 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08003873 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003874
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003875 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003876 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003877 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003878 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003879 if (class_table != nullptr) {
3880 class_table->FreezeSnapshot();
3881 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003882 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003883};
3884
3885void ClassLinker::MoveClassTableToPreZygote() {
3886 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003887 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003888 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003889 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003890}
3891
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003892// Look up classes by hash and descriptor and put all matching ones in the result array.
3893class LookupClassesVisitor : public ClassLoaderVisitor {
3894 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003895 LookupClassesVisitor(const char* descriptor,
3896 size_t hash,
3897 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003898 : descriptor_(descriptor),
3899 hash_(hash),
3900 result_(result) {}
3901
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003902 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003903 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003904 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003905 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003906 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3907 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003908 result_->push_back(klass);
3909 }
3910 }
3911
3912 private:
3913 const char* const descriptor_;
3914 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003915 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003916};
3917
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003918void ClassLinker::LookupClasses(const char* descriptor,
3919 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003920 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003921 Thread* const self = Thread::Current();
3922 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003923 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003924 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003925 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003926 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003927 result.push_back(klass);
3928 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003929 LookupClassesVisitor visitor(descriptor, hash, &result);
3930 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003931}
3932
Alex Lightf1f10492015-10-07 16:08:36 -07003933bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3934 Handle<mirror::Class> klass,
3935 Handle<mirror::Class> supertype) {
3936 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003937 DCHECK(klass != nullptr);
3938 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003939
Alex Lightf1f10492015-10-07 16:08:36 -07003940 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3941 VerifyClass(self, supertype);
3942 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003943
3944 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3945 // The supertype is either verified, or we soft failed at AOT time.
3946 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003947 return true;
3948 }
3949 // If we got this far then we have a hard failure.
3950 std::string error_msg =
3951 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003952 klass->PrettyDescriptor().c_str(),
3953 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003954 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003955 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003956 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003957 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003958 // Set during VerifyClass call (if at all).
3959 self->ClearException();
3960 }
3961 // Change into a verify error.
3962 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003963 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003964 self->GetException()->SetCause(cause.Get());
3965 }
3966 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3967 if (Runtime::Current()->IsAotCompiler()) {
3968 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3969 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003970 // Need to grab the lock to change status.
3971 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003972 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003973 return false;
3974}
3975
Andreas Gampecc1b5352016-12-01 16:58:38 -08003976// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
3977// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
3978// before.
3979static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
3980 REQUIRES_SHARED(Locks::mutator_lock_) {
3981 if (!klass->WasVerificationAttempted()) {
3982 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
3983 klass->SetVerificationAttempted();
3984 }
3985}
3986
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003987verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01003988 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07003989 {
3990 // TODO: assert that the monitor on the Class is held
3991 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003992
Andreas Gampe884f3b82016-03-30 19:52:58 -07003993 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00003994 ClassStatus old_status = klass->GetStatus();
3995 while (old_status == ClassStatus::kVerifying ||
3996 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07003997 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07003998 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
3999 // case we may see the same status again. b/62912904. This is why the check is
4000 // greater or equal.
4001 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004002 << "Class '" << klass->PrettyClass()
4003 << "' performed an illegal verification state transition from " << old_status
4004 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004005 old_status = klass->GetStatus();
4006 }
jeffhao98eacac2011-09-14 16:11:53 -07004007
Andreas Gampe884f3b82016-03-30 19:52:58 -07004008 // The class might already be erroneous, for example at compile time if we attempted to verify
4009 // this class as a parent to another.
4010 if (klass->IsErroneous()) {
4011 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004012 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004013 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004014
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004015 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004016 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004017 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004018 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004019 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004020
4021 // For AOT, don't attempt to re-verify if we have already found we should
4022 // verify at runtime.
4023 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004024 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004025 }
jeffhao98eacac2011-09-14 16:11:53 -07004026
Vladimir Marko2c64a832018-01-04 11:31:56 +00004027 if (klass->GetStatus() == ClassStatus::kResolved) {
4028 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004029 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004030 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004031 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004032 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004033 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004034 }
4035
4036 // Skip verification if disabled.
4037 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004038 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004039 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004040 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004041 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004042 }
4043
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004044 VLOG(class_linker) << "Beginning verification for class: "
4045 << klass->PrettyDescriptor()
4046 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4047
Ian Rogers9ffb0392012-09-10 11:56:50 -07004048 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004049 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004050 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4051 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004052 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004053 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004054 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004055 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004056
Alex Lightf1f10492015-10-07 16:08:36 -07004057 // Verify all default super-interfaces.
4058 //
4059 // (1) Don't bother if the superclass has already had a soft verification failure.
4060 //
4061 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4062 // recursive initialization by themselves. This is because when an interface is initialized
4063 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4064 // but choose not to for an optimization. If the interfaces is being verified due to a class
4065 // initialization (which would need all the default interfaces to be verified) the class code
4066 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004067 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004068 && !klass->IsInterface()) { // See (2)
4069 int32_t iftable_count = klass->GetIfTableCount();
4070 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4071 // Loop through all interfaces this class has defined. It doesn't matter the order.
4072 for (int32_t i = 0; i < iftable_count; i++) {
4073 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004074 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004075 // We only care if we have default interfaces and can skip if we are already verified...
4076 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4077 continue;
4078 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4079 // We had a hard failure while verifying this interface. Just return immediately.
4080 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004081 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004082 } else if (UNLIKELY(!iface->IsVerified())) {
4083 // We softly failed to verify the iface. Stop checking and clean up.
4084 // Put the iface into the supertype handle so we know what caused us to fail.
4085 supertype.Assign(iface.Get());
4086 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004087 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004088 }
4089 }
4090
Alex Lightf1f10492015-10-07 16:08:36 -07004091 // At this point if verification failed, then supertype is the "first" supertype that failed
4092 // verification (without a specific order). If verification succeeded, then supertype is either
4093 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004094 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004095 supertype.Get() == klass->GetSuperClass() ||
4096 !supertype->IsVerified());
4097
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004098 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004099 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004100 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004101 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004102
4103 VLOG(class_linker) << "Class preverified status for class "
4104 << klass->PrettyDescriptor()
4105 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4106 << ": "
4107 << preverified;
4108
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004109 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4110 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004111 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4112 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004113
Ian Rogers62d6c772013-02-27 08:32:07 -08004114 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004115 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004116 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004117 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004118 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004119
4120 // Verification is done, grab the lock again.
4121 ObjectLock<mirror::Class> lock(self, klass);
4122
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004123 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4124 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004125 VLOG(class_linker) << "Soft verification failure in class "
4126 << klass->PrettyDescriptor()
4127 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4128 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004129 }
Ian Rogers1f539342012-10-03 21:09:42 -07004130 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004131 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004132 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004133 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004134 // Even though there were no verifier failures we need to respect whether the super-class and
4135 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004136 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004137 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004138 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004139 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4140 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004141 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004142 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004143 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004144 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004145 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004146 // Soft failures at compile time should be retried at runtime. Soft
4147 // failures at runtime will be handled by slow paths in the generated
4148 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004149 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004150 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004151 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004152 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004153 // As this is a fake verified status, make sure the methods are _not_ marked
4154 // kAccSkipAccessChecks later.
4155 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004156 }
4157 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004158 } else {
David Sehr709b0702016-10-13 09:12:37 -07004159 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004160 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4161 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004162 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004163 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004164 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004165 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004166 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004167 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004168 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004169 // method.
4170 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004171 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004172 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004173
4174 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4175 // Never skip access checks if the verification soft fail is forced.
4176 // Mark the class as having a verification attempt to avoid re-running the verifier.
4177 klass->SetVerificationAttempted();
4178 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004179 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004180 }
Andreas Gampe48498592014-09-10 19:48:05 -07004181 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004182 // Done verifying. Notify the compiler about the verification status, in case the class
4183 // was verified implicitly (eg super class of a compiled class).
4184 if (Runtime::Current()->IsAotCompiler()) {
4185 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4186 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4187 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004188 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004189}
4190
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004191verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4192 Handle<mirror::Class> klass,
4193 verifier::HardFailLogMode log_level,
4194 std::string* error_msg) {
4195 Runtime* const runtime = Runtime::Current();
4196 return verifier::MethodVerifier::VerifyClass(self,
4197 klass.Get(),
4198 runtime->GetCompilerCallbacks(),
4199 runtime->IsAotCompiler(),
4200 log_level,
4201 error_msg);
4202}
4203
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004204bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004205 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004206 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004207 // If we're compiling, we can only verify the class using the oat file if
4208 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004209 // the compilation unit (app - dependencies). We will let the compiler callback
4210 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004211 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004212 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004213 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004214 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004215 return false;
4216 }
4217 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004218 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004219 return false;
4220 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004221 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004222
Richard Uhler07b3c232015-03-31 15:57:54 -07004223 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004224 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004225 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004226 return false;
4227 }
4228
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004229 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004230 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004231 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004232 return true;
4233 }
4234 // If we only verified a subset of the classes at compile time, we can end up with classes that
4235 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004236 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004237 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004238 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004239 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004240 // Compile time verification failed with a soft error. Compile time verification can fail
4241 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004242 // class ... {
4243 // Foo x;
4244 // .... () {
4245 // if (...) {
4246 // v1 gets assigned a type of resolved class Foo
4247 // } else {
4248 // v1 gets assigned a type of unresolved class Bar
4249 // }
4250 // iput x = v1
4251 // } }
4252 // when we merge v1 following the if-the-else it results in Conflict
4253 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4254 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4255 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4256 // at compile time).
4257 return false;
4258 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004259 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004260 // Compile time verification failed with a hard error. This is caused by invalid instructions
4261 // in the class. These errors are unrecoverable.
4262 return false;
4263 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004264 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004265 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4266 // not loading the class.
4267 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4268 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004269 return false;
4270 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004271 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004272 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004273 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004274 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004275 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004276}
4277
Alex Light5a559862016-01-29 12:24:48 -08004278void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004279 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004280 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004281 }
4282}
4283
Alex Light5a559862016-01-29 12:24:48 -08004284void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004285 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004286 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004287 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004288 return; // native or abstract method
4289 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004290 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004291 return; // nothing to process
4292 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004293 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004294 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004295 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4296 CatchHandlerIterator iterator(handlers_ptr);
4297 for (; iterator.HasNext(); iterator.Next()) {
4298 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4299 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004300 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004301 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004302 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004303 DCHECK(Thread::Current()->IsExceptionPending());
4304 Thread::Current()->ClearException();
4305 }
4306 }
4307 }
4308 handlers_ptr = iterator.EndDataPointer();
4309 }
4310}
4311
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004312mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4313 jstring name,
4314 jobjectArray interfaces,
4315 jobject loader,
4316 jobjectArray methods,
4317 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004318 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004319 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004320 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004321 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004322 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004323 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004324 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004325 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004326 DCHECK(temp_klass->GetClass() != nullptr);
4327 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004328 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4329 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004330 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4331 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4332 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4333 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004334 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004335 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004336 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004337 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004338 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004339 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004340
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004341 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004342 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004343
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004344 // Insert the class before loading the fields as the field roots
4345 // (ArtField::declaring_class_) are only visited from the class
4346 // table. There can't be any suspend points between inserting the
4347 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004348 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004349 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004350
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004351 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004352 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004353 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004354 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004355
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004356 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4357 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004358 ArtField& interfaces_sfield = sfields->At(0);
4359 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004360 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004361 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004362
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004363 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004364 ArtField& throws_sfield = sfields->At(1);
4365 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004366 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004367 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004368
Ian Rogers466bb252011-10-14 03:29:56 -07004369 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004370 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004371
Alex Lighte64300b2015-12-15 15:02:47 -08004372 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004373 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004374 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004375 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004376 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004377
4378 // Create the methods array.
4379 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4380 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004381 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4382 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004383 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004384 self->AssertPendingOOMException();
4385 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004386 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004387 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004388
4389 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004390 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004391
4392 // Create virtual method using specified prototypes.
4393 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004394 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004395 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004396 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004397 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004398 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4399 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004400 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004401
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004402 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004403 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004404 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004405 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004406 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004407
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004408 // At this point the class is loaded. Publish a ClassLoad event.
4409 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4410 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4411
4412 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004413 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004414 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004415 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004416 // Link the fields and virtual methods, creating vtable and iftables.
4417 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004418 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004419 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004420 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004421 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004422 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004423 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004424 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004425 CHECK(temp_klass->IsRetired());
4426 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004427
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004428 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004429 interfaces_sfield.SetObject<false>(
4430 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004431 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004432 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4433 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004434 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004435 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004436
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004437 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4438
Vladimir Marko305c38b2018-02-14 11:50:07 +00004439 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4440 // See also ClassLinker::EnsureInitialized().
4441 if (kBitstringSubtypeCheckEnabled) {
4442 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4443 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4444 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4445 }
4446
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004447 {
4448 // Lock on klass is released. Lock new class object.
4449 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004450 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004451 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004452
4453 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004454 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004455 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004456 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4457
Ian Rogersc2b44472011-12-14 21:17:17 -08004458 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004459 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4460 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004461 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004462 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004463
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004464 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004465 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004466 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004467 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004468 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004469
4470 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004471 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004472 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004473
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004474 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004475 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004476 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004477 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004478 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004479 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004480}
4481
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004482std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004483 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004484 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004485 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004486 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4487}
4488
Mathieu Chartiere401d142015-04-22 13:56:20 -07004489void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4490 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004491 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4492 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004493
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004494 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4495 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004496 ArtMethod* proxy_constructor = proxy_class->FindConstructor(
Vladimir Markoba118822017-06-12 15:41:56 +01004497 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004498 DCHECK(proxy_constructor != nullptr)
4499 << "Could not find <init> method in java.lang.reflect.Proxy";
4500
Jeff Haodb8a6642014-08-14 17:18:52 -07004501 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4502 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004503 DCHECK(out != nullptr);
4504 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004505 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004506 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004507 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004508 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4509 kAccPublic |
4510 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004511 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004512
4513 // Set the original constructor method.
4514 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004515}
4516
Mathieu Chartiere401d142015-04-22 13:56:20 -07004517void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004518 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004519 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4520 CHECK_STREQ(np->GetName(), "<init>");
4521 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004522 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004523}
4524
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004525void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004526 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004527 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004528 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004529 DCHECK(out != nullptr);
4530 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004531
Alex Lighte9dd04f2016-03-16 16:09:45 -07004532 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004533 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004534 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4535 // preference to the invocation handler.
4536 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4537 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004538 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4539 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004540 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4541
4542 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4543 // method they copy might (if it's a default method).
4544 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004545
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004546 // Set the original interface method.
4547 out->SetDataPtrSize(prototype, image_pointer_size_);
4548
Ian Rogers466bb252011-10-14 03:29:56 -07004549 // At runtime the method looks like a reference and argument saving method, clone the code
4550 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004551 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004552}
Jesse Wilson95caa792011-10-12 18:14:17 -04004553
Mathieu Chartiere401d142015-04-22 13:56:20 -07004554void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004555 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004556 CHECK(!prototype->IsFinal());
4557 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004558 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004559
4560 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4561 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004562 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004563 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004564}
4565
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004566bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004567 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004568 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004569 return true;
4570 }
4571 if (!can_init_statics) {
4572 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004573 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004574 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004575 return false;
4576 }
4577 // Check if there are encoded static values needing initialization.
4578 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004579 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004580 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004581 if (dex_class_def->static_values_off_ != 0) {
4582 return false;
4583 }
4584 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004585 // If we are a class we need to initialize all interfaces with default methods when we are
4586 // initialized. Check all of them.
4587 if (!klass->IsInterface()) {
4588 size_t num_interfaces = klass->GetIfTableCount();
4589 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004590 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004591 if (iface->HasDefaultMethods() &&
4592 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4593 return false;
4594 }
4595 }
4596 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004597 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004598 if (klass->IsInterface() || !klass->HasSuperClass()) {
4599 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004600 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004601 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004602 if (!can_init_parents && !super_class->IsInitialized()) {
4603 return false;
4604 }
4605 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004606}
4607
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004608bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4609 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004610 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4611
4612 // Are we already initialized and therefore done?
4613 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4614 // an initialized class will never change its state.
4615 if (klass->IsInitialized()) {
4616 return true;
4617 }
4618
4619 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004620 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004621 return false;
4622 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004623
Ian Rogers7b078e82014-09-10 14:44:24 -07004624 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004625 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004626 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004627 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004628
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004629 // Re-check under the lock in case another thread initialized ahead of us.
4630 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004631 return true;
4632 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004633
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004634 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004635 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004636 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004637 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004638 return false;
4639 }
4640
Vladimir Marko72ab6842017-01-20 19:32:50 +00004641 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4642 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004643
4644 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004645 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004646 if (!klass->IsVerified()) {
4647 // We failed to verify, expect either the klass to be erroneous or verification failed at
4648 // compile time.
4649 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004650 // The class is erroneous. This may be a verifier error, or another thread attempted
4651 // verification and/or initialization and failed. We can distinguish those cases by
4652 // whether an exception is already pending.
4653 if (self->IsExceptionPending()) {
4654 // Check that it's a VerifyError.
4655 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004656 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004657 } else {
4658 // Check that another thread attempted initialization.
4659 DCHECK_NE(0, klass->GetClinitThreadId());
4660 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4661 // Need to rethrow the previous failure now.
4662 ThrowEarlierClassFailure(klass.Get(), true);
4663 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004664 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004665 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004666 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004667 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004668 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004669 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004670 } else {
4671 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004672 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004673
4674 // A separate thread could have moved us all the way to initialized. A "simple" example
4675 // involves a subclass of the current class being initialized at the same time (which
4676 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004677 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004678 if (klass->IsInitialized()) {
4679 return true;
4680 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004681 }
4682
Vladimir Marko2c64a832018-01-04 11:31:56 +00004683 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07004684 // initializing higher up the stack or another thread has beat us
4685 // to initializing and we need to wait. Either way, this
4686 // invocation of InitializeClass will not be responsible for
4687 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004688 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004689 // Could have got an exception during verification.
4690 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004691 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004692 return false;
4693 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004694 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004695 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004696 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004697 return true;
4698 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004699 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004700 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004701 }
4702
Jeff Haoe2e40342017-07-19 10:45:18 -07004703 // Try to get the oat class's status for this class if the oat file is present. The compiler
4704 // tries to validate superclass descriptors, and writes the result into the oat file.
4705 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4706 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4707 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004708 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004709 const Runtime* runtime = Runtime::Current();
4710 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4711 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4712 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004713 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07004714 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004715 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004716 return false;
4717 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004718 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004719
Vladimir Marko2c64a832018-01-04 11:31:56 +00004720 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004721 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004723 // From here out other threads may observe that we're initializing and so changes of state
4724 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004725 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004726 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004727
4728 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004729 }
4730
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004731 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004732 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004733 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004734 if (!super_class->IsInitialized()) {
4735 CHECK(!super_class->IsInterface());
4736 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004737 StackHandleScope<1> hs(self);
4738 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004739 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004740 if (!super_initialized) {
4741 // The super class was verified ahead of entering initializing, we should only be here if
4742 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004743 // For the case of aot compiler, the super class might also be initializing but we don't
4744 // want to process circular dependencies in pre-compile.
4745 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004746 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004747 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004748 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004749 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004750 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004751 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004752 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004753 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004754 return false;
4755 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004756 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004757 }
4758
Alex Lighteb7c1442015-08-31 13:17:42 -07004759 if (!klass->IsInterface()) {
4760 // Initialize interfaces with default methods for the JLS.
4761 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004762 // Only setup the (expensive) handle scope if we actually need to.
4763 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004764 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004765 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4766 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004767 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004768 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004769 CHECK(handle_scope_iface->IsInterface());
4770 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4771 // We have already done this for this interface. Skip it.
4772 continue;
4773 }
4774 // We cannot just call initialize class directly because we need to ensure that ALL
4775 // interfaces with default methods are initialized. Non-default interface initialization
4776 // will not affect other non-default super-interfaces.
4777 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4778 handle_scope_iface,
4779 can_init_statics,
4780 can_init_parents);
4781 if (!iface_initialized) {
4782 ObjectLock<mirror::Class> lock(self, klass);
4783 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004784 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004785 return false;
4786 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004787 }
4788 }
4789 }
4790
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004791 const size_t num_static_fields = klass->NumStaticFields();
4792 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004793 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004794 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004795 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004796 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004797 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004798
4799 // Eagerly fill in static fields so that the we don't have to do as many expensive
4800 // Class::FindStaticField in ResolveField.
4801 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004802 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004803 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004804 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004805 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01004806 // Populating cache of a dex file which defines `klass` should always be allowed.
4807 DCHECK_EQ(hiddenapi::GetMemberAction(
4808 field, class_loader.Get(), dex_cache.Get(), hiddenapi::kNone), hiddenapi::kAllow);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004809 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004810 } else {
4811 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004812 }
4813 }
4814
Vladimir Markoe11dd502017-12-08 14:09:45 +00004815 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
4816 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07004817 this,
4818 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00004819 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers13735952014-10-08 12:43:28 -07004820 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004821 ClassDataItemIterator field_it(dex_file, class_data);
4822 if (value_it.HasNext()) {
4823 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004824 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004825 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004826 ArtField* field = ResolveField(
Vladimir Markoe11dd502017-12-08 14:09:45 +00004827 field_it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004828 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004829 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004830 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004831 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004832 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004833 if (self->IsExceptionPending()) {
4834 break;
4835 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004836 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004837 }
4838 }
4839 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004840
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004841
Mathieu Chartierda595be2016-08-10 13:57:39 -07004842 if (!self->IsExceptionPending()) {
4843 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4844 if (clinit != nullptr) {
4845 CHECK(can_init_statics);
4846 JValue result;
4847 clinit->Invoke(self, nullptr, 0, &result, "V");
4848 }
4849 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004850 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004851 uint64_t t1 = NanoTime();
4852
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004853 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004854 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004855 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004856
4857 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004858 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004859 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004860 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004861 } else if (Runtime::Current()->IsTransactionAborted()) {
4862 // The exception thrown when the transaction aborted has been caught and cleared
4863 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004864 VLOG(compiler) << "Return from class initializer of "
4865 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004866 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004867 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004868 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004869 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004870 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004871 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4872 RuntimeStats* thread_stats = self->GetStats();
4873 ++global_stats->class_init_count;
4874 ++thread_stats->class_init_count;
4875 global_stats->class_init_time_ns += (t1 - t0);
4876 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004877 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004878 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004879 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004880 std::string temp;
4881 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004882 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004883 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004884 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004885 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004886 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004887 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004888 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004889}
4890
Alex Lighteb7c1442015-08-31 13:17:42 -07004891// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4892// and perform the initialization only on those interfaces that contain default methods.
4893bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4894 Handle<mirror::Class> iface,
4895 bool can_init_statics,
4896 bool can_init_parents) {
4897 CHECK(iface->IsInterface());
4898 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004899 // Only create the (expensive) handle scope if we need it.
4900 if (UNLIKELY(num_direct_ifaces > 0)) {
4901 StackHandleScope<1> hs(self);
4902 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4903 // First we initialize all of iface's super-interfaces recursively.
4904 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004905 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004906 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004907 if (!super_iface->HasBeenRecursivelyInitialized()) {
4908 // Recursive step
4909 handle_super_iface.Assign(super_iface);
4910 if (!InitializeDefaultInterfaceRecursive(self,
4911 handle_super_iface,
4912 can_init_statics,
4913 can_init_parents)) {
4914 return false;
4915 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004916 }
4917 }
4918 }
4919
4920 bool result = true;
4921 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4922 // initialize if we don't have default methods.
4923 if (iface->HasDefaultMethods()) {
4924 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4925 }
4926
4927 // Mark that this interface has undergone recursive default interface initialization so we know we
4928 // can skip it on any later class initializations. We do this even if we are not a default
4929 // interface since we can still avoid the traversal. This is purely a performance optimization.
4930 if (result) {
4931 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08004932 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
4933 // interface. It is bad (Java) style, but not impossible. Marking the recursive
4934 // initialization is a performance optimization (to avoid another idempotent visit
4935 // for other implementing classes/interfaces), and can be revisited later.
4936 ObjectTryLock<mirror::Class> lock(self, iface);
4937 if (lock.Acquired()) {
4938 iface->SetRecursivelyInitialized();
4939 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004940 }
4941 return result;
4942}
4943
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004944bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4945 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004946 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004947 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004948 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004949 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004950 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004951 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004952
4953 // When we wake up, repeat the test for init-in-progress. If
4954 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004955 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004956 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004957 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004958 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004959 return false;
4960 }
4961 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004962 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004963 continue;
4964 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004965 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004966 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004967 // Compile time initialization failed.
4968 return false;
4969 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004970 if (klass->IsErroneous()) {
4971 // The caller wants an exception, but it was thrown in a
4972 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004973 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004974 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004975 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004976 return false;
4977 }
4978 if (klass->IsInitialized()) {
4979 return true;
4980 }
David Sehr709b0702016-10-13 09:12:37 -07004981 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004982 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004983 }
Ian Rogers07140832014-09-30 15:43:59 -07004984 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004985}
4986
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004987static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4988 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004989 ArtMethod* method,
4990 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004991 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004992 DCHECK(Thread::Current()->IsExceptionPending());
4993 DCHECK(!m->IsProxyMethod());
4994 const DexFile* dex_file = m->GetDexFile();
4995 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4996 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004997 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07004998 std::string return_type = dex_file->PrettyType(return_type_idx);
4999 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005000 ThrowWrappedLinkageError(klass.Get(),
5001 "While checking class %s method %s signature against %s %s: "
5002 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005003 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5004 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005005 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005006 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005007 return_type.c_str(), class_loader.c_str());
5008}
5009
5010static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5011 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005012 ArtMethod* method,
5013 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005014 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005015 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005016 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005017 DCHECK(Thread::Current()->IsExceptionPending());
5018 DCHECK(!m->IsProxyMethod());
5019 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005020 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5021 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005022 ThrowWrappedLinkageError(klass.Get(),
5023 "While checking class %s method %s signature against %s %s: "
5024 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005025 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5026 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005027 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005028 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005029 index, arg_type.c_str(), class_loader.c_str());
5030}
5031
5032static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5033 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005034 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005035 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005036 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005037 ThrowLinkageError(klass.Get(),
5038 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005039 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5040 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005041 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005042 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005043 error_msg.c_str());
5044}
5045
Ian Rogersb5fb2072014-12-02 17:22:02 -08005046static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005047 Handle<mirror::Class> klass,
5048 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005049 ArtMethod* method1,
5050 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005051 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005052 {
5053 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005054 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005055 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005056 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005057 return false;
5058 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005059 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005060 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005061 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005062 return false;
5063 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005064 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005065 ThrowSignatureMismatch(klass, super_klass, method1,
5066 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005067 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005068 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005069 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005070 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005071 return false;
5072 }
5073 }
5074 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5075 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5076 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005077 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005078 ThrowSignatureMismatch(klass, super_klass, method1,
5079 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005080 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005081 return false;
5082 }
5083 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005084 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005085 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005086 ThrowSignatureMismatch(klass, super_klass, method1,
5087 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005088 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005089 return false;
5090 }
5091 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005092 }
5093 uint32_t num_types = types1->Size();
5094 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005095 ThrowSignatureMismatch(klass, super_klass, method1,
5096 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005097 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005098 return false;
5099 }
5100 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005101 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005102 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005103 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005104 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005105 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005106 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005107 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005108 return false;
5109 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005110 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005111 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005112 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005113 if (UNLIKELY(other_param_type == nullptr)) {
5114 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005115 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005116 return false;
5117 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005118 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005119 ThrowSignatureMismatch(klass, super_klass, method1,
5120 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5121 i,
David Sehr709b0702016-10-13 09:12:37 -07005122 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005123 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005124 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005125 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005126 return false;
5127 }
5128 }
5129 return true;
5130}
5131
5132
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005133bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005134 if (klass->IsInterface()) {
5135 return true;
5136 }
Ian Rogers151f2212014-05-06 11:27:27 -07005137 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005138 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005139 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005140 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005141 if (klass->HasSuperClass() &&
5142 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005143 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005144 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005145 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5146 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5147 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005148 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5149 klass,
5150 super_klass,
5151 m,
5152 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005153 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005154 return false;
5155 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005156 }
5157 }
5158 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005159 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005160 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5161 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5162 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005163 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005164 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5165 j, image_pointer_size_);
5166 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5167 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005168 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5169 klass,
5170 super_klass,
5171 m,
5172 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005173 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005174 return false;
5175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005176 }
5177 }
5178 }
5179 }
5180 return true;
5181}
5182
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005183bool ClassLinker::EnsureInitialized(Thread* self,
5184 Handle<mirror::Class> c,
5185 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005186 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005187 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005188
Mathieu Chartier524507a2014-08-27 15:28:28 -07005189 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005190 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005191 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005192 return true;
5193 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005194 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5195 //
5196 // Ensure the bitstring is initialized before any of the class initialization
5197 // logic occurs. Once a class initializer starts running, objects can
5198 // escape into the heap and use the subtype checking code.
5199 //
5200 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5201 // can be used as a source for the IsSubClass check, and that all ancestors
5202 // of the class are Assigned (can be used as a target for IsSubClass check)
5203 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005204 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005205 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005206 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005207 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5208 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005209 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005210 if (!success) {
5211 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005212 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005213 }
5214 } else {
5215 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005216 }
5217 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005218}
5219
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005220void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5221 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005222 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005223 for (ArtField& field : new_class->GetIFields()) {
5224 if (field.GetDeclaringClass() == temp_class) {
5225 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005226 }
5227 }
5228
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005229 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005230 for (ArtField& field : new_class->GetSFields()) {
5231 if (field.GetDeclaringClass() == temp_class) {
5232 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005233 }
5234 }
5235
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005236 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005237 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005238 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005239 if (method.GetDeclaringClass() == temp_class) {
5240 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005241 }
5242 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005243
5244 // Make sure the remembered set and mod-union tables know that we updated some of the native
5245 // roots.
5246 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005247}
5248
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005249void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005250 CHECK(class_loader->GetAllocator() == nullptr);
5251 CHECK(class_loader->GetClassTable() == nullptr);
5252 Thread* const self = Thread::Current();
5253 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005254 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005255 // Create and set the class table.
5256 data.class_table = new ClassTable;
5257 class_loader->SetClassTable(data.class_table);
5258 // Create and set the linear allocator.
5259 data.allocator = Runtime::Current()->CreateLinearAlloc();
5260 class_loader->SetAllocator(data.allocator);
5261 // Add to the list so that we know to free the data later.
5262 class_loaders_.push_back(data);
5263}
5264
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005265ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005266 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005267 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005268 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005269 ClassTable* class_table = class_loader->GetClassTable();
5270 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005271 RegisterClassLoader(class_loader);
5272 class_table = class_loader->GetClassTable();
5273 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005274 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005275 return class_table;
5276}
5277
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005278ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005279 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005280}
5281
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005282static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005283 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005284 while (klass->HasSuperClass()) {
5285 klass = klass->GetSuperClass();
5286 if (klass->ShouldHaveImt()) {
5287 return klass->GetImt(pointer_size);
5288 }
5289 }
5290 return nullptr;
5291}
5292
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005293bool ClassLinker::LinkClass(Thread* self,
5294 const char* descriptor,
5295 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005296 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005297 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005298 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005299
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005300 if (!LinkSuperClass(klass)) {
5301 return false;
5302 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005303 ArtMethod* imt_data[ImTable::kSize];
5304 // If there are any new conflicts compared to super class.
5305 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005306 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005307 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005308 return false;
5309 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005310 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005311 return false;
5312 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005313 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005314 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005315 return false;
5316 }
5317 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005318 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005319
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005320 ImTable* imt = nullptr;
5321 if (klass->ShouldHaveImt()) {
5322 // If there are any new conflicts compared to the super class we can not make a copy. There
5323 // can be cases where both will have a conflict method at the same slot without having the same
5324 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5325 // will possibly create a table that is incorrect for either of the classes.
5326 // Same IMT with new_conflict does not happen very often.
5327 if (!new_conflict) {
5328 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5329 if (super_imt != nullptr) {
5330 bool imt_equals = true;
5331 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5332 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5333 }
5334 if (imt_equals) {
5335 imt = super_imt;
5336 }
5337 }
5338 }
5339 if (imt == nullptr) {
5340 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5341 imt = reinterpret_cast<ImTable*>(
5342 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5343 if (imt == nullptr) {
5344 return false;
5345 }
5346 imt->Populate(imt_data, image_pointer_size_);
5347 }
5348 }
5349
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005350 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5351 // We don't need to retire this class as it has no embedded tables or it was created the
5352 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005353 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005354
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005355 if (klass->ShouldHaveEmbeddedVTable()) {
5356 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005357 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005358 if (klass->ShouldHaveImt()) {
5359 klass->SetImt(imt, image_pointer_size_);
5360 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005361
5362 // Update CHA info based on whether we override methods.
5363 // Have to do this before setting the class as resolved which allows
5364 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005365 if (cha_ != nullptr) {
5366 cha_->UpdateAfterLoadingOf(klass);
5367 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005368
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005369 // This will notify waiters on klass that saw the not yet resolved
5370 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005371 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005372 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005373 } else {
5374 CHECK(!klass->IsResolved());
5375 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005376 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005377 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005378 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5379 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5380 // may not see any references to the target space and clean the card for a class if another
5381 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005382 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005383 klass->SetSFieldsPtrUnchecked(nullptr);
5384 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005385 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005386 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005387 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005388 return false;
5389 }
5390
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005391 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5392 ObjectLock<mirror::Class> lock(self, h_new_class);
5393 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005394
5395 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005396 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005397 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005398 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005399 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005400 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005401 if (class_loader != nullptr) {
5402 // We updated the class in the class table, perform the write barrier so that the GC knows
5403 // about the change.
5404 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5405 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005406 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005407 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005408 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5409 }
5410 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005411
Mingyao Yang063fc772016-08-02 11:02:54 -07005412 // Update CHA info based on whether we override methods.
5413 // Have to do this before setting the class as resolved which allows
5414 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005415 if (cha_ != nullptr) {
5416 cha_->UpdateAfterLoadingOf(h_new_class);
5417 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005418
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005419 // This will notify waiters on temp class that saw the not yet resolved class in the
5420 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005421 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005422
Vladimir Marko2c64a832018-01-04 11:31:56 +00005423 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005424 // This will notify waiters on new_class that saw the not yet resolved
5425 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005426 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005427 // Return the new class.
5428 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005429 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005430 return true;
5431}
5432
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005433bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005434 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005435 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005436 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5437 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005438 // Check that a class does not inherit from itself directly.
5439 //
5440 // TODO: This is a cheap check to detect the straightforward case
5441 // of a class extending itself (b/28685551), but we should do a
5442 // proper cycle detection on loaded classes, to detect all cases
5443 // of class circularity errors (b/28830038).
5444 if (super_class_idx == class_def.class_idx_) {
5445 ThrowClassCircularityError(klass.Get(),
5446 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005447 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005448 return false;
5449 }
5450
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005451 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005452 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005453 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005454 return false;
5455 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005456 // Verify
5457 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005458 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005459 super_class->PrettyDescriptor().c_str(),
5460 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005461 return false;
5462 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005463 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005464 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005465 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005466 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005467 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005468 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005469 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005470 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005471 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005472 DCHECK(Thread::Current()->IsExceptionPending());
5473 return false;
5474 }
5475 // Verify
5476 if (!klass->CanAccess(interface)) {
5477 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005478 ThrowIllegalAccessError(klass.Get(),
5479 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005480 interface->PrettyDescriptor().c_str(),
5481 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005482 return false;
5483 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005484 }
5485 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005486 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005487 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005488 return true;
5489}
5490
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005491bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005492 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005493 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005494 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5495 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005496 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005497 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005498 return false;
5499 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005500 return true;
5501 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005502 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005503 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005504 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005505 return false;
5506 }
5507 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005508 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005509 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5510 return false;
5511 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005512 if (super->IsFinal()) {
5513 ThrowVerifyError(klass.Get(),
5514 "Superclass %s of %s is declared final",
5515 super->PrettyDescriptor().c_str(),
5516 klass->PrettyDescriptor().c_str());
5517 return false;
5518 }
5519 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005520 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005521 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005522 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005523 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005524 return false;
5525 }
5526 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005527 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005528 super->PrettyDescriptor().c_str(),
5529 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005530 return false;
5531 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005532
Brian Carlstromf3632832014-05-20 15:36:53 -07005533 // Inherit kAccClassIsFinalizable from the superclass in case this
5534 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005535 if (super->IsFinalizable()) {
5536 klass->SetFinalizable();
5537 }
5538
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005539 // Inherit class loader flag form super class.
5540 if (super->IsClassLoaderClass()) {
5541 klass->SetClassLoaderClass();
5542 }
5543
Elliott Hughes2da50362011-10-10 16:57:08 -07005544 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005545 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005546 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005547 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005548 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005549 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005550 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005551 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005552 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005553 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005554 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005555 return false;
5556 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005557
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005558 if (kIsDebugBuild) {
5559 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005560 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005561 CHECK(super->IsResolved());
5562 super = super->GetSuperClass();
5563 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005564 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005565 return true;
5566}
5567
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005568// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005569bool ClassLinker::LinkMethods(Thread* self,
5570 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005571 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005572 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005573 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005574 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005575 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5576 // need to have default methods be in the virtuals array of each class but we don't set that up
5577 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005578 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005579 // Link virtual methods then interface methods.
5580 // We set up the interface lookup table first because we need it to determine if we need to update
5581 // any vtable entries with new default method implementations.
5582 return SetupInterfaceLookupTable(self, klass, interfaces)
5583 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005584 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005585}
5586
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005587// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5588// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5589// caches in the implementation below.
5590class MethodNameAndSignatureComparator FINAL : public ValueObject {
5591 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005592 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005593 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005594 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5595 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005596 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005597 }
5598
5599 const char* GetName() {
5600 if (name_ == nullptr) {
5601 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5602 }
5603 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005604 }
5605
Mathieu Chartiere401d142015-04-22 13:56:20 -07005606 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005607 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005608 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005609 const DexFile* other_dex_file = other->GetDexFile();
5610 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5611 if (dex_file_ == other_dex_file) {
5612 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5613 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005614 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005615 uint32_t other_name_len;
5616 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5617 &other_name_len);
5618 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5619 return false;
5620 }
5621 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5622 }
5623
5624 private:
5625 // Dex file for the method to compare against.
5626 const DexFile* const dex_file_;
5627 // MethodId for the method to compare against.
5628 const DexFile::MethodId* const mid_;
5629 // Lazily computed name from the dex file's strings.
5630 const char* name_;
5631 // Lazily computed name length.
5632 uint32_t name_len_;
5633};
5634
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005635class LinkVirtualHashTable {
5636 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005637 LinkVirtualHashTable(Handle<mirror::Class> klass,
5638 size_t hash_size,
5639 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005640 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005641 : klass_(klass),
5642 hash_size_(hash_size),
5643 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005644 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005645 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5646 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005647
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005648 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005649 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5650 virtual_method_index, image_pointer_size_);
5651 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005652 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005653 uint32_t index = hash % hash_size_;
5654 // Linear probe until we have an empty slot.
5655 while (hash_table_[index] != invalid_index_) {
5656 if (++index == hash_size_) {
5657 index = 0;
5658 }
5659 }
5660 hash_table_[index] = virtual_method_index;
5661 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005662
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005663 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005664 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005665 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005666 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005667 size_t index = hash % hash_size_;
5668 while (true) {
5669 const uint32_t value = hash_table_[index];
5670 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5671 // the block and can safely assume not found.
5672 if (value == invalid_index_) {
5673 break;
5674 }
5675 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005676 ArtMethod* virtual_method =
5677 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5678 if (comparator->HasSameNameAndSignature(
5679 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005680 hash_table_[index] = removed_index_;
5681 return value;
5682 }
5683 }
5684 if (++index == hash_size_) {
5685 index = 0;
5686 }
5687 }
5688 return GetNotFoundIndex();
5689 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005690
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005691 static uint32_t GetNotFoundIndex() {
5692 return invalid_index_;
5693 }
5694
5695 private:
5696 static const uint32_t invalid_index_;
5697 static const uint32_t removed_index_;
5698
5699 Handle<mirror::Class> klass_;
5700 const size_t hash_size_;
5701 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005702 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005703};
5704
5705const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5706const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5707
Stephen Hines1ddd9132017-02-08 01:51:18 -08005708bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005709 Thread* self,
5710 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005711 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005712 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005713 if (klass->IsInterface()) {
5714 // No vtable.
5715 if (!IsUint<16>(num_virtual_methods)) {
5716 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5717 return false;
5718 }
5719 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005720 // Assign each method an IMT index and set the default flag.
5721 for (size_t i = 0; i < num_virtual_methods; ++i) {
5722 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5723 m->SetMethodIndex(i);
5724 if (!m->IsAbstract()) {
5725 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5726 has_defaults = true;
5727 }
5728 }
5729 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5730 // during initialization. This is a performance optimization. We could simply traverse the
5731 // virtual_methods_ array again during initialization.
5732 if (has_defaults) {
5733 klass->SetHasDefaultMethods();
5734 }
5735 return true;
5736 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005737 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5738 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005739 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005740 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005741 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005742 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005743 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005744 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005745 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005746 return false;
5747 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005748 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005749 vtable->SetElementPtrSize(
5750 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005751 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005752 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5753 // might give us new default methods). If no new interfaces then we can skip the rest since
5754 // the class cannot override any of the super-class's methods. This is required for
5755 // correctness since without it we might not update overridden default method vtable entries
5756 // correctly.
5757 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005758 klass->SetVTable(vtable.Get());
5759 return true;
5760 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005761 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005762 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005763 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005764 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005765 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5766 // might give us new default methods). See comment above.
5767 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005768 klass->SetVTable(super_vtable);
5769 return true;
5770 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005771 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5772 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005773 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005774 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005775 return false;
5776 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005777 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005778 // How the algorithm works:
5779 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5780 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5781 // method which has not been matched to a vtable method, and j if the virtual method at the
5782 // index overrode the super virtual method at index j.
5783 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5784 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5785 // the need for the initial vtable which we later shrink back down).
5786 // 3. Add non overridden methods to the end of the vtable.
5787 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005788 // + 1 so that even if we only have new default methods we will still be able to use this hash
5789 // table (i.e. it will never have 0 size).
5790 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005791 uint32_t* hash_table_ptr;
5792 std::unique_ptr<uint32_t[]> hash_heap_storage;
5793 if (hash_table_size <= kMaxStackHash) {
5794 hash_table_ptr = reinterpret_cast<uint32_t*>(
5795 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5796 } else {
5797 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5798 hash_table_ptr = hash_heap_storage.get();
5799 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005800 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005801 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005802 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005803 DCHECK(klass->GetVirtualMethodDuringLinking(
5804 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005805 hash_table.Add(i);
5806 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005807 // 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 -07005808 // the hash table.
5809 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005810 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005811 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005812 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5813 super_method->GetAccessFlags())) {
5814 // Continue on to the next method since this one is package private and canot be overridden.
5815 // Before Android 4.1, the package-private method super_method might have been incorrectly
5816 // overridden.
5817 continue;
5818 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005819 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005820 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005821 // We remove the method so that subsequent lookups will be faster by making the hash-map
5822 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005823 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5824 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005825 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5826 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005827 if (super_method->IsFinal()) {
5828 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5829 virtual_method->PrettyMethod().c_str(),
5830 super_method->GetDeclaringClassDescriptor());
5831 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005832 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005833 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5834 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005835 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005836 // We didn't directly override this method but we might through default methods...
5837 // Check for default method update.
5838 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005839 switch (FindDefaultMethodImplementation(self,
5840 super_method,
5841 klass,
5842 /*out*/&default_method)) {
5843 case DefaultMethodSearchResult::kDefaultConflict: {
5844 // A conflict was found looking for default methods. Note this (assuming it wasn't
5845 // pre-existing) in the translations map.
5846 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5847 // Don't generate another conflict method to reduce memory use as an optimization.
5848 default_translations->insert(
5849 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5850 }
5851 break;
5852 }
5853 case DefaultMethodSearchResult::kAbstractFound: {
5854 // No conflict but method is abstract.
5855 // We note that this vtable entry must be made abstract.
5856 if (UNLIKELY(!super_method->IsAbstract())) {
5857 default_translations->insert(
5858 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5859 }
5860 break;
5861 }
5862 case DefaultMethodSearchResult::kDefaultFound: {
5863 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5864 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5865 // Found a default method implementation that is new.
5866 // TODO Refactor this add default methods to virtuals here and not in
5867 // LinkInterfaceMethods maybe.
5868 // The problem is default methods might override previously present
5869 // default-method or miranda-method vtable entries from the superclass.
5870 // Unfortunately we need these to be entries in this class's virtuals. We do not
5871 // give these entries there until LinkInterfaceMethods so we pass this map around
5872 // to let it know which vtable entries need to be updated.
5873 // Make a note that vtable entry j must be updated, store what it needs to be updated
5874 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5875 // then.
5876 default_translations->insert(
5877 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005878 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5879 << " overridden by default "
5880 << default_method->PrettyMethod()
5881 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005882 }
5883 break;
5884 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005885 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005886 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005887 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005888 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005889 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005890 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005891 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005892 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5893 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005894 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005895 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005896 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005897 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005898 local_method->SetMethodIndex(actual_count);
5899 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005900 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005901 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005902 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005903 return false;
5904 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005905 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005906 CHECK_LE(actual_count, max_count);
5907 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005908 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005909 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005910 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005911 return false;
5912 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005913 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005914 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005915 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005916 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005917 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005918 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5919 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005920 return false;
5921 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005922 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005923 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005924 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005925 return false;
5926 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005927 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005928 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5929 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005930 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005931 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005932 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005933 }
5934 return true;
5935}
5936
Alex Light9139e002015-10-09 15:59:48 -07005937// Determine if the given iface has any subinterface in the given list that declares the method
5938// specified by 'target'.
5939//
5940// Arguments
5941// - self: The thread we are running on
5942// - target: A comparator that will match any method that overrides the method we are checking for
5943// - iftable: The iftable we are searching for an overriding method on.
5944// - ifstart: The index of the interface we are checking to see if anything overrides
5945// - iface: The interface we are checking to see if anything overrides.
5946// - image_pointer_size:
5947// The image pointer size.
5948//
5949// Returns
5950// - True: There is some method that matches the target comparator defined in an interface that
5951// is a subtype of iface.
5952// - False: There is no method that matches the target comparator in any interface that is a subtype
5953// of iface.
5954static bool ContainsOverridingMethodOf(Thread* self,
5955 MethodNameAndSignatureComparator& target,
5956 Handle<mirror::IfTable> iftable,
5957 size_t ifstart,
5958 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005959 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005960 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005961 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005962 DCHECK(iface != nullptr);
5963 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07005964 DCHECK_GE(ifstart, 0u);
5965 DCHECK_LT(ifstart, iftable->Count());
5966 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5967 DCHECK(iface->IsInterface());
5968
5969 size_t iftable_count = iftable->Count();
5970 StackHandleScope<1> hs(self);
5971 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5972 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5973 // Skip ifstart since our current interface obviously cannot override itself.
5974 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005975 // Iterate through every method on this interface. The order does not matter.
5976 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07005977 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08005978 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07005979 // Check if the i'th interface is a subtype of this one.
5980 if (iface->IsAssignableFrom(current_iface.Get())) {
5981 return true;
5982 }
5983 break;
5984 }
5985 }
5986 }
5987 return false;
5988}
5989
Alex Lighteb7c1442015-08-31 13:17:42 -07005990// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07005991// out_default_method and returns kDefaultFound on success. If no default method was found return
5992// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
5993// default_method conflict) it will return kDefaultConflict.
5994ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
5995 Thread* self,
5996 ArtMethod* target_method,
5997 Handle<mirror::Class> klass,
5998 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07005999 DCHECK(self != nullptr);
6000 DCHECK(target_method != nullptr);
6001 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006002
6003 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006004
6005 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6006 // table. This lets us walk the table backwards when searching for default methods. The first one
6007 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6008 // track of it and then continue checking all other interfaces, since we need to throw an error if
6009 // we encounter conflicting default method implementations (one is not a subtype of the other).
6010 //
6011 // The order of unrelated interfaces does not matter and is not defined.
6012 size_t iftable_count = klass->GetIfTableCount();
6013 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006014 // No interfaces. We have already reset out to null so just return kAbstractFound.
6015 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006016 }
6017
Alex Light9139e002015-10-09 15:59:48 -07006018 StackHandleScope<3> hs(self);
6019 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006020 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006021 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006022 MethodNameAndSignatureComparator target_name_comparator(
6023 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6024 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006025 for (size_t k = iftable_count; k != 0; ) {
6026 --k;
6027
Alex Lighteb7c1442015-08-31 13:17:42 -07006028 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006029
6030 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006031 // Iterate through every declared method on this interface. The order does not matter.
6032 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6033 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006034 // Skip abstract methods and methods with different names.
6035 if (current_method->IsAbstract() ||
6036 !target_name_comparator.HasSameNameAndSignature(
6037 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6038 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006039 } else if (!current_method->IsPublic()) {
6040 // The verifier should have caught the non-public method for dex version 37. Just warn and
6041 // skip it since this is from before default-methods so we don't really need to care that it
6042 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006043 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6044 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006045 << "This will be a fatal error in subsequent versions of android. "
6046 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006047 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006048 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006049 // We have multiple default impls of the same method. This is a potential default conflict.
6050 // We need to check if this possibly conflicting method is either a superclass of the chosen
6051 // default implementation or is overridden by a non-default interface method. In either case
6052 // there is no conflict.
6053 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6054 !ContainsOverridingMethodOf(self,
6055 target_name_comparator,
6056 iftable,
6057 k,
6058 iface,
6059 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006060 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006061 << current_method->PrettyMethod() << " and "
6062 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6063 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006064 *out_default_method = nullptr;
6065 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006066 } else {
6067 break; // Continue checking at the next interface.
6068 }
6069 } else {
Alex Light9139e002015-10-09 15:59:48 -07006070 // chosen_iface == null
6071 if (!ContainsOverridingMethodOf(self,
6072 target_name_comparator,
6073 iftable,
6074 k,
6075 iface,
6076 image_pointer_size_)) {
6077 // Don't set this as the chosen interface if something else is overriding it (because that
6078 // other interface would be potentially chosen instead if it was default). If the other
6079 // interface was abstract then we wouldn't select this interface as chosen anyway since
6080 // the abstract method masks it.
6081 *out_default_method = current_method;
6082 chosen_iface.Assign(iface.Get());
6083 // We should now finish traversing the graph to find if we have default methods that
6084 // conflict.
6085 } else {
David Sehr709b0702016-10-13 09:12:37 -07006086 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6087 << "' was "
6088 << "skipped because it was overridden by an abstract method in a "
6089 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006090 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006091 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006092 break;
6093 }
6094 }
Alex Light9139e002015-10-09 15:59:48 -07006095 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006096 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6097 << "' selected "
6098 << "as the implementation for '" << target_method->PrettyMethod()
6099 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006100 return DefaultMethodSearchResult::kDefaultFound;
6101 } else {
6102 return DefaultMethodSearchResult::kAbstractFound;
6103 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006104}
6105
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006106ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006107 ArtMethod* conflict_method,
6108 ArtMethod* interface_method,
6109 ArtMethod* method,
6110 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006111 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006112 Runtime* const runtime = Runtime::Current();
6113 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6114 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6115
6116 // Create a new entry if the existing one is the shared conflict method.
6117 ArtMethod* new_conflict_method = new_entry
6118 ? runtime->CreateImtConflictMethod(linear_alloc)
6119 : conflict_method;
6120
6121 // Allocate a new table. Note that we will leak this table at the next conflict,
6122 // but that's a tradeoff compared to making the table fixed size.
6123 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006124 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6125 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006126 if (data == nullptr) {
6127 LOG(ERROR) << "Failed to allocate conflict table";
6128 return conflict_method;
6129 }
6130 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6131 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006132 method,
6133 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006134
6135 // Do a fence to ensure threads see the data in the table before it is assigned
6136 // to the conflict method.
6137 // Note that there is a race in the presence of multiple threads and we may leak
6138 // memory from the LinearAlloc, but that's a tradeoff compared to using
6139 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006140 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006141 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006142 return new_conflict_method;
6143}
6144
Vladimir Marko921094a2017-01-12 18:37:06 +00006145bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6146 Handle<mirror::Class> klass,
6147 Handle<mirror::IfTable> iftable) {
6148 DCHECK(!klass->IsInterface());
6149 const bool has_superclass = klass->HasSuperClass();
6150 const bool extend_super_iftable = has_superclass;
6151 const size_t ifcount = klass->GetIfTableCount();
6152 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6153 for (size_t i = 0; i < ifcount; ++i) {
6154 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6155 if (num_methods > 0) {
6156 const bool is_super = i < super_ifcount;
6157 // This is an interface implemented by a super-class. Therefore we can just copy the method
6158 // array from the superclass.
6159 const bool super_interface = is_super && extend_super_iftable;
6160 ObjPtr<mirror::PointerArray> method_array;
6161 if (super_interface) {
6162 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6163 DCHECK(if_table != nullptr);
6164 DCHECK(if_table->GetMethodArray(i) != nullptr);
6165 // If we are working on a super interface, try extending the existing method array.
6166 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6167 } else {
6168 method_array = AllocPointerArray(self, num_methods);
6169 }
6170 if (UNLIKELY(method_array == nullptr)) {
6171 self->AssertPendingOOMException();
6172 return false;
6173 }
6174 iftable->SetMethodArray(i, method_array);
6175 }
6176 }
6177 return true;
6178}
6179
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006180void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6181 ArtMethod* imt_conflict_method,
6182 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006183 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006184 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006185 // Place method in imt if entry is empty, place conflict otherwise.
6186 if (*imt_ref == unimplemented_method) {
6187 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006188 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006189 // If we are not a conflict and we have the same signature and name as the imt
6190 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006191 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6192 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006193 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006194 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006195 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006196 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006197 *imt_ref = current_method;
6198 } else {
Alex Light9139e002015-10-09 15:59:48 -07006199 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006200 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006201 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006202 } else {
6203 // Place the default conflict method. Note that there may be an existing conflict
6204 // method in the IMT, but it could be one tailored to the super class, with a
6205 // specific ImtConflictTable.
6206 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006207 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006208 }
6209}
6210
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006211void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006212 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6213 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006214 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006215 Runtime* const runtime = Runtime::Current();
6216 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6217 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006218 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006219 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006220 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006221 FillIMTFromIfTable(klass->GetIfTable(),
6222 unimplemented_method,
6223 conflict_method,
6224 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006225 /*create_conflict_tables*/true,
6226 /*ignore_copied_methods*/false,
6227 &new_conflict,
6228 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006229 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006230 if (!klass->ShouldHaveImt()) {
6231 return;
6232 }
6233 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6234 // we can just use the same pointer.
6235 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006236 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006237 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6238 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6239 bool same = true;
6240 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6241 ArtMethod* method = imt_data[i];
6242 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6243 if (method != super_method) {
6244 bool is_conflict_table = method->IsRuntimeMethod() &&
6245 method != unimplemented_method &&
6246 method != conflict_method;
6247 // Verify conflict contents.
6248 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6249 super_method != unimplemented_method &&
6250 super_method != conflict_method;
6251 if (!is_conflict_table || !super_conflict_table) {
6252 same = false;
6253 } else {
6254 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6255 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6256 same = same && table1->Equals(table2, image_pointer_size_);
6257 }
6258 }
6259 }
6260 if (same) {
6261 imt = super_imt;
6262 }
6263 }
6264 if (imt == nullptr) {
6265 imt = klass->GetImt(image_pointer_size_);
6266 DCHECK(imt != nullptr);
6267 imt->Populate(imt_data, image_pointer_size_);
6268 } else {
6269 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006270 }
6271}
6272
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006273ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6274 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006275 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006276 void* data = linear_alloc->Alloc(Thread::Current(),
6277 ImtConflictTable::ComputeSize(count,
6278 image_pointer_size));
6279 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6280}
6281
6282ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6283 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6284}
6285
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006286void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006287 ArtMethod* unimplemented_method,
6288 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006289 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006290 bool create_conflict_tables,
6291 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006292 /*out*/bool* new_conflict,
6293 /*out*/ArtMethod** imt) {
6294 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006295 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006296 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006297 const size_t num_virtuals = interface->NumVirtualMethods();
6298 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6299 // Virtual methods can be larger than the if table methods if there are default methods.
6300 DCHECK_GE(num_virtuals, method_array_count);
6301 if (kIsDebugBuild) {
6302 if (klass->IsInterface()) {
6303 DCHECK_EQ(method_array_count, 0u);
6304 } else {
6305 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6306 }
6307 }
6308 if (method_array_count == 0) {
6309 continue;
6310 }
6311 auto* method_array = if_table->GetMethodArray(i);
6312 for (size_t j = 0; j < method_array_count; ++j) {
6313 ArtMethod* implementation_method =
6314 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6315 if (ignore_copied_methods && implementation_method->IsCopied()) {
6316 continue;
6317 }
6318 DCHECK(implementation_method != nullptr);
6319 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6320 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6321 // or interface methods in the IMT here they will not create extra conflicts since we compare
6322 // names and signatures in SetIMTRef.
6323 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006324 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006325
6326 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6327 // the same implementation method, keep track of this to avoid creating a conflict table in
6328 // this case.
6329
6330 // Conflict table size for each IMT slot.
6331 ++conflict_counts[imt_index];
6332
6333 SetIMTRef(unimplemented_method,
6334 imt_conflict_method,
6335 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006336 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006337 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006338 }
6339 }
6340
6341 if (create_conflict_tables) {
6342 // Create the conflict tables.
6343 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006344 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006345 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006346 if (imt[i] == imt_conflict_method) {
6347 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6348 if (new_table != nullptr) {
6349 ArtMethod* new_conflict_method =
6350 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6351 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6352 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006353 } else {
6354 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006355 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006356 }
6357 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006358 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006359 }
6360 }
6361
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006362 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006363 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006364 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6365 // Virtual methods can be larger than the if table methods if there are default methods.
6366 if (method_array_count == 0) {
6367 continue;
6368 }
6369 auto* method_array = if_table->GetMethodArray(i);
6370 for (size_t j = 0; j < method_array_count; ++j) {
6371 ArtMethod* implementation_method =
6372 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6373 if (ignore_copied_methods && implementation_method->IsCopied()) {
6374 continue;
6375 }
6376 DCHECK(implementation_method != nullptr);
6377 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006378 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006379 if (!imt[imt_index]->IsRuntimeMethod() ||
6380 imt[imt_index] == unimplemented_method ||
6381 imt[imt_index] == imt_conflict_method) {
6382 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006383 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006384 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6385 const size_t num_entries = table->NumEntries(image_pointer_size_);
6386 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6387 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006388 }
6389 }
6390 }
6391}
6392
Alex Lighteb7c1442015-08-31 13:17:42 -07006393// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6394// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006395static bool NotSubinterfaceOfAny(
6396 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6397 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006398 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006399 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006400 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006401 for (ObjPtr<mirror::Class> c : classes) {
6402 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006403 return false;
6404 }
6405 }
6406 return true;
6407}
6408
6409// Fills in and flattens the interface inheritance hierarchy.
6410//
6411// By the end of this function all interfaces in the transitive closure of to_process are added to
6412// the iftable and every interface precedes all of its sub-interfaces in this list.
6413//
6414// all I, J: Interface | I <: J implies J precedes I
6415//
6416// (note A <: B means that A is a subtype of B)
6417//
6418// This returns the total number of items in the iftable. The iftable might be resized down after
6419// this call.
6420//
6421// We order this backwards so that we do not need to reorder superclass interfaces when new
6422// interfaces are added in subclass's interface tables.
6423//
6424// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6425// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6426// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6427// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006428static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006429 size_t super_ifcount,
6430 std::vector<mirror::Class*> to_process)
6431 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006432 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006433 // This is the set of all class's already in the iftable. Used to make checking if a class has
6434 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006435 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006436 // The first super_ifcount elements are from the superclass. We note that they are already added.
6437 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006438 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006439 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6440 classes_in_iftable.insert(iface);
6441 }
6442 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006443 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006444 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6445 // At this point in the loop current-iface-list has the invariant that:
6446 // for every pair of interfaces I,J within it:
6447 // if index_of(I) < index_of(J) then I is not a subtype of J
6448
6449 // If we have already seen this element then all of its super-interfaces must already be in the
6450 // current-iface-list so we can skip adding it.
6451 if (!ContainsElement(classes_in_iftable, interface)) {
6452 // We haven't seen this interface so add all of its super-interfaces onto the
6453 // current-iface-list, skipping those already on it.
6454 int32_t ifcount = interface->GetIfTableCount();
6455 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006456 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006457 if (!ContainsElement(classes_in_iftable, super_interface)) {
6458 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6459 classes_in_iftable.insert(super_interface);
6460 iftable->SetInterface(filled_ifcount, super_interface);
6461 filled_ifcount++;
6462 }
6463 }
6464 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6465 // Place this interface onto the current-iface-list after all of its super-interfaces.
6466 classes_in_iftable.insert(interface);
6467 iftable->SetInterface(filled_ifcount, interface);
6468 filled_ifcount++;
6469 } else if (kIsDebugBuild) {
6470 // Check all super-interfaces are already in the list.
6471 int32_t ifcount = interface->GetIfTableCount();
6472 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006473 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006474 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006475 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6476 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006477 }
6478 }
6479 }
6480 if (kIsDebugBuild) {
6481 // Check that the iftable is ordered correctly.
6482 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006483 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006484 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006485 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006486 // !(if_a <: if_b)
6487 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006488 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6489 << ") extends "
6490 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006491 << "interface list.";
6492 }
6493 }
6494 }
6495 return filled_ifcount;
6496}
6497
6498bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6499 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6500 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006501 const bool has_superclass = klass->HasSuperClass();
6502 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006503 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006504 const size_t num_interfaces =
6505 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006506 if (num_interfaces == 0) {
6507 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006508 if (LIKELY(has_superclass)) {
6509 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6510 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006511 // Class implements no interfaces.
6512 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006513 return true;
6514 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006515 // Class implements same interfaces as parent, are any of these not marker interfaces?
6516 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006517 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006518 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006519 if (super_iftable->GetMethodArrayCount(i) > 0) {
6520 has_non_marker_interface = true;
6521 break;
6522 }
6523 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006524 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006525 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006526 klass->SetIfTable(super_iftable);
6527 return true;
6528 }
6529 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006530 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006531 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006532 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006533 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006534 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006535 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006536 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006537 if (UNLIKELY(!interface->IsInterface())) {
6538 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006539 ThrowIncompatibleClassChangeError(klass.Get(),
6540 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006541 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006542 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6543 return false;
6544 }
6545 ifcount += interface->GetIfTableCount();
6546 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006547 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006548 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006549 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006550 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006551 return false;
6552 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006553 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006554 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006555 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006556 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006557 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006558 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006559 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006560 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006561
6562 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6563 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6564 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006565 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006566
6567 size_t new_ifcount;
6568 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006569 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006570 std::vector<mirror::Class*> to_add;
6571 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006572 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006573 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006574 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006575 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006576
6577 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006578 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006579
Ian Rogers7b078e82014-09-10 14:44:24 -07006580 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006581
Ian Rogersb52b01a2012-01-12 17:01:38 -08006582 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006583 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006584 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006585 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006586 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006587 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006588 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006589 return false;
6590 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006591 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006592 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006593 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006594 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006595 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006596 return true;
6597}
6598
Alex Light1f3925d2016-09-07 12:04:20 -07006599// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6600// of methods must be unique.
6601static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6602 return nullptr;
6603}
6604
6605template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006606static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006607 const ScopedArenaVector<ArtMethod*>& list,
6608 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006609 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006610 for (ArtMethod* method : list) {
6611 if (cmp.HasSameNameAndSignature(method)) {
6612 return method;
6613 }
6614 }
Alex Light1f3925d2016-09-07 12:04:20 -07006615 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006616}
6617
Alex Light1f3925d2016-09-07 12:04:20 -07006618// Check that all vtable entries are present in this class's virtuals or are the same as a
6619// superclasses vtable entry.
6620static void CheckClassOwnsVTableEntries(Thread* self,
6621 Handle<mirror::Class> klass,
6622 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006623 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006624 StackHandleScope<2> hs(self);
6625 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006626 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006627 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006628 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006629 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6630 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6631 CHECK(m != nullptr);
6632
Alex Lighta41a30782017-03-29 11:33:19 -07006633 if (m->GetMethodIndexDuringLinking() != i) {
6634 LOG(WARNING) << m->PrettyMethod()
6635 << " has an unexpected method index for its spot in the vtable for class"
6636 << klass->PrettyClass();
6637 }
Alex Lighte64300b2015-12-15 15:02:47 -08006638 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6639 auto is_same_method = [m] (const ArtMethod& meth) {
6640 return &meth == m;
6641 };
Alex Light3f980532017-03-17 15:10:32 -07006642 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6643 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6644 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6645 << klass->PrettyClass() << " or any of its superclasses!";
6646 }
Alex Lighte64300b2015-12-15 15:02:47 -08006647 }
6648}
6649
Alex Light1f3925d2016-09-07 12:04:20 -07006650// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6651// method is overridden in a subclass.
6652static void CheckVTableHasNoDuplicates(Thread* self,
6653 Handle<mirror::Class> klass,
6654 PointerSize pointer_size)
6655 REQUIRES_SHARED(Locks::mutator_lock_) {
6656 StackHandleScope<1> hs(self);
6657 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6658 int32_t num_entries = vtable->GetLength();
6659 for (int32_t i = 0; i < num_entries; i++) {
6660 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6661 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6662 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6663 vtable_entry->GetAccessFlags())) {
6664 continue;
6665 }
6666 MethodNameAndSignatureComparator name_comparator(
6667 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006668 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006669 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006670 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6671 other_entry->GetAccessFlags())) {
6672 continue;
6673 }
Alex Light3f980532017-03-17 15:10:32 -07006674 if (vtable_entry == other_entry ||
6675 name_comparator.HasSameNameAndSignature(
6676 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6677 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6678 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6679 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6680 << other_entry->PrettyMethod() << " (0x" << std::hex
6681 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6682 }
Alex Light1f3925d2016-09-07 12:04:20 -07006683 }
6684 }
6685}
6686
6687static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6688 REQUIRES_SHARED(Locks::mutator_lock_) {
6689 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6690 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6691}
6692
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006693void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6694 ArtMethod* unimplemented_method,
6695 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006696 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006697 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006698 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006699 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006700 if (super_class->ShouldHaveImt()) {
6701 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6702 for (size_t i = 0; i < ImTable::kSize; ++i) {
6703 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006704 }
6705 } else {
6706 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006707 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006708 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006709 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006710 FillIMTFromIfTable(if_table,
6711 unimplemented_method,
6712 imt_conflict_method,
6713 klass.Get(),
6714 /*create_conflict_table*/false,
6715 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006716 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006717 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006718 }
6719 }
6720}
6721
Vladimir Marko921094a2017-01-12 18:37:06 +00006722class ClassLinker::LinkInterfaceMethodsHelper {
6723 public:
6724 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6725 Handle<mirror::Class> klass,
6726 Thread* self,
6727 Runtime* runtime)
6728 : class_linker_(class_linker),
6729 klass_(klass),
6730 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6731 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6732 self_(self),
6733 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6734 allocator_(&stack_),
6735 default_conflict_methods_(allocator_.Adapter()),
6736 overriding_default_conflict_methods_(allocator_.Adapter()),
6737 miranda_methods_(allocator_.Adapter()),
6738 default_methods_(allocator_.Adapter()),
6739 overriding_default_methods_(allocator_.Adapter()),
6740 move_table_(allocator_.Adapter()) {
6741 }
6742
6743 ArtMethod* FindMethod(ArtMethod* interface_method,
6744 MethodNameAndSignatureComparator& interface_name_comparator,
6745 ArtMethod* vtable_impl)
6746 REQUIRES_SHARED(Locks::mutator_lock_);
6747
6748 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6749 MethodNameAndSignatureComparator& interface_name_comparator)
6750 REQUIRES_SHARED(Locks::mutator_lock_);
6751
6752 bool HasNewVirtuals() const {
6753 return !(miranda_methods_.empty() &&
6754 default_methods_.empty() &&
6755 overriding_default_methods_.empty() &&
6756 overriding_default_conflict_methods_.empty() &&
6757 default_conflict_methods_.empty());
6758 }
6759
6760 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6761
6762 ObjPtr<mirror::PointerArray> UpdateVtable(
6763 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6764 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6765
6766 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6767
6768 void UpdateIMT(ArtMethod** out_imt);
6769
6770 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6771 if (kIsDebugBuild) {
6772 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6773 // Check that there are no stale methods are in the dex cache array.
6774 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6775 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006776 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6777 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006778 CHECK(move_table_.find(m) == move_table_.end() ||
6779 // The original versions of copied methods will still be present so allow those too.
6780 // Note that if the first check passes this might fail to GetDeclaringClass().
6781 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6782 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6783 [m] (ArtMethod& meth) {
6784 return &meth == m;
6785 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6786 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6787 }
6788 }
6789 }
6790
6791 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6792 LengthPrefixedArray<ArtMethod>* methods) {
6793 if (kIsDebugBuild) {
6794 CHECK(methods != nullptr);
6795 // Put some random garbage in old methods to help find stale pointers.
6796 if (methods != old_methods && old_methods != nullptr) {
6797 // Need to make sure the GC is not running since it could be scanning the methods we are
6798 // about to overwrite.
6799 ScopedThreadStateChange tsc(self_, kSuspended);
6800 gc::ScopedGCCriticalSection gcs(self_,
6801 gc::kGcCauseClassLinker,
6802 gc::kCollectorTypeClassLinker);
6803 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6804 method_size_,
6805 method_alignment_);
6806 memset(old_methods, 0xFEu, old_size);
6807 }
6808 }
6809 }
6810
6811 private:
6812 size_t NumberOfNewVirtuals() const {
6813 return miranda_methods_.size() +
6814 default_methods_.size() +
6815 overriding_default_conflict_methods_.size() +
6816 overriding_default_methods_.size() +
6817 default_conflict_methods_.size();
6818 }
6819
6820 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6821 return !klass_->IsInterface();
6822 }
6823
6824 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6825 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6826 << "Interfaces should only have default-conflict methods appended to them.";
6827 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6828 << miranda_methods_.size()
6829 << " default_methods=" << default_methods_.size()
6830 << " overriding_default_methods=" << overriding_default_methods_.size()
6831 << " default_conflict_methods=" << default_conflict_methods_.size()
6832 << " overriding_default_conflict_methods="
6833 << overriding_default_conflict_methods_.size();
6834 }
6835
6836 ClassLinker* class_linker_;
6837 Handle<mirror::Class> klass_;
6838 size_t method_alignment_;
6839 size_t method_size_;
6840 Thread* const self_;
6841
6842 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6843 // the virtual methods array.
6844 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6845 // during cross compilation.
6846 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6847 ArenaStack stack_;
6848 ScopedArenaAllocator allocator_;
6849
6850 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6851 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6852 ScopedArenaVector<ArtMethod*> miranda_methods_;
6853 ScopedArenaVector<ArtMethod*> default_methods_;
6854 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6855
6856 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6857};
6858
6859ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6860 ArtMethod* interface_method,
6861 MethodNameAndSignatureComparator& interface_name_comparator,
6862 ArtMethod* vtable_impl) {
6863 ArtMethod* current_method = nullptr;
6864 switch (class_linker_->FindDefaultMethodImplementation(self_,
6865 interface_method,
6866 klass_,
6867 /*out*/&current_method)) {
6868 case DefaultMethodSearchResult::kDefaultConflict: {
6869 // Default method conflict.
6870 DCHECK(current_method == nullptr);
6871 ArtMethod* default_conflict_method = nullptr;
6872 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6873 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6874 default_conflict_method = vtable_impl;
6875 } else {
6876 // See if we already have a conflict method for this method.
6877 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6878 interface_name_comparator,
6879 default_conflict_methods_,
6880 overriding_default_conflict_methods_);
6881 if (LIKELY(preexisting_conflict != nullptr)) {
6882 // We already have another conflict we can reuse.
6883 default_conflict_method = preexisting_conflict;
6884 } else {
6885 // Note that we do this even if we are an interface since we need to create this and
6886 // cannot reuse another classes.
6887 // Create a new conflict method for this to use.
6888 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6889 new(default_conflict_method) ArtMethod(interface_method,
6890 class_linker_->GetImagePointerSize());
6891 if (vtable_impl == nullptr) {
6892 // Save the conflict method. We need to add it to the vtable.
6893 default_conflict_methods_.push_back(default_conflict_method);
6894 } else {
6895 // Save the conflict method but it is already in the vtable.
6896 overriding_default_conflict_methods_.push_back(default_conflict_method);
6897 }
6898 }
6899 }
6900 current_method = default_conflict_method;
6901 break;
6902 } // case kDefaultConflict
6903 case DefaultMethodSearchResult::kDefaultFound: {
6904 DCHECK(current_method != nullptr);
6905 // Found a default method.
6906 if (vtable_impl != nullptr &&
6907 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6908 // We found a default method but it was the same one we already have from our
6909 // superclass. Don't bother adding it to our vtable again.
6910 current_method = vtable_impl;
6911 } else if (LIKELY(FillTables())) {
6912 // Interfaces don't need to copy default methods since they don't have vtables.
6913 // Only record this default method if it is new to save space.
6914 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6915 // would make lookup for interface super much faster. (We would only need to scan
6916 // the iftable to find if there is a NSME or AME.)
6917 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6918 default_methods_,
6919 overriding_default_methods_);
6920 if (old == nullptr) {
6921 // We found a default method implementation and there were no conflicts.
6922 if (vtable_impl == nullptr) {
6923 // Save the default method. We need to add it to the vtable.
6924 default_methods_.push_back(current_method);
6925 } else {
6926 // Save the default method but it is already in the vtable.
6927 overriding_default_methods_.push_back(current_method);
6928 }
6929 } else {
6930 CHECK(old == current_method) << "Multiple default implementations selected!";
6931 }
6932 }
6933 break;
6934 } // case kDefaultFound
6935 case DefaultMethodSearchResult::kAbstractFound: {
6936 DCHECK(current_method == nullptr);
6937 // Abstract method masks all defaults.
6938 if (vtable_impl != nullptr &&
6939 vtable_impl->IsAbstract() &&
6940 !vtable_impl->IsDefaultConflicting()) {
6941 // We need to make this an abstract method but the version in the vtable already is so
6942 // don't do anything.
6943 current_method = vtable_impl;
6944 }
6945 break;
6946 } // case kAbstractFound
6947 }
6948 return current_method;
6949}
6950
6951ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
6952 ArtMethod* interface_method,
6953 MethodNameAndSignatureComparator& interface_name_comparator) {
6954 // Find out if there is already a miranda method we can use.
6955 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6956 miranda_methods_);
6957 if (miranda_method == nullptr) {
6958 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
6959 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6960 CHECK(miranda_method != nullptr);
6961 // Point the interface table at a phantom slot.
6962 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
6963 miranda_methods_.push_back(miranda_method);
6964 }
6965 return miranda_method;
6966}
6967
6968void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
6969 LogNewVirtuals();
6970
6971 const size_t old_method_count = klass_->NumMethods();
6972 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
6973 DCHECK_NE(old_method_count, new_method_count);
6974
6975 // Attempt to realloc to save RAM if possible.
6976 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
6977 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
6978 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6979 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6980 // CopyFrom has internal read barriers.
6981 //
6982 // TODO We should maybe move some of this into mirror::Class or at least into another method.
6983 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6984 method_size_,
6985 method_alignment_);
6986 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
6987 method_size_,
6988 method_alignment_);
6989 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
6990 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01006991 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00006992 self_, old_methods, old_methods_ptr_size, new_size));
6993 CHECK(methods != nullptr); // Native allocation failure aborts.
6994
6995 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6996 if (methods != old_methods) {
6997 // Maps from heap allocated miranda method to linear alloc miranda method.
6998 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
6999 // Copy over the old methods.
7000 for (auto& m : klass_->GetMethods(pointer_size)) {
7001 move_table_.emplace(&m, &*out);
7002 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7003 // barriers when it copies.
7004 out->CopyFrom(&m, pointer_size);
7005 ++out;
7006 }
7007 }
7008 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7009 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7010 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007011 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7012 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007013 ArtMethod& new_method = *out;
7014 new_method.CopyFrom(mir_method, pointer_size);
7015 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7016 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7017 << "Miranda method should be abstract!";
7018 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007019 // Update the entry in the method array, as the array will be used for future lookups,
7020 // where thread suspension is allowed.
7021 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7022 // would not see them.
7023 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007024 ++out;
7025 }
7026 // We need to copy the default methods into our own method table since the runtime requires that
7027 // every method on a class's vtable be in that respective class's virtual method table.
7028 // NOTE This means that two classes might have the same implementation of a method from the same
7029 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7030 // default method found on a class with one found on the declaring interface directly and must
7031 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007032 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7033 &overriding_default_methods_}) {
7034 for (size_t i = 0; i < methods_vec->size(); ++i) {
7035 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007036 ArtMethod& new_method = *out;
7037 new_method.CopyFrom(def_method, pointer_size);
7038 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7039 // verified yet it shouldn't have methods that are skipping access checks.
7040 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7041 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007042 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007043 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7044 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7045 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7046 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007047 // Update the entry in the method array, as the array will be used for future lookups,
7048 // where thread suspension is allowed.
7049 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7050 // would not see them.
7051 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007052 ++out;
7053 }
7054 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007055 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7056 &overriding_default_conflict_methods_}) {
7057 for (size_t i = 0; i < methods_vec->size(); ++i) {
7058 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007059 ArtMethod& new_method = *out;
7060 new_method.CopyFrom(conf_method, pointer_size);
7061 // This is a type of default method (there are default method impls, just a conflict) so
7062 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7063 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7064 // methods that are skipping access checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007065 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007066 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7067 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7068 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7069 DCHECK(new_method.IsDefaultConflicting());
7070 // The actual method might or might not be marked abstract since we just copied it from a
7071 // (possibly default) interface method. We need to set it entry point to be the bridge so
7072 // that the compiler will not invoke the implementation of whatever method we copied from.
7073 EnsureThrowsInvocationError(class_linker_, &new_method);
7074 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007075 // Update the entry in the method array, as the array will be used for future lookups,
7076 // where thread suspension is allowed.
7077 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7078 // would not see them.
7079 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007080 ++out;
7081 }
7082 }
7083 methods->SetSize(new_method_count);
7084 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7085}
7086
7087ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7088 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7089 ObjPtr<mirror::PointerArray> old_vtable) {
7090 // Update the vtable to the new method structures. We can skip this for interfaces since they
7091 // do not have vtables.
7092 const size_t old_vtable_count = old_vtable->GetLength();
7093 const size_t new_vtable_count = old_vtable_count +
7094 miranda_methods_.size() +
7095 default_methods_.size() +
7096 default_conflict_methods_.size();
7097
7098 ObjPtr<mirror::PointerArray> vtable =
7099 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7100 if (UNLIKELY(vtable == nullptr)) {
7101 self_->AssertPendingOOMException();
7102 return nullptr;
7103 }
7104
7105 size_t vtable_pos = old_vtable_count;
7106 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7107 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7108 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7109 default_conflict_methods_,
7110 miranda_methods_}) {
7111 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007112 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007113 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7114 // fields are references into the dex file the method was defined in. Since the ArtMethod
7115 // does not store that information it uses declaring_class_->dex_cache_.
7116 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7117 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7118 ++vtable_pos;
7119 }
7120 }
7121 DCHECK_EQ(vtable_pos, new_vtable_count);
7122
7123 // Update old vtable methods. We use the default_translations map to figure out what each
7124 // vtable entry should be updated to, if they need to be at all.
7125 for (size_t i = 0; i < old_vtable_count; ++i) {
7126 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7127 // Try and find what we need to change this method to.
7128 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007129 if (translation_it != default_translations.end()) {
7130 if (translation_it->second.IsInConflict()) {
7131 // Find which conflict method we are to use for this method.
7132 MethodNameAndSignatureComparator old_method_comparator(
7133 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7134 // We only need to look through overriding_default_conflict_methods since this is an
7135 // overridden method we are fixing up here.
7136 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7137 old_method_comparator, overriding_default_conflict_methods_);
7138 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7139 translated_method = new_conflict_method;
7140 } else if (translation_it->second.IsAbstract()) {
7141 // Find which miranda method we are to use for this method.
7142 MethodNameAndSignatureComparator old_method_comparator(
7143 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7144 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7145 miranda_methods_);
7146 DCHECK(miranda_method != nullptr);
7147 translated_method = miranda_method;
7148 } else {
7149 // Normal default method (changed from an older default or abstract interface method).
7150 DCHECK(translation_it->second.IsTranslation());
7151 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007152 auto it = move_table_.find(translated_method);
7153 DCHECK(it != move_table_.end());
7154 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007155 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007156 } else {
7157 auto it = move_table_.find(translated_method);
7158 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007159 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007160
7161 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007162 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007163 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007164 if (kIsDebugBuild) {
7165 auto* methods = klass_->GetMethodsPtr();
7166 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007167 reinterpret_cast<uintptr_t>(translated_method));
7168 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007169 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7170 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007171 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007172 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007173 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007174 }
7175 }
7176 klass_->SetVTable(vtable.Ptr());
7177 return vtable;
7178}
7179
7180void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7181 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7182 const size_t ifcount = klass_->GetIfTableCount();
7183 // Go fix up all the stale iftable pointers.
7184 for (size_t i = 0; i < ifcount; ++i) {
7185 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7186 auto* method_array = iftable->GetMethodArray(i);
7187 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7188 DCHECK(m != nullptr) << klass_->PrettyClass();
7189 auto it = move_table_.find(m);
7190 if (it != move_table_.end()) {
7191 auto* new_m = it->second;
7192 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7193 method_array->SetElementPtrSize(j, new_m, pointer_size);
7194 }
7195 }
7196 }
7197}
7198
7199void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7200 // Fix up IMT next.
7201 for (size_t i = 0; i < ImTable::kSize; ++i) {
7202 auto it = move_table_.find(out_imt[i]);
7203 if (it != move_table_.end()) {
7204 out_imt[i] = it->second;
7205 }
7206 }
7207}
7208
Alex Light705ad492015-09-21 11:36:30 -07007209// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007210bool ClassLinker::LinkInterfaceMethods(
7211 Thread* self,
7212 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007213 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007214 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007215 ArtMethod** out_imt) {
7216 StackHandleScope<3> hs(self);
7217 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007218
7219 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007220 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007221 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007222 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007223 const size_t ifcount = klass->GetIfTableCount();
7224
Vladimir Marko921094a2017-01-12 18:37:06 +00007225 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007226
7227 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7228 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007229 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007230 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007231 const bool extend_super_iftable = has_superclass;
7232 if (has_superclass && fill_tables) {
7233 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007234 unimplemented_method,
7235 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007236 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007237 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007238 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007239 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7240 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007241 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007242 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7243 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007244 }
7245 }
7246
Vladimir Marko921094a2017-01-12 18:37:06 +00007247 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7248
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007249 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007250 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007251 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7252 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7253 // they will already be null. This has the additional benefit that the declarer of a miranda
7254 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007255 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007256 --i;
Alex Light9139e002015-10-09 15:59:48 -07007257 DCHECK_LT(i, ifcount);
7258
Alex Light705ad492015-09-21 11:36:30 -07007259 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007260 if (num_methods > 0) {
7261 StackHandleScope<2> hs2(self);
7262 const bool is_super = i < super_ifcount;
7263 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007264 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7265 // conflict methods. Just set this as nullptr in those cases.
7266 Handle<mirror::PointerArray> method_array(fill_tables
7267 ? hs2.NewHandle(iftable->GetMethodArray(i))
7268 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007269
Alex Lighte64300b2015-12-15 15:02:47 -08007270 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007271 ScopedNullHandle<mirror::PointerArray> null_handle;
7272 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007273 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007274
Alex Light9139e002015-10-09 15:59:48 -07007275 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7276 // and confusing. Default methods should always look through all the superclasses
7277 // because they are the last choice of an implementation. We get around this by looking
7278 // at the super-classes iftable methods (copied into method_array previously) when we are
7279 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007280 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007281 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007282 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007283 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007284 using_virtuals = true;
7285 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7286 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007287 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007288 // For a new interface, however, we need the whole vtable in case a new
7289 // interface method is implemented in the whole superclass.
7290 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007291 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007292 input_vtable_array = vtable;
7293 input_array_length = input_vtable_array->GetLength();
7294 }
Alex Lighte64300b2015-12-15 15:02:47 -08007295
Alex Lighteb7c1442015-08-31 13:17:42 -07007296 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007297 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007298 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007299 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007300 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007301 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007302 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007303 // For each method listed in the interface's method list, find the
7304 // matching method in our class's method list. We want to favor the
7305 // subclass over the superclass, which just requires walking
7306 // back from the end of the vtable. (This only matters if the
7307 // superclass defines a private method and this class redefines
7308 // it -- otherwise it would use the same vtable slot. In .dex files
7309 // those don't end up in the virtual method table, so it shouldn't
7310 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007311 //
7312 // To find defaults we need to do the same but also go over interfaces.
7313 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007314 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007315 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007316 ArtMethod* vtable_method = using_virtuals ?
7317 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007318 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7319 ArtMethod* vtable_method_for_name_comparison =
7320 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007321 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007322 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007323 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007324 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7325 // allocations.
7326 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007327 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007328 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007329 vtable_method->PrettyMethod().c_str(),
7330 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007331 return false;
Alex Light9139e002015-10-09 15:59:48 -07007332 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007333 // We might have a newer, better, default method for this, so we just skip it. If we
7334 // are still using this we will select it again when scanning for default methods. To
7335 // obviate the need to copy the method again we will make a note that we already found
7336 // a default here.
7337 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007338 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007339 break;
7340 } else {
7341 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007342 if (LIKELY(fill_tables)) {
7343 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7344 // Place method in imt if entry is empty, place conflict otherwise.
7345 SetIMTRef(unimplemented_method,
7346 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007347 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007348 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007349 /*out*/imt_ptr);
7350 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007351 break;
7352 }
7353 }
Alex Light9139e002015-10-09 15:59:48 -07007354 }
7355 // Continue on to the next method if we are done.
7356 if (LIKELY(found_impl)) {
7357 continue;
7358 } else if (LIKELY(super_interface)) {
7359 // Don't look for a default implementation when the super-method is implemented directly
7360 // by the class.
7361 //
7362 // See if we can use the superclasses method and skip searching everything else.
7363 // Note: !found_impl && super_interface
7364 CHECK(extend_super_iftable);
7365 // If this is a super_interface method it is possible we shouldn't override it because a
7366 // superclass could have implemented it directly. We get the method the superclass used
7367 // to implement this to know if we can override it with a default method. Doing this is
7368 // safe since we know that the super_iftable is filled in so we can simply pull it from
7369 // there. We don't bother if this is not a super-classes interface since in that case we
7370 // have scanned the entire vtable anyway and would have found it.
7371 // TODO This is rather dirty but it is faster than searching through the entire vtable
7372 // every time.
7373 ArtMethod* supers_method =
7374 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7375 DCHECK(supers_method != nullptr);
7376 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007377 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007378 // The method is not overridable by a default method (i.e. it is directly implemented
7379 // in some class). Therefore move onto the next interface method.
7380 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007381 } else {
7382 // If the super-classes method is override-able by a default method we need to keep
7383 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7384 // 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 -07007385 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7386 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7387 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007388 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007389 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7390 << " and not 'nullptr' or "
7391 << supers_method->PrettyMethod()
7392 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007393 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007394 }
7395 }
7396 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007397 ArtMethod* current_method = helper.FindMethod(interface_method,
7398 interface_name_comparator,
7399 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007400 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007401 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007402 // We could not find an implementation for this method and since it is a brand new
7403 // interface we searched the entire vtable (and all default methods) for an
7404 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007405 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7406 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007407 }
7408
7409 if (current_method != nullptr) {
7410 // We found a default method implementation. Record it in the iftable and IMT.
7411 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7412 SetIMTRef(unimplemented_method,
7413 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007414 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007415 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007416 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007417 }
7418 }
Alex Light705ad492015-09-21 11:36:30 -07007419 } // For each method in interface end.
7420 } // if (num_methods > 0)
7421 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007422 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007423 if (helper.HasNewVirtuals()) {
7424 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7425 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7426 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7427
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007428 // 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 -07007429 // suspension assert.
7430 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007431
Alex Light705ad492015-09-21 11:36:30 -07007432 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007433 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007434 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007435 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007436 return false;
7437 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007438 helper.UpdateIfTable(iftable);
7439 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007440 }
Alex Light705ad492015-09-21 11:36:30 -07007441
Vladimir Marko921094a2017-01-12 18:37:06 +00007442 helper.CheckNoStaleMethodsInDexCache();
7443 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007444 } else {
7445 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007446 }
Alex Light705ad492015-09-21 11:36:30 -07007447 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007448 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007449 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007450 return true;
7451}
7452
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007453bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007454 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007455 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007456}
7457
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007458bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007459 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007460 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007461}
7462
Brian Carlstromdbc05252011-09-09 01:59:59 -07007463struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007464 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007465 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007466 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007467 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007468 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007469 // 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 -07007470 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7471 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007472 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007473 if (type1 == Primitive::kPrimNot) {
7474 // Reference always goes first.
7475 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007476 }
Vladimir Markod5777482014-11-12 17:02:02 +00007477 if (type2 == Primitive::kPrimNot) {
7478 // Reference always goes first.
7479 return false;
7480 }
7481 size_t size1 = Primitive::ComponentSize(type1);
7482 size_t size2 = Primitive::ComponentSize(type2);
7483 if (size1 != size2) {
7484 // Larger primitive types go first.
7485 return size1 > size2;
7486 }
7487 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7488 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007489 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007490 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7491 // by name and for equal names by type id index.
7492 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7493 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007494 }
7495};
7496
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007497bool ClassLinker::LinkFields(Thread* self,
7498 Handle<mirror::Class> klass,
7499 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007500 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007501 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007502 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007503 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7504 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007505
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007506 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007507 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007508 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007509 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007510 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007511 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007512 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007513 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007514 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007515 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007516 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007517 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007518
David Sehr709b0702016-10-13 09:12:37 -07007519 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007520
Brian Carlstromdbc05252011-09-09 01:59:59 -07007521 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007522 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007523 //
7524 // The overall sort order order is:
7525 // 1) All object reference fields, sorted alphabetically.
7526 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7527 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7528 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7529 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7530 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7531 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7532 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7533 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7534 //
7535 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7536 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007537 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007538 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007539 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007540 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007541 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007542 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007543 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7544 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007545
Fred Shih381e4ca2014-08-25 17:24:27 -07007546 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007547 size_t current_field = 0;
7548 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007549 FieldGaps gaps;
7550
Brian Carlstromdbc05252011-09-09 01:59:59 -07007551 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007552 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007553 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007554 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007555 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007556 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007557 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007558 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7559 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007560 MemberOffset old_offset = field_offset;
7561 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7562 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7563 }
Roland Levillain14d90572015-07-16 10:52:26 +01007564 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007565 grouped_and_sorted_fields.pop_front();
7566 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007567 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007568 field_offset = MemberOffset(field_offset.Uint32Value() +
7569 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007570 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007571 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7572 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007573 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7574 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7575 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7576 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007577 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7578 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007579 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007580
Elliott Hughesadb460d2011-10-05 17:02:34 -07007581 // 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 -07007582 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007583 // We know there are no non-reference fields in the Reference classes, and we know
7584 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007585 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007586 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007587 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007588 --num_reference_fields;
7589 }
7590
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007591 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007592 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007593 if (is_static) {
7594 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007595 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007596 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007597 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007598 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007599 if (num_reference_fields == 0 || super_class == nullptr) {
7600 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007601 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007602 if (super_class == nullptr ||
7603 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7604 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007605 }
7606 }
7607 if (kIsDebugBuild) {
7608 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7609 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007610 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007611 while (cur_super != nullptr) {
7612 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7613 cur_super = cur_super->GetSuperClass();
7614 }
7615 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007616 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007617 } else {
7618 // Check that there is at least num_reference_fields other than Object.class.
7619 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007620 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007621 }
7622 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007623 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007624 std::string temp;
7625 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7626 size_t previous_size = klass->GetObjectSize();
7627 if (previous_size != 0) {
7628 // Make sure that we didn't originally have an incorrect size.
7629 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007630 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007631 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007632 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007633 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007634
7635 if (kIsDebugBuild) {
7636 // Make sure that the fields array is ordered by name but all reference
7637 // offsets are at the beginning as far as alignment allows.
7638 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007639 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007640 : klass->GetFirstReferenceInstanceFieldOffset();
7641 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7642 num_reference_fields *
7643 sizeof(mirror::HeapReference<mirror::Object>));
7644 MemberOffset current_ref_offset = start_ref_offset;
7645 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007646 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007647 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007648 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7649 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007650 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007651 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007652 // NOTE: The field names can be the same. This is not possible in the Java language
7653 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007654 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007655 }
7656 Primitive::Type type = field->GetTypeAsPrimitiveType();
7657 bool is_primitive = type != Primitive::kPrimNot;
7658 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7659 strcmp("referent", field->GetName()) == 0) {
7660 is_primitive = true; // We lied above, so we have to expect a lie here.
7661 }
7662 MemberOffset offset = field->GetOffsetDuringLinking();
7663 if (is_primitive) {
7664 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7665 // Shuffled before references.
7666 size_t type_size = Primitive::ComponentSize(type);
7667 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7668 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7669 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7670 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7671 }
7672 } else {
7673 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7674 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7675 sizeof(mirror::HeapReference<mirror::Object>));
7676 }
7677 }
7678 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7679 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007680 return true;
7681}
7682
Vladimir Marko76649e82014-11-10 18:32:59 +00007683// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007684void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007685 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007686 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007687 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007688 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007689 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007690 // Compute reference offsets unless our superclass overflowed.
7691 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7692 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007693 if (num_reference_fields != 0u) {
7694 // All of the fields that contain object references are guaranteed be grouped in memory
7695 // starting at an appropriately aligned address after super class object data.
7696 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7697 sizeof(mirror::HeapReference<mirror::Object>));
7698 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007699 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007700 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007701 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007702 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007703 reference_offsets |= (0xffffffffu << start_bit) &
7704 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007705 }
7706 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007707 }
7708 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007709 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007710}
7711
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007712ObjPtr<mirror::String> ClassLinker::ResolveString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007713 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007714 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007715 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007716 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007717 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007718 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007719 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007720 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07007721 uint32_t utf16_length;
7722 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007723 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007724 if (string != nullptr) {
7725 dex_cache->SetResolvedString(string_idx, string);
7726 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007727 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007728}
7729
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007730ObjPtr<mirror::String> ClassLinker::LookupString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007731 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007732 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007733 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007734 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007735 return resolved;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007736 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007737 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007738 uint32_t utf16_length;
7739 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007740 ObjPtr<mirror::String> string =
7741 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007742 if (string != nullptr) {
7743 dex_cache->SetResolvedString(string_idx, string);
7744 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007745 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007746}
7747
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007748ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
7749 ObjPtr<mirror::DexCache> dex_cache,
7750 ObjPtr<mirror::ClassLoader> class_loader) {
7751 const DexFile& dex_file = *dex_cache->GetDexFile();
7752 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7753 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7754 ObjPtr<mirror::Class> type = nullptr;
7755 if (descriptor[1] == '\0') {
7756 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7757 // for primitive classes that aren't backed by dex files.
7758 type = FindPrimitiveClass(descriptor[0]);
7759 } else {
7760 Thread* const self = Thread::Current();
7761 DCHECK(self != nullptr);
7762 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7763 // Find the class in the loaded classes table.
7764 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
7765 }
7766 if (type != nullptr) {
7767 if (type->IsResolved()) {
7768 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07007769 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007770 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007771 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007772 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007773 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007774}
7775
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007776ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
7777 Handle<mirror::DexCache> dex_cache,
7778 Handle<mirror::ClassLoader> class_loader) {
7779 Thread* self = Thread::Current();
7780 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
7781 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
7782 if (resolved != nullptr) {
7783 // TODO: we used to throw here if resolved's class loader was not the
7784 // boot class loader. This was to permit different classes with the
7785 // same name to be loaded simultaneously by different loaders
7786 dex_cache->SetResolvedType(type_idx, resolved);
7787 } else {
7788 CHECK(self->IsExceptionPending())
7789 << "Expected pending exception for failed resolution of: " << descriptor;
7790 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7791 StackHandleScope<1> hs(self);
7792 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01007793 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007794 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7795 self->ClearException();
7796 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7797 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007798 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007799 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007800 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007801 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00007802 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007803}
7804
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007805ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
7806 ObjPtr<mirror::DexCache> dex_cache,
7807 ObjPtr<mirror::ClassLoader> class_loader,
7808 uint32_t method_idx) {
7809 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7810 // functions can optimize the search if the dex_cache is the same as the DexCache
7811 // of the class, with fall-back to name and signature search otherwise.
7812 ArtMethod* resolved = nullptr;
7813 if (klass->IsInterface()) {
7814 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7815 } else {
7816 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7817 }
7818 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00007819 if (resolved != nullptr &&
Narayan Kamathf5f1f802018-04-03 15:23:46 +01007820 hiddenapi::GetMemberAction(
7821 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00007822 resolved = nullptr;
7823 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007824 if (resolved != nullptr) {
7825 // In case of jmvti, the dex file gets verified before being registered, so first
7826 // check if it's registered before checking class tables.
7827 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007828 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
7829 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007830 << "DexFile referrer: " << dex_file.GetLocation()
7831 << " ClassLoader: " << DescribeLoaders(class_loader, "");
7832 // Be a good citizen and update the dex cache to speed subsequent calls.
7833 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007834 // Disable the following invariant check as the verifier breaks it. b/73760543
7835 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7836 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
7837 // << "Method: " << resolved->PrettyMethod() << ", "
7838 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
7839 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007840 }
7841 return resolved;
7842}
7843
David Brazdil4525e0b2018-04-05 16:57:32 +01007844// Returns true if `method` is either null or hidden.
7845// Does not print any warnings if it is hidden.
7846static bool CheckNoSuchMethod(ArtMethod* method,
7847 ObjPtr<mirror::DexCache> dex_cache,
7848 ObjPtr<mirror::ClassLoader> class_loader)
7849 REQUIRES_SHARED(Locks::mutator_lock_) {
7850 return method == nullptr ||
7851 hiddenapi::GetMemberAction(method,
7852 class_loader,
7853 dex_cache,
7854 hiddenapi::kNone) // do not print warnings
7855 == hiddenapi::kDeny;
7856}
7857
7858ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
7859 ObjPtr<mirror::DexCache> dex_cache,
7860 ObjPtr<mirror::ClassLoader> class_loader,
7861 uint32_t method_idx) {
7862 if (klass->IsInterface()) {
7863 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7864 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
7865 } else {
7866 // If there was an interface method with the same signature, we would have
7867 // found it in the "copied" methods. Only DCHECK that the interface method
7868 // really does not exist.
7869 if (kIsDebugBuild) {
7870 ArtMethod* method =
7871 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7872 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
7873 }
7874 return nullptr;
7875 }
7876}
7877
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007878template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00007879ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007880 Handle<mirror::DexCache> dex_cache,
7881 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007882 ArtMethod* referrer,
7883 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007884 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007885 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007886 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007887 PointerSize pointer_size = image_pointer_size_;
7888 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007889 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007890 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7891 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007892 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7893 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007894 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007895 return resolved;
7896 }
Vladimir Marko89011192017-12-11 13:45:05 +00007897 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007898 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007899 ObjPtr<mirror::Class> klass = nullptr;
7900 if (valid_dex_cache_method) {
7901 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7902 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007903 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007904 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007905 // We normaly should not end up here. However the verifier currently doesn't guarantee
7906 // the invariant of having the klass in the class table. b/73760543
7907 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007908 }
Vladimir Markoba118822017-06-12 15:41:56 +01007909 } else {
7910 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007911 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01007912 if (klass == nullptr) {
7913 DCHECK(Thread::Current()->IsExceptionPending());
7914 return nullptr;
7915 }
7916 }
7917
7918 // Check if the invoke type matches the class type.
7919 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
7920 CheckInvokeClassMismatch</* kThrow */ true>(
7921 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007922 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007923 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007924 }
Vladimir Markoba118822017-06-12 15:41:56 +01007925
7926 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007927 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007928 }
Vladimir Markoba118822017-06-12 15:41:56 +01007929
7930 // Note: We can check for IllegalAccessError only if we have a referrer.
7931 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
7932 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
7933 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
7934 if (!referring_class->CheckResolvedMethodAccess(methods_class,
7935 resolved,
7936 dex_cache.Get(),
7937 method_idx,
7938 type)) {
7939 DCHECK(Thread::Current()->IsExceptionPending());
7940 return nullptr;
7941 }
7942 }
7943
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007944 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01007945 if (LIKELY(resolved != nullptr) &&
7946 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
7947 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007948 return resolved;
7949 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007950 // If we had a method, or if we can find one with another lookup type,
7951 // it's an incompatible-class-change error.
7952 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01007953 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007954 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007955 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007956 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007957 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007958 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007959 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7960 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01007961 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07007962 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007963 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007964 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07007965 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007966}
7967
Vladimir Marko89011192017-12-11 13:45:05 +00007968ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00007969 Handle<mirror::DexCache> dex_cache,
7970 Handle<mirror::ClassLoader> class_loader) {
7971 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007972 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007973 if (resolved != nullptr) {
7974 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00007975 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7976 return resolved;
7977 }
7978 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007979 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
7980 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00007981 if (klass == nullptr) {
7982 Thread::Current()->AssertPendingException();
7983 return nullptr;
7984 }
7985 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01007986 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7987 } else {
7988 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00007989 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00007990 if (resolved != nullptr &&
Narayan Kamathf5f1f802018-04-03 15:23:46 +01007991 hiddenapi::GetMemberAction(
7992 resolved, class_loader.Get(), dex_cache.Get(), hiddenapi::kLinking) == hiddenapi::kDeny) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00007993 resolved = nullptr;
7994 }
Jeff Hao13e748b2015-08-25 20:44:19 +00007995 return resolved;
7996}
7997
Vladimir Markof44d36c2017-03-14 14:18:46 +00007998ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
7999 ObjPtr<mirror::DexCache> dex_cache,
8000 ObjPtr<mirror::ClassLoader> class_loader,
8001 bool is_static) {
8002 const DexFile& dex_file = *dex_cache->GetDexFile();
8003 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8004 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8005 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008006 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008007 }
8008 if (klass == nullptr) {
8009 // The class has not been resolved yet, so the field is also unresolved.
8010 return nullptr;
8011 }
8012 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008013
David Brazdil1ab0fa82018-05-04 11:28:03 +01008014 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008015}
8016
Vladimir Markoe11dd502017-12-08 14:09:45 +00008017ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008018 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008019 Handle<mirror::ClassLoader> class_loader,
8020 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008021 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008022 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008023 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008024 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008025 return resolved;
8026 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008027 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008028 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008029 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008030 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008031 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008032 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008033 }
8034
David Brazdil1ab0fa82018-05-04 11:28:03 +01008035 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008036 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008037 const char* name = dex_file.GetFieldName(field_id);
8038 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008039 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008040 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008041 return resolved;
8042}
8043
Vladimir Markoe11dd502017-12-08 14:09:45 +00008044ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008045 Handle<mirror::DexCache> dex_cache,
8046 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008047 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008048 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008049 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008050 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008051 return resolved;
8052 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008053 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008054 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008055 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008056 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008057 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008058 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008059 }
8060
David Brazdil1ab0fa82018-05-04 11:28:03 +01008061 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8062 if (resolved == nullptr) {
8063 const char* name = dex_file.GetFieldName(field_id);
8064 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008065 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008066 }
8067 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008068}
8069
David Brazdil1ab0fa82018-05-04 11:28:03 +01008070ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8071 ObjPtr<mirror::DexCache> dex_cache,
8072 ObjPtr<mirror::ClassLoader> class_loader,
8073 uint32_t field_idx,
8074 bool is_static) {
8075 ArtField* resolved = nullptr;
8076 Thread* self = is_static ? Thread::Current() : nullptr;
8077 const DexFile& dex_file = *dex_cache->GetDexFile();
8078
8079 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8080 : klass->FindInstanceField(dex_cache, field_idx);
8081
8082 if (resolved == nullptr) {
8083 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8084 const char* name = dex_file.GetFieldName(field_id);
8085 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8086 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8087 : klass->FindInstanceField(name, type);
8088 }
8089
8090 if (resolved != nullptr &&
8091 hiddenapi::GetMemberAction(
8092 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
8093 resolved = nullptr;
8094 }
8095
8096 if (resolved != nullptr) {
8097 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8098 }
8099
8100 return resolved;
8101}
8102
8103ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8104 ObjPtr<mirror::DexCache> dex_cache,
8105 ObjPtr<mirror::ClassLoader> class_loader,
8106 uint32_t field_idx) {
8107 ArtField* resolved = nullptr;
8108 Thread* self = Thread::Current();
8109 const DexFile& dex_file = *dex_cache->GetDexFile();
8110 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8111
8112 const char* name = dex_file.GetFieldName(field_id);
8113 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8114 resolved = mirror::Class::FindField(self, klass, name, type);
8115
8116 if (resolved != nullptr &&
8117 hiddenapi::GetMemberAction(
8118 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
8119 resolved = nullptr;
8120 }
8121
8122 if (resolved != nullptr) {
8123 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8124 }
8125
8126 return resolved;
8127}
8128
Vladimir Markoaf940202017-12-08 15:01:18 +00008129ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8130 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008131 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008132 Handle<mirror::DexCache> dex_cache,
8133 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008134 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008135 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008136
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008137 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008138 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008139 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008140 }
8141
Narayan Kamath25352fc2016-08-03 12:46:58 +01008142 StackHandleScope<4> hs(self);
8143
8144 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008145 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008146 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8147 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008148 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008149 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008150 DCHECK(self->IsExceptionPending());
8151 return nullptr;
8152 }
8153
8154 // Then resolve the argument types.
8155 //
8156 // TODO: Is there a better way to figure out the number of method arguments
8157 // other than by looking at the shorty ?
8158 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8159
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008160 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008161 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008162 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8163 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008164 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008165 DCHECK(self->IsExceptionPending());
8166 return nullptr;
8167 }
8168
8169 DexFileParameterIterator it(dex_file, proto_id);
8170 int32_t i = 0;
8171 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8172 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008173 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008174 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008175 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008176 DCHECK(self->IsExceptionPending());
8177 return nullptr;
8178 }
8179
8180 method_params->Set(i++, param_class.Get());
8181 }
8182
8183 DCHECK(!it.HasNext());
8184
8185 Handle<mirror::MethodType> type = hs.NewHandle(
8186 mirror::MethodType::Create(self, return_type, method_params));
8187 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8188
8189 return type.Get();
8190}
8191
Vladimir Markoaf940202017-12-08 15:01:18 +00008192ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008193 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008194 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008195 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008196 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8197 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008198 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008199}
8200
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008201mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8202 Thread* self,
8203 const DexFile::MethodHandleItem& method_handle,
8204 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008205 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008206 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8207 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008208 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008209 bool is_static;
8210 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008211 switch (handle_type) {
8212 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008213 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008214 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008215 is_static = true;
8216 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008217 break;
8218 }
8219 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008220 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008221 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008222 is_static = true;
8223 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008224 break;
8225 }
8226 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008227 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008228 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008229 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008230 num_params = 2;
8231 break;
8232 }
8233 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008234 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008235 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008236 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008237 num_params = 1;
8238 break;
8239 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008240 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008241 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008242 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008243 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008244 case DexFile::MethodHandleType::kInvokeInterface:
8245 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008246 }
8247
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008248 ArtField* target_field =
8249 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8250 if (LIKELY(target_field != nullptr)) {
8251 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8252 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8253 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8254 ThrowIllegalAccessErrorField(referring_class, target_field);
8255 return nullptr;
8256 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008257 if (UNLIKELY(is_put && target_field->IsFinal())) {
8258 ThrowIllegalAccessErrorField(referring_class, target_field);
8259 return nullptr;
8260 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008261 } else {
8262 DCHECK(Thread::Current()->IsExceptionPending());
8263 return nullptr;
8264 }
8265
8266 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008267 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8268 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8269 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8270 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008271 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008272 DCHECK(self->IsExceptionPending());
8273 return nullptr;
8274 }
8275
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008276 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008277 Handle<mirror::Class> return_type;
8278 switch (handle_type) {
8279 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008280 method_params->Set(0, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008281 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8282 break;
8283 }
8284 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008285 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008286 break;
8287 }
8288 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008289 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008290 method_params->Set(1, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008291 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8292 break;
8293 }
8294 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008295 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008296 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008297 break;
8298 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008299 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008300 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008301 case DexFile::MethodHandleType::kInvokeConstructor:
8302 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008303 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008304 UNREACHABLE();
8305 }
8306
8307 for (int32_t i = 0; i < num_params; ++i) {
8308 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8309 DCHECK(self->IsExceptionPending());
8310 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008311 }
8312 }
8313
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008314 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008315 DCHECK(self->IsExceptionPending());
8316 return nullptr;
8317 }
8318
8319 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008320 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8321 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008322 DCHECK(self->IsExceptionPending());
8323 return nullptr;
8324 }
Orion Hodson631827d2017-04-10 14:53:47 +01008325
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008326 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8327 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8328}
8329
8330mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8331 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008332 const DexFile::MethodHandleItem& method_handle,
8333 ArtMethod* referrer) {
8334 DexFile::MethodHandleType handle_type =
8335 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8336 mirror::MethodHandle::Kind kind;
8337 uint32_t receiver_count = 0;
8338 ArtMethod* target_method = nullptr;
8339 switch (handle_type) {
8340 case DexFile::MethodHandleType::kStaticPut:
8341 case DexFile::MethodHandleType::kStaticGet:
8342 case DexFile::MethodHandleType::kInstancePut:
8343 case DexFile::MethodHandleType::kInstanceGet:
8344 UNREACHABLE();
8345 case DexFile::MethodHandleType::kInvokeStatic: {
8346 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8347 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008348 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8349 method_handle.field_or_method_idx_,
8350 referrer,
8351 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008352 break;
8353 }
8354 case DexFile::MethodHandleType::kInvokeInstance: {
8355 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8356 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008357 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8358 method_handle.field_or_method_idx_,
8359 referrer,
8360 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008361 break;
8362 }
8363 case DexFile::MethodHandleType::kInvokeConstructor: {
8364 // Constructors are currently implemented as a transform. They
8365 // are special cased later in this method.
8366 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8367 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008368 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8369 method_handle.field_or_method_idx_,
8370 referrer,
8371 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008372 break;
8373 }
8374 case DexFile::MethodHandleType::kInvokeDirect: {
8375 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8376 receiver_count = 1;
8377 StackHandleScope<2> hs(self);
8378 // A constant method handle with type kInvokeDirect can refer to
8379 // a method that is private or to a method in a super class. To
8380 // disambiguate the two options, we resolve the method ignoring
8381 // the invocation type to determine if the method is private. We
8382 // then resolve again specifying the intended invocation type to
8383 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008384 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008385 hs.NewHandle(referrer->GetDexCache()),
8386 hs.NewHandle(referrer->GetClassLoader()));
8387 if (UNLIKELY(target_method == nullptr)) {
8388 break;
8389 }
8390
8391 if (target_method->IsPrivate()) {
8392 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008393 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8394 method_handle.field_or_method_idx_,
8395 referrer,
8396 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008397 } else {
8398 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008399 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8400 method_handle.field_or_method_idx_,
8401 referrer,
8402 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008403 if (UNLIKELY(target_method == nullptr)) {
8404 break;
8405 }
8406 // Find the method specified in the parent in referring class
8407 // so invoke-super invokes the method in the parent of the
8408 // referrer.
8409 target_method =
8410 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8411 kRuntimePointerSize);
8412 }
8413 break;
8414 }
8415 case DexFile::MethodHandleType::kInvokeInterface: {
8416 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8417 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008418 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8419 method_handle.field_or_method_idx_,
8420 referrer,
8421 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008422 break;
8423 }
Orion Hodson631827d2017-04-10 14:53:47 +01008424 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008425
8426 if (UNLIKELY(target_method == nullptr)) {
8427 DCHECK(Thread::Current()->IsExceptionPending());
8428 return nullptr;
8429 }
8430
8431 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8432 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8433 uint32_t access_flags = target_method->GetAccessFlags();
8434 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8435 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8436 return nullptr;
8437 }
8438
8439 // Calculate the number of parameters from the method shorty. We add the
8440 // receiver count (0 or 1) and deduct one for the return value.
8441 uint32_t shorty_length;
8442 target_method->GetShorty(&shorty_length);
8443 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8444
8445 StackHandleScope<7> hs(self);
8446 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8447 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8448 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8449 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8450 if (method_params.Get() == nullptr) {
8451 DCHECK(self->IsExceptionPending());
8452 return nullptr;
8453 }
8454
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008455 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008456 if (receiver_count != 0) {
8457 // Insert receiver
8458 method_params->Set(index++, target_method->GetDeclaringClass());
8459 }
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008460 DexFileParameterIterator it(*target_method->GetDexFile(), target_method->GetPrototype());
8461 Handle<mirror::DexCache> target_method_dex_cache(hs.NewHandle(target_method->GetDexCache()));
8462 Handle<mirror::ClassLoader> target_method_class_loader(hs.NewHandle(target_method->GetClassLoader()));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008463 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008464 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008465 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008466 ObjPtr<mirror::Class> klass = ResolveType(type_idx,
8467 target_method_dex_cache,
8468 target_method_class_loader);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008469 if (nullptr == klass) {
8470 DCHECK(self->IsExceptionPending());
8471 return nullptr;
8472 }
8473 method_params->Set(index++, klass);
8474 it.Next();
8475 }
8476
Vladimir Markob45528c2017-07-27 14:14:28 +01008477 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008478 if (UNLIKELY(return_type.IsNull())) {
8479 DCHECK(self->IsExceptionPending());
8480 return nullptr;
8481 }
8482
8483 Handle<mirror::MethodType>
8484 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8485 if (UNLIKELY(method_type.IsNull())) {
8486 DCHECK(self->IsExceptionPending());
8487 return nullptr;
8488 }
8489
8490 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8491 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8492 Handle<mirror::MethodHandlesLookup> lookup =
8493 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8494 return lookup->FindConstructor(self, constructor_class, method_type);
8495 }
8496
8497 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8498 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8499}
8500
Vladimir Markoaf940202017-12-08 15:01:18 +00008501ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8502 uint32_t method_handle_idx,
8503 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008504 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008505 const DexFile* const dex_file = referrer->GetDexFile();
8506 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8507 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8508 case DexFile::MethodHandleType::kStaticPut:
8509 case DexFile::MethodHandleType::kStaticGet:
8510 case DexFile::MethodHandleType::kInstancePut:
8511 case DexFile::MethodHandleType::kInstanceGet:
8512 return ResolveMethodHandleForField(self, method_handle, referrer);
8513 case DexFile::MethodHandleType::kInvokeStatic:
8514 case DexFile::MethodHandleType::kInvokeInstance:
8515 case DexFile::MethodHandleType::kInvokeConstructor:
8516 case DexFile::MethodHandleType::kInvokeDirect:
8517 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008518 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008519 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008520}
8521
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008522bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8523 return (entry_point == GetQuickResolutionStub()) ||
8524 (quick_resolution_trampoline_ == entry_point);
8525}
8526
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008527bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8528 return (entry_point == GetQuickToInterpreterBridge()) ||
8529 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8530}
8531
8532bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8533 return (entry_point == GetQuickGenericJniStub()) ||
8534 (quick_generic_jni_trampoline_ == entry_point);
8535}
8536
David Sehra49e0532017-08-25 08:05:29 -07008537bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8538 return entry_point == GetJniDlsymLookupStub();
8539}
8540
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008541const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8542 return GetQuickGenericJniStub();
8543}
8544
Mathieu Chartiere401d142015-04-22 13:56:20 -07008545void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008546 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008547 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8548 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008549 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008550 }
8551}
8552
Alex Lightdb01a092017-04-03 15:39:55 -07008553void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8554 DCHECK(method->IsObsolete());
8555 // We cannot mess with the entrypoints of native methods because they are used to determine how
8556 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8557 if (!method->IsNative()) {
8558 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8559 }
8560}
8561
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008562void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008563 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008564 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008565 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8566 << NumNonZygoteClasses() << "\n";
8567}
8568
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008569class CountClassesVisitor : public ClassLoaderVisitor {
8570 public:
8571 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8572
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008573 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008574 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008575 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008576 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008577 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8578 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008579 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008580 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008581
8582 size_t num_zygote_classes;
8583 size_t num_non_zygote_classes;
8584};
8585
8586size_t ClassLinker::NumZygoteClasses() const {
8587 CountClassesVisitor visitor;
8588 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008589 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008590}
8591
8592size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008593 CountClassesVisitor visitor;
8594 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008595 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008596}
8597
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008598size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008599 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008600 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008601 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008602}
8603
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008604pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008605 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008606}
8607
8608pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008609 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008610}
8611
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008612void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008613 DCHECK(!init_done_);
8614
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008615 DCHECK(klass != nullptr);
8616 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008617
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008618 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008619 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008620 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
8621 int32_t index = static_cast<int32_t>(class_root);
8622 DCHECK(class_roots->Get(index) == nullptr);
8623 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008624}
8625
Calin Juravle7865ac72017-06-28 11:03:12 -07008626jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
Andreas Gampe473191c2017-12-28 16:55:31 -08008627 const std::vector<const DexFile*>& dex_files,
8628 jclass loader_class,
8629 jobject parent_loader) {
Calin Juravle7865ac72017-06-28 11:03:12 -07008630 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8631 WellKnownClasses::dalvik_system_PathClassLoader) ||
8632 self->GetJniEnv()->IsSameObject(loader_class,
8633 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8634
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008635 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8636 // We could move the jobject to the callers, but all call-sites do this...
8637 ScopedObjectAccessUnchecked soa(self);
8638
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008639 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008640 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008641
Mathieu Chartierc7853442015-03-27 14:35:38 -07008642 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008643 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008644
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008645 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008646 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008647 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008648 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008649 mirror::ObjectArray<mirror::Object>::Alloc(self,
8650 dex_elements_class.Get(),
8651 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008652 Handle<mirror::Class> h_dex_element_class =
8653 hs.NewHandle(dex_elements_class->GetComponentType());
8654
Mathieu Chartierc7853442015-03-27 14:35:38 -07008655 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008656 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008657 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008658
Andreas Gampe08883de2016-11-08 13:20:52 -08008659 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00008660 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008661
Andreas Gampe08883de2016-11-08 13:20:52 -08008662 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00008663 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008664
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008665 // Fill the elements array.
8666 int32_t index = 0;
8667 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008668 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008669
Calin Juravle7865ac72017-06-28 11:03:12 -07008670 // CreateWellKnownClassLoader is only used by gtests and compiler.
8671 // 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 -07008672 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8673 self,
8674 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008675 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008676 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008677
Mathieu Chartier3738e982017-05-12 16:07:28 -07008678 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8679 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008680 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008681 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008682 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008683 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008684
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008685 Handle<mirror::String> h_file_name = hs2.NewHandle(
8686 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008687 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008688 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8689
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008690 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008691 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008692 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008693
8694 h_dex_elements->Set(index, h_element.Get());
8695 index++;
8696 }
8697 DCHECK_EQ(index, h_dex_elements->GetLength());
8698
8699 // Create DexPathList.
8700 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008701 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008702 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008703 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008704 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08008705 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
8706 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
8707 // elements.
8708 {
8709 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
8710 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
8711 DCHECK(native_lib_dirs != nullptr);
8712 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
8713 DCHECK(list_class != nullptr);
8714 {
8715 StackHandleScope<1> h_list_scope(self);
8716 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
8717 bool list_init = EnsureInitialized(self, h_list_class, true, true);
8718 DCHECK(list_init);
8719 list_class = h_list_class.Get();
8720 }
8721 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
8722 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
8723 // is fine for testing. While it violates a Java-code invariant (the elementData field is
8724 // normally never null), as long as one does not try to add elements, this will still
8725 // work.
8726 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
8727 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008728
Calin Juravle7865ac72017-06-28 11:03:12 -07008729 // Create the class loader..
8730 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8731 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8732 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008733 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008734 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008735 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008736 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008737 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008738
8739 // Make a pretend boot-classpath.
8740 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008741 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008742 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008743 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008744 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008745 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008746 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008747
8748 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8749 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8750 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8751 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008752
8753 // Make it a global ref and return.
8754 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008755 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008756 return soa.Env()->NewGlobalRef(local_ref.get());
8757}
8758
Calin Juravle7865ac72017-06-28 11:03:12 -07008759jobject ClassLinker::CreatePathClassLoader(Thread* self,
8760 const std::vector<const DexFile*>& dex_files) {
8761 return CreateWellKnownClassLoader(self,
8762 dex_files,
8763 WellKnownClasses::dalvik_system_PathClassLoader,
8764 nullptr);
8765}
8766
Andreas Gampe8ac75952015-06-02 21:01:45 -07008767void ClassLinker::DropFindArrayClassCache() {
8768 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8769 find_array_class_cache_next_victim_ = 0;
8770}
8771
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008772void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008773 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008774 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008775 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008776 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8777 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008778 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008779 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008780 }
8781 }
8782}
8783
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03008784void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
8785 for (const ClassLoaderData& data : class_loaders_) {
8786 LinearAlloc* alloc = data.allocator;
8787 if (alloc != nullptr && !visitor->Visit(alloc)) {
8788 break;
8789 }
8790 }
8791}
8792
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008793void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8794 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008795 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008796 Thread* const self = Thread::Current();
8797 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008798 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008799 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008800 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008801 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8802 // class table was modified.
8803 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8804 }
8805}
8806
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008807void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008808 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008809 std::vector<ClassLoaderData> to_delete;
8810 // Do the delete outside the lock to avoid lock violation in jit code cache.
8811 {
8812 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8813 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8814 const ClassLoaderData& data = *it;
8815 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008816 ObjPtr<mirror::ClassLoader> class_loader =
8817 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008818 if (class_loader != nullptr) {
8819 ++it;
8820 } else {
8821 VLOG(class_linker) << "Freeing class loader";
8822 to_delete.push_back(data);
8823 it = class_loaders_.erase(it);
8824 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008825 }
8826 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008827 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03008828 // CHA unloading analysis and SingleImplementaion cleanups are required.
8829 DeleteClassLoader(self, data, true /*cleanup_cha*/);
Mathieu Chartier65975772016-08-05 10:46:36 -07008830 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008831}
8832
Vladimir Marko21300532017-01-24 18:06:55 +00008833class GetResolvedClassesVisitor : public ClassVisitor {
8834 public:
8835 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8836 : result_(result),
8837 ignore_boot_classes_(ignore_boot_classes),
8838 last_resolved_classes_(result->end()),
8839 last_dex_file_(nullptr),
8840 vlog_is_on_(VLOG_IS_ON(class_linker)),
8841 extra_stats_(),
8842 last_extra_stats_(extra_stats_.end()) { }
8843
8844 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8845 if (!klass->IsProxyClass() &&
8846 !klass->IsArrayClass() &&
8847 klass->IsResolved() &&
8848 !klass->IsErroneousResolved() &&
8849 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8850 const DexFile& dex_file = klass->GetDexFile();
8851 if (&dex_file != last_dex_file_) {
8852 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008853 DexCacheResolvedClasses resolved_classes(
8854 dex_file.GetLocation(),
8855 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8856 dex_file.GetLocationChecksum(),
8857 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008858 last_resolved_classes_ = result_->find(resolved_classes);
8859 if (last_resolved_classes_ == result_->end()) {
8860 last_resolved_classes_ = result_->insert(resolved_classes).first;
8861 }
8862 }
8863 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8864 if (UNLIKELY(vlog_is_on_) && added) {
8865 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8866 if (last_extra_stats_ == extra_stats_.end() ||
8867 last_extra_stats_->first != resolved_classes) {
8868 last_extra_stats_ = extra_stats_.find(resolved_classes);
8869 if (last_extra_stats_ == extra_stats_.end()) {
8870 last_extra_stats_ =
8871 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8872 }
8873 }
8874 }
8875 }
8876 return true;
8877 }
8878
8879 void PrintStatistics() const {
8880 if (vlog_is_on_) {
8881 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8882 auto it = extra_stats_.find(std::addressof(resolved_classes));
8883 DCHECK(it != extra_stats_.end());
8884 const ExtraStats& extra_stats = it->second;
8885 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8886 << " has " << resolved_classes.GetClasses().size() << " / "
8887 << extra_stats.number_of_class_defs_ << " resolved classes";
8888 }
8889 }
8890 }
8891
8892 private:
8893 struct ExtraStats {
8894 explicit ExtraStats(uint32_t number_of_class_defs)
8895 : number_of_class_defs_(number_of_class_defs) {}
8896 uint32_t number_of_class_defs_;
8897 };
8898
8899 std::set<DexCacheResolvedClasses>* result_;
8900 bool ignore_boot_classes_;
8901 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8902 const DexFile* last_dex_file_;
8903
8904 // Statistics.
8905 bool vlog_is_on_;
8906 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8907 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8908};
8909
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008910std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008911 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008912 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008913 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008914 std::set<DexCacheResolvedClasses> ret;
8915 VLOG(class_linker) << "Collecting resolved classes";
8916 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008917 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8918 VisitClasses(&visitor);
8919 if (VLOG_IS_ON(class_linker)) {
8920 visitor.PrintStatistics();
8921 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008922 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008923 return ret;
8924}
8925
Mathieu Chartier65975772016-08-05 10:46:36 -07008926class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
8927 public:
8928 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
8929 : method_(method),
8930 pointer_size_(pointer_size) {}
8931
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008932 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07008933 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
8934 holder_ = klass;
8935 }
8936 // Return false to stop searching if holder_ is not null.
8937 return holder_ == nullptr;
8938 }
8939
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008940 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07008941 const ArtMethod* const method_;
8942 const PointerSize pointer_size_;
8943};
8944
8945mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
8946 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
8947 CHECK(method->IsCopied());
8948 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
8949 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008950 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07008951}
8952
Andreas Gampec6ea7d02017-02-01 16:46:28 -08008953mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
8954 return down_cast<mirror::IfTable*>(
8955 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008956 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Andreas Gampec6ea7d02017-02-01 16:46:28 -08008957 ifcount * mirror::IfTable::kMax));
8958}
8959
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008960// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01008961template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008962 uint32_t method_idx,
8963 Handle<mirror::DexCache> dex_cache,
8964 Handle<mirror::ClassLoader> class_loader,
8965 ArtMethod* referrer,
8966 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01008967template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008968 uint32_t method_idx,
8969 Handle<mirror::DexCache> dex_cache,
8970 Handle<mirror::ClassLoader> class_loader,
8971 ArtMethod* referrer,
8972 InvokeType type);
8973
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008974} // namespace art