blob: e2449f941cc0b143387d99fe90e175dae1c9498d [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());
502 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700503
Ian Rogers23435d02012-09-24 11:23:12 -0700504 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700505 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700506 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700507 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 mirror::String::SetClass(java_lang_String.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000509 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400510
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700511 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700512 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700513 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700514 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
515 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000516 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700517
Ian Rogers23435d02012-09-24 11:23:12 -0700518 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700519 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100520 mirror::ObjectArray<mirror::Class>::Alloc(self,
521 object_array_class.Get(),
522 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700523 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100524 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
525 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
526 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
527 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
528 SetClassRoot(ClassRoot::kCharArrayClass, char_array_class.Get());
529 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
530 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531
Mathieu Chartier6beced42016-11-15 15:51:31 -0800532 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
533 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
534
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100536 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
537 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
538 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
539 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
540 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
541 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
542 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
543 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700544
Ian Rogers23435d02012-09-24 11:23:12 -0700545 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700546 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547
Ian Rogers23435d02012-09-24 11:23:12 -0700548 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700549 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700550 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100551 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700552 mirror::IntArray::SetArrayClass(int_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100553 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554
Mathieu Chartierc7853442015-03-27 14:35:38 -0700555 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
556 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700557 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100558 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700559 mirror::LongArray::SetArrayClass(long_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100560 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700561
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700562 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700563
Ian Rogers52813c92012-10-11 11:50:38 -0700564 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700565 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700566 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100567 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100568 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700569 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000570 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700571
Alex Lightd6251582016-10-31 11:12:30 -0700572
573 // Setup dalvik.system.ClassExt
574 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
575 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100576 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Alex Lightd6251582016-10-31 11:12:30 -0700577 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000578 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700579
Mathieu Chartier66f19252012-09-18 08:57:04 -0700580 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700581 Handle<mirror::Class> object_array_string(hs.NewHandle(
582 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700583 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700584 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100585 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700586
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000587 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700588 // Create runtime resolution and imt conflict methods.
589 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000590 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
591 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700592
Ian Rogers23435d02012-09-24 11:23:12 -0700593 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
594 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
595 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800596 if (boot_class_path.empty()) {
597 *error_msg = "Boot classpath is empty.";
598 return false;
599 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800600 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800601 if (dex_file.get() == nullptr) {
602 *error_msg = "Null dex file.";
603 return false;
604 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700605 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800606 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700607 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700608
609 // now we can use FindSystemClass
610
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700611 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700612 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100613 SetClassRoot(ClassRoot::kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700614
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700615 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
616 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700617 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800618 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700619 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700620 quick_resolution_trampoline_ = GetQuickResolutionStub();
621 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
622 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700623 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700624
Alex Lightd6251582016-10-31 11:12:30 -0700625 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000626 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800627 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700628 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000629 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800630 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000631 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800632 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700633 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000634 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700635 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
636 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637
Ian Rogers23435d02012-09-24 11:23:12 -0700638 // Setup the primitive array type classes - can't be done until Object has a vtable.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100639 SetClassRoot(ClassRoot::kBooleanArrayClass, FindSystemClass(self, "[Z"));
640 mirror::BooleanArray::SetArrayClass(GetClassRoot(ClassRoot::kBooleanArrayClass, this));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700641
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100642 SetClassRoot(ClassRoot::kByteArrayClass, FindSystemClass(self, "[B"));
643 mirror::ByteArray::SetArrayClass(GetClassRoot(ClassRoot::kByteArrayClass, this));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700644
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800645 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700646
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100647 SetClassRoot(ClassRoot::kShortArrayClass, FindSystemClass(self, "[S"));
648 mirror::ShortArray::SetArrayClass(GetClassRoot(ClassRoot::kShortArrayClass, this));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800650 CheckSystemClass(self, int_array_class, "[I");
651 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100653 SetClassRoot(ClassRoot::kFloatArrayClass, FindSystemClass(self, "[F"));
654 mirror::FloatArray::SetArrayClass(GetClassRoot(ClassRoot::kFloatArrayClass, this));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700655
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100656 SetClassRoot(ClassRoot::kDoubleArrayClass, FindSystemClass(self, "[D"));
657 mirror::DoubleArray::SetArrayClass(GetClassRoot(ClassRoot::kDoubleArrayClass, this));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700658
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800659 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
660 // in class_table_.
661 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700662
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800663 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
664 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665
Ian Rogers23435d02012-09-24 11:23:12 -0700666 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700667 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800668 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700669 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800670 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700671 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
672 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700673 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
674 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700675
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700676 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
677 // suspension.
678 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000679 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700680 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000681 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700682 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000683 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700684 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000685 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700686
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700687 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100688 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700689
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800690 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700691
Ian Rogers23435d02012-09-24 11:23:12 -0700692 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100693 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
694 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700695
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700696 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700697 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
698 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100699 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700700 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700701
702 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700703 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
704 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100705 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700706 mirror::Field::SetArrayClass(class_root);
707
708 // Create java.lang.reflect.Constructor.class root and array root.
709 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
710 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100711 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700712 mirror::Constructor::SetClass(class_root);
713 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
714 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100715 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700716 mirror::Constructor::SetArrayClass(class_root);
717
718 // Create java.lang.reflect.Method.class root and array root.
719 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
720 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100721 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700722 mirror::Method::SetClass(class_root);
723 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
724 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100725 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700726 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700727
Orion Hodson005ac512017-10-24 15:43:43 +0100728 // Create java.lang.invoke.CallSite.class root
729 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
730 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100731 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100732 mirror::CallSite::SetClass(class_root);
733
Narayan Kamathafa48272016-08-03 12:46:58 +0100734 // Create java.lang.invoke.MethodType.class root
735 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
736 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100737 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100738 mirror::MethodType::SetClass(class_root);
739
740 // Create java.lang.invoke.MethodHandleImpl.class root
741 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
742 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100743 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100744 mirror::MethodHandleImpl::SetClass(class_root);
745
Orion Hodsonc069a302017-01-18 09:23:12 +0000746 // Create java.lang.invoke.MethodHandles.Lookup.class root
747 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
748 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100749 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000750 mirror::MethodHandlesLookup::SetClass(class_root);
751
Orion Hodson005ac512017-10-24 15:43:43 +0100752 // Create java.lang.invoke.VarHandle.class root
753 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000754 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100755 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100756 mirror::VarHandle::SetClass(class_root);
757
758 // Create java.lang.invoke.FieldVarHandle.class root
759 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
760 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100761 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100762 mirror::FieldVarHandle::SetClass(class_root);
763
764 // Create java.lang.invoke.ArrayElementVarHandle.class root
765 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
766 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100767 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100768 mirror::ArrayElementVarHandle::SetClass(class_root);
769
770 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
771 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
772 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100773 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100774 mirror::ByteArrayViewVarHandle::SetClass(class_root);
775
776 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
777 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
778 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100779 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100780 mirror::ByteBufferViewVarHandle::SetClass(class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000781
Narayan Kamath000e1882016-10-24 17:14:25 +0100782 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
783 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100784 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100785 mirror::EmulatedStackFrame::SetClass(class_root);
786
Brian Carlstrom1f870082011-08-23 16:02:11 -0700787 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700788 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000789 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800790 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700791 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700792 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
793 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700794 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700795 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700796 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700797 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700798 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700799 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700800 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700801 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700802 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700803 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700804 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700805 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700806
Ian Rogers23435d02012-09-24 11:23:12 -0700807 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700808 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700809 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700810 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100811 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700812
jeffhao8cd6dda2012-02-22 10:15:34 -0800813 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700814 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100815 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
816 mirror::Throwable::SetClass(GetClassRoot(ClassRoot::kJavaLangThrowable, this));
817 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700818 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
820 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
821 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700822 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100823 mirror::StackTraceElement::SetClass(GetClassRoot(ClassRoot::kJavaLangStackTraceElement, this));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700824
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700825 // Create conflict tables that depend on the class linker.
826 runtime->FixupConflictTables();
827
Ian Rogers98379392014-02-24 16:53:16 -0800828 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700829
Brian Carlstroma004aa92012-02-08 18:05:09 -0800830 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800831
832 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700833}
834
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700835static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
836 REQUIRES_SHARED(Locks::mutator_lock_) {
837 // Find String.<init> -> StringFactory bindings.
838 ObjPtr<mirror::Class> string_factory_class =
839 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
840 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100841 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700842 WellKnownClasses::InitStringInit(string_class, string_factory_class);
843 // Update the primordial thread.
844 self->InitStringEntryPoints();
845}
846
Ian Rogers98379392014-02-24 16:53:16 -0800847void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800848 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700849
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700850 CreateStringInitBindings(self, this);
851
Brian Carlstrom16192862011-09-12 17:50:06 -0700852 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700853 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700854 // as the types of the field can't be resolved prior to the runtime being
855 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700856 StackHandleScope<2> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100857 Handle<mirror::Class> java_lang_ref_Reference =
858 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700859 Handle<mirror::Class> java_lang_ref_FinalizerReference =
860 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800861
Mathieu Chartierc7853442015-03-27 14:35:38 -0700862 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700863 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
864 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700865
Mathieu Chartierc7853442015-03-27 14:35:38 -0700866 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700867 CHECK_STREQ(queue->GetName(), "queue");
868 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700869
Mathieu Chartierc7853442015-03-27 14:35:38 -0700870 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700871 CHECK_STREQ(queueNext->GetName(), "queueNext");
872 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700873
Mathieu Chartierc7853442015-03-27 14:35:38 -0700874 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700875 CHECK_STREQ(referent->GetName(), "referent");
876 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700877
Mathieu Chartierc7853442015-03-27 14:35:38 -0700878 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700879 CHECK_STREQ(zombie->GetName(), "zombie");
880 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700881
Brian Carlstroma663ea52011-08-19 23:33:41 -0700882 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100883 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700884 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700885 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700886 CHECK(klass != nullptr);
887 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700888 // note SetClassRoot does additional validation.
889 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700890 }
891
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700892 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700893
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700894 // disable the slow paths in FindClass and CreatePrimitiveClass now
895 // that Object, Class, and Object[] are setup
896 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700897
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800898 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700899}
900
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700901void ClassLinker::RunRootClinits() {
902 Thread* self = Thread::Current();
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100903 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
904 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700905 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700906 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100907 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700908 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700909 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700910 }
911 }
912}
913
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200914// Set image methods' entry point to interpreter.
915class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
916 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700917 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200918 : image_pointer_size_(image_pointer_size) {}
919
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700920 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200921 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
922 CHECK(method->GetDeclaringClass() != nullptr);
923 }
924 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
925 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
926 image_pointer_size_);
927 }
928 }
929
930 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700931 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200932
933 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
934};
935
Jeff Haodcdc85b2015-12-04 14:06:18 -0800936struct TrampolineCheckData {
937 const void* quick_resolution_trampoline;
938 const void* quick_imt_conflict_trampoline;
939 const void* quick_generic_jni_trampoline;
940 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700941 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800942 ArtMethod* m;
943 bool error;
944};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800945
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800946bool ClassLinker::InitFromBootImage(std::string* error_msg) {
947 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700948 CHECK(!init_done_);
949
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700950 Runtime* const runtime = Runtime::Current();
951 Thread* const self = Thread::Current();
952 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800953 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
954 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700955 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
956 if (!ValidPointerSize(pointer_size_unchecked)) {
957 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800958 return false;
959 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700960 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800961 if (!runtime->IsAotCompiler()) {
962 // Only the Aot compiler supports having an image with a different pointer size than the
963 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
964 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700965 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800966 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700967 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800968 sizeof(void*));
969 return false;
970 }
971 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800972 std::vector<const OatFile*> oat_files =
973 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
974 DCHECK(!oat_files.empty());
975 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800976 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
977 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700978 GetStoreValueByKey(OatHeader::kImageLocationKey);
979 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800980 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
981 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
982 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
983 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
984 if (kIsDebugBuild) {
985 // Check that the other images use the same trampoline.
986 for (size_t i = 1; i < oat_files.size(); ++i) {
987 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
988 const void* ith_quick_resolution_trampoline =
989 ith_oat_header.GetQuickResolutionTrampoline();
990 const void* ith_quick_imt_conflict_trampoline =
991 ith_oat_header.GetQuickImtConflictTrampoline();
992 const void* ith_quick_generic_jni_trampoline =
993 ith_oat_header.GetQuickGenericJniTrampoline();
994 const void* ith_quick_to_interpreter_bridge_trampoline =
995 ith_oat_header.GetQuickToInterpreterBridge();
996 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
997 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
998 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
999 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1000 // Make sure that all methods in this image do not contain those trampolines as
1001 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1002 TrampolineCheckData data;
1003 data.error = false;
1004 data.pointer_size = GetImagePointerSize();
1005 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1006 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1007 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1008 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1009 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001010 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1011 if (obj->IsClass()) {
1012 ObjPtr<mirror::Class> klass = obj->AsClass();
1013 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1014 const void* entrypoint =
1015 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1016 if (entrypoint == data.quick_resolution_trampoline ||
1017 entrypoint == data.quick_imt_conflict_trampoline ||
1018 entrypoint == data.quick_generic_jni_trampoline ||
1019 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1020 data.m = &m;
1021 data.error = true;
1022 return;
1023 }
1024 }
1025 }
1026 };
1027 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001028 if (data.error) {
1029 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001030 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001031 *error_msg = "Found an ArtMethod with a bad entrypoint";
1032 return false;
1033 }
1034 }
1035 }
1036 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001037
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001038 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1039 down_cast<mirror::ObjectArray<mirror::Class>*>(
1040 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001041 mirror::Class::SetClassClass(GetClassRoot(ClassRoot::kJavaLangClass, this));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001042
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001043 // Special case of setting up the String class early so that we can test arbitrary objects
1044 // as being Strings or not
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001045 mirror::String::SetClass(GetClassRoot<mirror::String>(this));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001046
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001047 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001048 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001049 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1050 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001051 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1052 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001053
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001054 // reinit array_iftable_ from any array class instance, they should be ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001055 array_iftable_ =
1056 GcRoot<mirror::IfTable>(GetClassRoot(ClassRoot::kObjectArrayClass, this)->GetIfTable());
1057 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(ClassRoot::kBooleanArrayClass, this)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001058 // String class root was set above
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001059 mirror::Field::SetClass(GetClassRoot(ClassRoot::kJavaLangReflectField, this));
1060 mirror::Field::SetArrayClass(GetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, this));
1061 mirror::Constructor::SetClass(GetClassRoot(ClassRoot::kJavaLangReflectConstructor, this).Ptr());
1062 mirror::Constructor::SetArrayClass(
1063 GetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, this).Ptr());
1064 mirror::Method::SetClass(GetClassRoot(ClassRoot::kJavaLangReflectMethod, this).Ptr());
1065 mirror::Method::SetArrayClass(
1066 GetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, this).Ptr());
1067 mirror::CallSite::SetClass(GetClassRoot(ClassRoot::kJavaLangInvokeCallSite, this).Ptr());
1068 mirror::MethodHandleImpl::SetClass(
1069 GetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, this).Ptr());
1070 mirror::MethodHandlesLookup::SetClass(
1071 GetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, this).Ptr());
1072 mirror::MethodType::SetClass(
1073 GetClassRoot(ClassRoot::kJavaLangInvokeMethodType, this).Ptr());
1074 mirror::VarHandle::SetClass(GetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, this).Ptr());
1075 mirror::FieldVarHandle::SetClass(
1076 GetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, this).Ptr());
1077 mirror::ArrayElementVarHandle::SetClass(
1078 GetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, this).Ptr());
1079 mirror::ByteArrayViewVarHandle::SetClass(
1080 GetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, this).Ptr());
1081 mirror::ByteBufferViewVarHandle::SetClass(
1082 GetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, this).Ptr());
1083 mirror::Reference::SetClass(GetClassRoot(ClassRoot::kJavaLangRefReference, this));
1084 mirror::BooleanArray::SetArrayClass(GetClassRoot(ClassRoot::kBooleanArrayClass, this));
1085 mirror::ByteArray::SetArrayClass(GetClassRoot(ClassRoot::kByteArrayClass, this));
1086 mirror::CharArray::SetArrayClass(GetClassRoot(ClassRoot::kCharArrayClass, this));
1087 mirror::DoubleArray::SetArrayClass(GetClassRoot(ClassRoot::kDoubleArrayClass, this));
1088 mirror::FloatArray::SetArrayClass(GetClassRoot(ClassRoot::kFloatArrayClass, this));
1089 mirror::IntArray::SetArrayClass(GetClassRoot(ClassRoot::kIntArrayClass, this));
1090 mirror::LongArray::SetArrayClass(GetClassRoot(ClassRoot::kLongArrayClass, this));
1091 mirror::ShortArray::SetArrayClass(GetClassRoot(ClassRoot::kShortArrayClass, this));
1092 mirror::Throwable::SetClass(GetClassRoot(ClassRoot::kJavaLangThrowable, this));
1093 mirror::StackTraceElement::SetClass(GetClassRoot(ClassRoot::kJavaLangStackTraceElement, this));
1094 mirror::EmulatedStackFrame::SetClass(
1095 GetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, this).Ptr());
1096 mirror::ClassExt::SetClass(GetClassRoot(ClassRoot::kDalvikSystemClassExt, this));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001097
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001098 for (gc::space::ImageSpace* image_space : spaces) {
1099 // Boot class loader, use a null handle.
1100 std::vector<std::unique_ptr<const DexFile>> dex_files;
1101 if (!AddImageSpace(image_space,
1102 ScopedNullHandle<mirror::ClassLoader>(),
1103 /*dex_elements*/nullptr,
1104 /*dex_location*/nullptr,
1105 /*out*/&dex_files,
1106 error_msg)) {
1107 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001108 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001109 // Append opened dex files at the end.
1110 boot_dex_files_.insert(boot_dex_files_.end(),
1111 std::make_move_iterator(dex_files.begin()),
1112 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001113 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001114 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1115 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1116 }
Ian Rogers98379392014-02-24 16:53:16 -08001117 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001118
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001119 VLOG(startup) << __FUNCTION__ << " exiting";
1120 return true;
1121}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001122
Jeff Hao5872d7c2016-04-27 11:07:41 -07001123bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001124 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001126 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1127 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128}
1129
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001130static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1131 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001132 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001133 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001134 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001135 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001136 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001137 DCHECK(dex_file_field != nullptr);
1138 DCHECK(dex_file_name_field != nullptr);
1139 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001140 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001141 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001142 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001143 // Null dex file means it was probably a jar with no dex files, return a null string.
1144 *out_name = nullptr;
1145 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001146 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001147 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001148 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001149 *out_name = name_object->AsString();
1150 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001151 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001152 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001153}
1154
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001155static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001156 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001157 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001158 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001159 DCHECK(out_dex_file_names != nullptr);
1160 DCHECK(error_msg != nullptr);
1161 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001162 StackHandleScope<1> hs(soa.Self());
1163 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Jeff Hao5872d7c2016-04-27 11:07:41 -07001164 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001165 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1166 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001167 *error_msg = StringPrintf("Unknown class loader type %s",
1168 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001169 // Unsupported class loader.
1170 return false;
1171 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001172 // Get element names. Sets error to true on failure.
1173 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1174 REQUIRES_SHARED(Locks::mutator_lock_) {
1175 if (element == nullptr) {
1176 *error_msg = "Null dex element";
1177 *error = true; // Null element is a critical error.
1178 return false; // Had an error, stop the visit.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001179 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001180 ObjPtr<mirror::String> name;
1181 if (!GetDexPathListElementName(element, &name)) {
1182 *error_msg = "Invalid dex path list element";
1183 *error = false; // Invalid element is not a critical error.
1184 return false; // Stop the visit.
1185 }
1186 if (name != nullptr) {
1187 out_dex_file_names->push_front(name.Ptr());
1188 }
1189 return true; // Continue with the next Element.
1190 };
1191 bool error = VisitClassLoaderDexElements(soa, handle, add_element_names, /* error */ false);
1192 if (error) {
1193 // An error occurred during DexPathList Element visiting.
1194 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001195 }
1196 class_loader = class_loader->GetParent();
1197 }
1198 return true;
1199}
1200
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001201class CHAOnDeleteUpdateClassVisitor {
1202 public:
1203 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1204 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1205 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1206 self_(Thread::Current()) {}
1207
1208 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1209 // This class is going to be unloaded. Tell CHA about it.
1210 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1211 return true;
1212 }
1213 private:
1214 const LinearAlloc* allocator_;
1215 const ClassHierarchyAnalysis* cha_;
1216 const PointerSize pointer_size_;
1217 const Thread* self_;
1218};
1219
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001220class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1221 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001222 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001223 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1224
1225 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001226 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001227 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001228 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001229 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001230 }
1231 }
1232
1233 private:
1234 gc::accounting::HeapBitmap* const live_bitmap_;
1235};
1236
Chang Xingba17dbd2017-06-28 21:27:56 +00001237class FixupInternVisitor {
1238 public:
1239 ALWAYS_INLINE ObjPtr<mirror::Object> TryInsertIntern(mirror::Object* obj) const
1240 REQUIRES_SHARED(Locks::mutator_lock_) {
1241 if (obj != nullptr && obj->IsString()) {
1242 const auto intern = Runtime::Current()->GetInternTable()->InternStrong(obj->AsString());
1243 return intern;
1244 }
1245 return obj;
1246 }
1247
1248 ALWAYS_INLINE void VisitRootIfNonNull(
1249 mirror::CompressedReference<mirror::Object>* root) const
1250 REQUIRES_SHARED(Locks::mutator_lock_) {
1251 if (!root->IsNull()) {
1252 VisitRoot(root);
1253 }
1254 }
1255
1256 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1257 REQUIRES_SHARED(Locks::mutator_lock_) {
1258 root->Assign(TryInsertIntern(root->AsMirrorPtr()));
1259 }
1260
1261 // Visit Class Fields
1262 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1263 MemberOffset offset,
1264 bool is_static ATTRIBUTE_UNUSED) const
1265 REQUIRES_SHARED(Locks::mutator_lock_) {
1266 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1267 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1268 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1269 // Updating images, don't do a read barrier.
1270 // Only string fields are fixed, don't do a verify.
1271 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1272 offset);
1273 obj->SetFieldObject<false, false>(offset, TryInsertIntern(ref));
1274 }
1275 }
1276
1277 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1278 ObjPtr<mirror::Reference> ref) const
1279 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1280 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1281 }
1282
1283 void operator()(mirror::Object* obj) const
1284 REQUIRES_SHARED(Locks::mutator_lock_) {
1285 if (obj->IsDexCache()) {
1286 obj->VisitReferences<true, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1287 } else {
1288 // Don't visit native roots for non-dex-cache
1289 obj->VisitReferences<false, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1290 }
1291 }
1292};
1293
Andreas Gampe2af99022017-04-25 08:32:59 -07001294// new_class_set is the set of classes that were read from the class table section in the image.
1295// If there was no class table section, it is null.
1296// Note: using a class here to avoid having to make ClassLinker internals public.
1297class AppImageClassLoadersAndDexCachesHelper {
1298 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001299 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001300 ClassLinker* class_linker,
1301 gc::space::ImageSpace* space,
1302 Handle<mirror::ClassLoader> class_loader,
1303 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001304 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001305 REQUIRES(!Locks::dex_lock_)
1306 REQUIRES_SHARED(Locks::mutator_lock_);
1307};
1308
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001309void AppImageClassLoadersAndDexCachesHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001310 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001311 gc::space::ImageSpace* space,
1312 Handle<mirror::ClassLoader> class_loader,
1313 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001314 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001315 REQUIRES(!Locks::dex_lock_)
1316 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001317 Thread* const self = Thread::Current();
1318 gc::Heap* const heap = Runtime::Current()->GetHeap();
1319 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001320 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001321 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001322 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001323 const size_t num_dex_caches = dex_caches->GetLength();
1324 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001325 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001326 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001327 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001328 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001329 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1330 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001331 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001332 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001333 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001334 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001335 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001336 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001337 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001338 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001339 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001340 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001341 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001342 DCHECK(it != new_class_set->end());
1343 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001344 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001345 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001346 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001347 DCHECK(it2 != new_class_set->end());
1348 DCHECK_EQ(it2->Read(), super_class);
1349 }
1350 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1351 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001352 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1353 if (!class_linker->IsQuickResolutionStub(code) &&
1354 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001355 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001356 !m.IsNative()) {
1357 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001358 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001359 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001360 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1361 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001362 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1363 if (!class_linker->IsQuickResolutionStub(code) &&
1364 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001365 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001366 !m.IsNative()) {
1367 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001368 }
1369 }
1370 }
1371 }
1372 }
1373 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001374 }
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001375 if (ClassLinker::kAppImageMayContainStrings) {
Chang Xingba17dbd2017-06-28 21:27:56 +00001376 // Fixup all the literal strings happens at app images which are supposed to be interned.
1377 ScopedTrace timing("Fixup String Intern in image and dex_cache");
1378 const auto& image_header = space->GetImageHeader();
1379 const auto bitmap = space->GetMarkBitmap(); // bitmap of objects
1380 const uint8_t* target_base = space->GetMemMap()->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001381 const ImageSection& objects_section = image_header.GetObjectsSection();
Chang Xingba17dbd2017-06-28 21:27:56 +00001382
1383 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1384 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1385
1386 FixupInternVisitor fixup_intern_visitor;
1387 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_intern_visitor);
1388 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001389 if (kVerifyArtMethodDeclaringClasses) {
1390 ScopedTrace timing("Verify declaring classes");
1391 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1392 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001393 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001394 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001395}
1396
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001397// Update the class loader. Should only be used on classes in the image space.
1398class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001399 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001400 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001401 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001402 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001403
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001404 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001405 // Do not update class loader for boot image classes where the app image
1406 // class loader is only the initiating loader but not the defining loader.
1407 if (klass->GetClassLoader() != nullptr) {
1408 klass->SetClassLoader(class_loader_);
1409 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001410 return true;
1411 }
1412
1413 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001414 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001415};
1416
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001417static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1418 const char* location,
1419 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001420 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001421 DCHECK(error_msg != nullptr);
1422 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001423 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001424 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001425 return std::unique_ptr<const DexFile>();
1426 }
1427 std::string inner_error_msg;
1428 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1429 if (dex_file == nullptr) {
1430 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1431 location,
1432 oat_file->GetLocation().c_str(),
1433 inner_error_msg.c_str());
1434 return std::unique_ptr<const DexFile>();
1435 }
1436
1437 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1438 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1439 location,
1440 dex_file->GetLocationChecksum(),
1441 oat_dex_file->GetDexFileLocationChecksum());
1442 return std::unique_ptr<const DexFile>();
1443 }
1444 return dex_file;
1445}
1446
1447bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1448 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1449 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001450 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001451 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001452 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001453 DCHECK(dex_caches_object != nullptr);
1454 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1455 dex_caches_object->AsObjectArray<mirror::DexCache>();
1456 const OatFile* oat_file = space->GetOatFile();
1457 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001458 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001459 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1460 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1461 dex_file_location.c_str(),
1462 error_msg);
1463 if (dex_file == nullptr) {
1464 return false;
1465 }
1466 dex_cache->SetDexFile(dex_file.get());
1467 out_dex_files->push_back(std::move(dex_file));
1468 }
1469 return true;
1470}
1471
Andreas Gampe0793bec2016-12-01 11:37:33 -08001472// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1473// together and caches some intermediate results.
1474class ImageSanityChecks FINAL {
1475 public:
1476 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1477 REQUIRES_SHARED(Locks::mutator_lock_) {
1478 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001479 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1480 DCHECK(obj != nullptr);
1481 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1482 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1483 if (obj->IsClass()) {
1484 auto klass = obj->AsClass();
1485 for (ArtField& field : klass->GetIFields()) {
1486 CHECK_EQ(field.GetDeclaringClass(), klass);
1487 }
1488 for (ArtField& field : klass->GetSFields()) {
1489 CHECK_EQ(field.GetDeclaringClass(), klass);
1490 }
1491 const auto pointer_size = isc.pointer_size_;
1492 for (auto& m : klass->GetMethods(pointer_size)) {
1493 isc.SanityCheckArtMethod(&m, klass);
1494 }
1495 auto* vtable = klass->GetVTable();
1496 if (vtable != nullptr) {
1497 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1498 }
1499 if (klass->ShouldHaveImt()) {
1500 ImTable* imt = klass->GetImt(pointer_size);
1501 for (size_t i = 0; i < ImTable::kSize; ++i) {
1502 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1503 }
1504 }
1505 if (klass->ShouldHaveEmbeddedVTable()) {
1506 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1507 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1508 }
1509 }
1510 mirror::IfTable* iftable = klass->GetIfTable();
1511 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1512 if (iftable->GetMethodArrayCount(i) > 0) {
1513 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1514 }
1515 }
1516 }
1517 };
1518 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001519 }
1520
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001521 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1522 ClassLinker* class_linker,
1523 mirror::MethodDexCacheType* arr,
1524 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001525 REQUIRES_SHARED(Locks::mutator_lock_) {
1526 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001527 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001528 }
1529
Andreas Gampe0793bec2016-12-01 11:37:33 -08001530 private:
1531 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1532 : spaces_(heap->GetBootImageSpaces()),
1533 pointer_size_(class_linker->GetImagePointerSize()) {
1534 space_begin_.reserve(spaces_.size());
1535 method_sections_.reserve(spaces_.size());
1536 runtime_method_sections_.reserve(spaces_.size());
1537 for (gc::space::ImageSpace* space : spaces_) {
1538 space_begin_.push_back(space->Begin());
1539 auto& header = space->GetImageHeader();
1540 method_sections_.push_back(&header.GetMethodsSection());
1541 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1542 }
1543 }
1544
1545 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1546 REQUIRES_SHARED(Locks::mutator_lock_) {
1547 if (m->IsRuntimeMethod()) {
1548 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1549 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1550 } else if (m->IsCopied()) {
1551 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1552 } else if (expected_class != nullptr) {
1553 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1554 }
1555 if (!spaces_.empty()) {
1556 bool contains = false;
1557 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1558 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1559 contains = method_sections_[i]->Contains(offset) ||
1560 runtime_method_sections_[i]->Contains(offset);
1561 }
1562 CHECK(contains) << m << " not found";
1563 }
1564 }
1565
1566 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1567 ObjPtr<mirror::Class> expected_class)
1568 REQUIRES_SHARED(Locks::mutator_lock_) {
1569 CHECK(arr != nullptr);
1570 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1571 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1572 // expected_class == null means we are a dex cache.
1573 if (expected_class != nullptr) {
1574 CHECK(method != nullptr);
1575 }
1576 if (method != nullptr) {
1577 SanityCheckArtMethod(method, expected_class);
1578 }
1579 }
1580 }
1581
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001582 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001583 REQUIRES_SHARED(Locks::mutator_lock_) {
1584 CHECK_EQ(arr != nullptr, size != 0u);
1585 if (arr != nullptr) {
1586 bool contains = false;
1587 for (auto space : spaces_) {
1588 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001589 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001590 contains = true;
1591 break;
1592 }
1593 }
1594 CHECK(contains);
1595 }
1596 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001597 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1598 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001599 // expected_class == null means we are a dex cache.
1600 if (method != nullptr) {
1601 SanityCheckArtMethod(method, nullptr);
1602 }
1603 }
1604 }
1605
1606 const std::vector<gc::space::ImageSpace*>& spaces_;
1607 const PointerSize pointer_size_;
1608
1609 // Cached sections from the spaces.
1610 std::vector<const uint8_t*> space_begin_;
1611 std::vector<const ImageSection*> method_sections_;
1612 std::vector<const ImageSection*> runtime_method_sections_;
1613};
1614
Andreas Gampebe7af222017-07-25 09:57:28 -07001615static void VerifyAppImage(const ImageHeader& header,
1616 const Handle<mirror::ClassLoader>& class_loader,
1617 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1618 ClassTable* class_table, gc::space::ImageSpace* space)
1619 REQUIRES_SHARED(Locks::mutator_lock_) {
1620 {
1621 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1622 public:
1623 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1624
1625 virtual void Visit(ArtMethod* method)
1626 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1627 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1628 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1629 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1630 }
1631 }
1632
1633 private:
1634 ClassTable* const table_;
1635 };
1636 VerifyClassInTableArtMethodVisitor visitor(class_table);
1637 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1638 }
1639 {
1640 // Verify that all direct interfaces of classes in the class table are also resolved.
1641 std::vector<ObjPtr<mirror::Class>> classes;
1642 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1643 REQUIRES_SHARED(Locks::mutator_lock_) {
1644 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1645 classes.push_back(klass);
1646 }
1647 return true;
1648 };
1649 class_table->Visit(verify_direct_interfaces_in_table);
1650 Thread* self = Thread::Current();
1651 for (ObjPtr<mirror::Class> klass : classes) {
1652 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1653 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1654 << klass->PrettyDescriptor() << " iface #" << i;
1655 }
1656 }
1657 }
1658 // Check that all non-primitive classes in dex caches are also in the class table.
1659 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1660 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1661 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1662 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1663 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1664 if (klass != nullptr && !klass->IsPrimitive()) {
1665 CHECK(class_table->Contains(klass))
1666 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1667 }
1668 }
1669 }
1670}
1671
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001672bool ClassLinker::AddImageSpace(
1673 gc::space::ImageSpace* space,
1674 Handle<mirror::ClassLoader> class_loader,
1675 jobjectArray dex_elements,
1676 const char* dex_location,
1677 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1678 std::string* error_msg) {
1679 DCHECK(out_dex_files != nullptr);
1680 DCHECK(error_msg != nullptr);
1681 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001682 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001683 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001684 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001685 DCHECK(dex_caches_object != nullptr);
1686 Runtime* const runtime = Runtime::Current();
1687 gc::Heap* const heap = runtime->GetHeap();
1688 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001689 // Check that the image is what we are expecting.
1690 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1691 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1692 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1693 image_pointer_size_);
1694 return false;
1695 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001696 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1697 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1698 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1699 expected_image_roots,
1700 header.GetImageRoots()->GetLength());
1701 return false;
1702 }
1703 StackHandleScope<3> hs(self);
1704 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1705 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1706 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1707 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1708 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1709 "Class loader should be the last image root.");
1710 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1711 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001712 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001713 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001714 *error_msg = StringPrintf("Expected %d class roots but got %d",
1715 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001716 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001717 return false;
1718 }
1719 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001720 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1721 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1722 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001723 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1724 return false;
1725 }
1726 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001727 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001728 if (oat_file->GetOatHeader().GetDexFileCount() !=
1729 static_cast<uint32_t>(dex_caches->GetLength())) {
1730 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1731 "image";
1732 return false;
1733 }
1734
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001735 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001736 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1737 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001738 // TODO: Only store qualified paths.
1739 // If non qualified, qualify it.
1740 if (dex_file_location.find('/') == std::string::npos) {
1741 std::string dex_location_path = dex_location;
1742 const size_t pos = dex_location_path.find_last_of('/');
1743 CHECK_NE(pos, std::string::npos);
1744 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1745 dex_file_location = dex_location_path + dex_file_location;
1746 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001747 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1748 dex_file_location.c_str(),
1749 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001750 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001751 return false;
1752 }
1753
1754 if (app_image) {
1755 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1756 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001757 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001758 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001759 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001760 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001761 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001762 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001763 }
1764 }
1765 } else {
1766 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001767 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
1768 this,
1769 dex_cache->GetResolvedMethods(),
1770 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001771 }
1772 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001773 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001774 }
1775 out_dex_files->push_back(std::move(dex_file));
1776 }
1777
1778 if (app_image) {
1779 ScopedObjectAccessUnchecked soa(Thread::Current());
1780 // Check that the class loader resolves the same way as the ones in the image.
1781 // Image class loader [A][B][C][image dex files]
1782 // Class loader = [???][dex_elements][image dex files]
1783 // Need to ensure that [???][dex_elements] == [A][B][C].
1784 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1785 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1786 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1787 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001788 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1789 *error_msg = "Unexpected BootClassLoader in app image";
1790 return false;
1791 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001792 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001793 std::string temp_error_msg;
1794 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1795 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1796 temp_error_msg.c_str());
1797 return false;
1798 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001799 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001800 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1801 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1802 temp_error_msg.c_str());
1803 return false;
1804 }
1805 // Add the temporary dex path list elements at the end.
1806 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1807 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1808 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1809 if (element != nullptr) {
1810 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001811 ObjPtr<mirror::String> name;
1812 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1813 loader_dex_file_names.push_back(name);
1814 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001815 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001816 }
1817 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1818 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1819 static_cast<size_t>(dex_caches->GetLength()));
1820 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1821 // Check that the dex file names match.
1822 bool equal = image_count == loader_dex_file_names.size();
1823 if (equal) {
1824 auto it1 = image_dex_file_names.begin();
1825 auto it2 = loader_dex_file_names.begin();
1826 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1827 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001828 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001829 }
1830 if (!equal) {
1831 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1832 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1833 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001834 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001835 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1836 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1837 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001838 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001839 *error_msg = "Rejecting application image due to class loader mismatch";
1840 // Ignore class loader mismatch for now since these would just use possibly incorrect
1841 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001842 }
1843 }
1844
1845 if (kSanityCheckObjects) {
1846 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1847 auto* dex_cache = dex_caches->Get(i);
1848 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1849 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1850 if (field != nullptr) {
1851 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1852 }
1853 }
1854 }
1855 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001856 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001857 }
1858 }
1859
1860 // Set entry point to interpreter if in InterpretOnly mode.
1861 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001862 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001863 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001864 }
1865
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001866 ClassTable* class_table = nullptr;
1867 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001868 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001869 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001870 }
1871 // If we have a class table section, read it and use it for verification in
1872 // UpdateAppImageClassLoadersAndDexCaches.
1873 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001874 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001875 const bool added_class_table = class_table_section.Size() > 0u;
1876 if (added_class_table) {
1877 const uint64_t start_time2 = NanoTime();
1878 size_t read_count = 0;
1879 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1880 /*make copy*/false,
1881 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001882 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001883 }
1884 if (app_image) {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001885 AppImageClassLoadersAndDexCachesHelper::Update(this,
1886 space,
1887 class_loader,
1888 dex_caches,
1889 &temp_set);
Mathieu Chartier69731002016-03-02 16:08:31 -08001890 // Update class loader and resolved strings. If added_class_table is false, the resolved
1891 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001892 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1893 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001894 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001895 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001896
Vladimir Marko305c38b2018-02-14 11:50:07 +00001897 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07001898 // Every class in the app image has initially SubtypeCheckInfo in the
1899 // Uninitialized state.
1900 //
1901 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
1902 // after class initialization is complete. The app image ClassStatus as-is
1903 // are almost all ClassStatus::Initialized, and being in the
1904 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
1905 //
1906 // Force every app image class's SubtypeCheck to be at least kIninitialized.
1907 //
1908 // See also ImageWriter::FixupClass.
1909 ScopedTrace trace("Recalculate app image SubtypeCheck bitstrings");
1910 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
1911 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00001912 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07001913 }
1914 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001915 }
1916 if (!oat_file->GetBssGcRoots().empty()) {
1917 // Insert oat file to class table for visiting .bss GC roots.
1918 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001919 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001920
Mathieu Chartier69731002016-03-02 16:08:31 -08001921 if (added_class_table) {
1922 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1923 class_table->AddClassSet(std::move(temp_set));
1924 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001925
Mathieu Chartier69731002016-03-02 16:08:31 -08001926 if (kIsDebugBuild && app_image) {
1927 // This verification needs to happen after the classes have been added to the class loader.
1928 // Since it ensures classes are in the class table.
Andreas Gampeacbd98b2017-10-12 10:44:11 -07001929 ScopedTrace trace("VerifyAppImage");
Andreas Gampebe7af222017-07-25 09:57:28 -07001930 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08001931 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001932
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001933 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001934 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001935}
1936
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001937bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001938 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1939 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001940}
1941
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001942void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001943 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1944 // enabling tracing requires the mutator lock, there are no race conditions here.
1945 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001946 Thread* const self = Thread::Current();
1947 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001948 if (kUseReadBarrier) {
1949 // We do not track new roots for CC.
1950 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1951 kVisitRootFlagClearRootLog |
1952 kVisitRootFlagStartLoggingNewRoots |
1953 kVisitRootFlagStopLoggingNewRoots));
1954 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001955 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001956 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1957 // There is 3 GC cases to handle:
1958 // Non moving concurrent:
1959 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001960 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001961 //
1962 // Moving non-concurrent:
1963 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1964 // To prevent missing roots, this case needs to ensure that there is no
1965 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1966 // class which is in the class table.
1967 //
1968 // Moving concurrent:
1969 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1970 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001971 //
1972 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1973 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1974 // these objects.
1975 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07001976 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001977 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001978 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001979 for (const ClassLoaderData& data : class_loaders_) {
1980 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1981 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1982 }
1983 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001984 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001985 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001986 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001987 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001988 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001989 // Concurrent moving GC marked new roots through the to-space invariant.
1990 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001991 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001992 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1993 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1994 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1995 if (old_ref != nullptr) {
1996 DCHECK(old_ref->IsClass());
1997 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1998 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1999 // Concurrent moving GC marked new roots through the to-space invariant.
2000 CHECK_EQ(new_ref, old_ref);
2001 }
2002 }
2003 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002004 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002005 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002006 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002007 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002008 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002009 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002010 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002011 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002012 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002013 }
2014 // We deliberately ignore the class roots in the image since we
2015 // handle image roots by using the MS/CMS rescanning of dirty cards.
2016}
2017
Brian Carlstroma663ea52011-08-19 23:33:41 -07002018// Keep in sync with InitCallback. Anything we visit, we need to
2019// reinit references to when reinitializing a ClassLinker from a
2020// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002021void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002022 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002023 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07002024 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002025 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2026 // unloading if we are marking roots.
2027 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002028}
2029
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002030class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2031 public:
2032 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2033 : visitor_(visitor),
2034 done_(false) {}
2035
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002036 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002037 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002038 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002039 if (!done_ && class_table != nullptr) {
2040 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2041 if (!class_table->Visit(visitor)) {
2042 // If the visitor ClassTable returns false it means that we don't need to continue.
2043 done_ = true;
2044 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002045 }
2046 }
2047
2048 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002049 // Class visitor that limits the class visits from a ClassTable to the classes with
2050 // the provided defining class loader. This filter is used to avoid multiple visits
2051 // of the same class which can be recorded for multiple initiating class loaders.
2052 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2053 public:
2054 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2055 ClassVisitor* visitor)
2056 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2057
2058 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2059 if (klass->GetClassLoader() != defining_class_loader_) {
2060 return true;
2061 }
2062 return (*visitor_)(klass);
2063 }
2064
2065 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2066 ClassVisitor* const visitor_;
2067 };
2068
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002069 ClassVisitor* const visitor_;
2070 // If done is true then we don't need to do any more visiting.
2071 bool done_;
2072};
2073
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002074void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002075 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002076 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2077 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002078 }
2079}
2080
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002081void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002082 Thread* const self = Thread::Current();
2083 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2084 // Not safe to have thread suspension when we are holding a lock.
2085 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002086 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002087 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002088 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002089 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002090 }
2091}
2092
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002093class GetClassesInToVector : public ClassVisitor {
2094 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002095 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002096 classes_.push_back(klass);
2097 return true;
2098 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002099 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002100};
2101
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002102class GetClassInToObjectArray : public ClassVisitor {
2103 public:
2104 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2105 : arr_(arr), index_(0) {}
2106
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002107 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002108 ++index_;
2109 if (index_ <= arr_->GetLength()) {
2110 arr_->Set(index_ - 1, klass);
2111 return true;
2112 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002113 return false;
2114 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002115
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002116 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002117 return index_ <= arr_->GetLength();
2118 }
2119
2120 private:
2121 mirror::ObjectArray<mirror::Class>* const arr_;
2122 int32_t index_;
2123};
2124
2125void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002126 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2127 // is avoiding duplicates.
2128 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002129 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002130 GetClassesInToVector accumulator;
2131 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002132 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002133 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002134 return;
2135 }
2136 }
2137 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002138 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002139 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002140 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002141 // We size the array assuming classes won't be added to the class table during the visit.
2142 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002143 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002144 size_t class_table_size;
2145 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002146 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002147 // Add 100 in case new classes get loaded when we are filling in the object array.
2148 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002149 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002150 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002151 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002152 classes.Assign(
2153 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002154 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002155 GetClassInToObjectArray accumulator(classes.Get());
2156 VisitClasses(&accumulator);
2157 if (accumulator.Succeeded()) {
2158 break;
2159 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002160 }
2161 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2162 // If the class table shrank during creation of the clases array we expect null elements. If
2163 // the class table grew then the loop repeats. If classes are created after the loop has
2164 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002165 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002166 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002167 return;
2168 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 }
2170 }
2171}
2172
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002173ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002174 mirror::Class::ResetClass();
2175 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002176 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002177 mirror::Method::ResetClass();
2178 mirror::Reference::ResetClass();
2179 mirror::StackTraceElement::ResetClass();
2180 mirror::String::ResetClass();
2181 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002182 mirror::BooleanArray::ResetArrayClass();
2183 mirror::ByteArray::ResetArrayClass();
2184 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002185 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002186 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002187 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002188 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002189 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002190 mirror::IntArray::ResetArrayClass();
2191 mirror::LongArray::ResetArrayClass();
2192 mirror::ShortArray::ResetArrayClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002193 mirror::CallSite::ResetClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002194 mirror::MethodType::ResetClass();
2195 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002196 mirror::MethodHandlesLookup::ResetClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002197 mirror::VarHandle::ResetClass();
2198 mirror::FieldVarHandle::ResetClass();
2199 mirror::ArrayElementVarHandle::ResetClass();
2200 mirror::ByteArrayViewVarHandle::ResetClass();
2201 mirror::ByteBufferViewVarHandle::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002202 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002203 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002204 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002205 // CHA unloading analysis is not needed. No negative consequences are expected because
2206 // all the classloaders are deleted at the same time.
2207 DeleteClassLoader(self, data, false /*cleanup_cha*/);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002208 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002209 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002210}
2211
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002212void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002213 Runtime* const runtime = Runtime::Current();
2214 JavaVMExt* const vm = runtime->GetJavaVM();
2215 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002216 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002217 if (runtime->GetJit() != nullptr) {
2218 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2219 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002220 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002221 code_cache->RemoveMethodsIn(self, *data.allocator);
2222 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002223 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002224 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002225 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002226 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002227 // Cleanup references to single implementation ArtMethods that will be deleted.
2228 if (cleanup_cha) {
2229 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2230 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2231 }
2232
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002233 delete data.allocator;
2234 delete data.class_table;
2235}
2236
Mathieu Chartiere401d142015-04-22 13:56:20 -07002237mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002238 return down_cast<mirror::PointerArray*>(
2239 image_pointer_size_ == PointerSize::k64
2240 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2241 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002242}
2243
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002244mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002245 Thread* self,
2246 const DexFile& dex_file) {
2247 StackHandleScope<1> hs(self);
2248 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002249 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002250 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002251 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002252 self->AssertPendingOOMException();
2253 return nullptr;
2254 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002255 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002256 if (location == nullptr) {
2257 self->AssertPendingOOMException();
2258 return nullptr;
2259 }
2260 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002261 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002262}
2263
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002264mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2265 const DexFile& dex_file,
2266 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002267 ObjPtr<mirror::String> location = nullptr;
2268 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002269 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002270 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002271 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002272 mirror::DexCache::InitializeDexCache(self,
2273 dex_cache,
2274 location,
2275 &dex_file,
2276 linear_alloc,
2277 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002278 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002279 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002280}
2281
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002282mirror::Class* ClassLinker::AllocClass(Thread* self,
2283 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002284 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002285 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002286 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002287 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002288 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002289 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2290 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002291 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002292 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002293 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002294 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002295 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002296}
2297
Ian Rogers6fac4472014-02-25 17:01:10 -08002298mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002299 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002300}
2301
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002302mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002303 Thread* self,
2304 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002305 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002306 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002307}
2308
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002309mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2310 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002311 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002312 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002313 if (kIsDebugBuild) {
2314 StackHandleScope<1> hs(self);
2315 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2316 Thread::PoisonObjectPointersIfDebug();
2317 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002318
2319 // For temporary classes we must wait for them to be retired.
2320 if (init_done_ && klass->IsTemp()) {
2321 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002322 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002323 ThrowEarlierClassFailure(klass);
2324 return nullptr;
2325 }
2326 StackHandleScope<1> hs(self);
2327 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2328 ObjectLock<mirror::Class> lock(self, h_class);
2329 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002330 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002331 lock.WaitIgnoringInterrupts();
2332 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002333 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002334 ThrowEarlierClassFailure(h_class.Get());
2335 return nullptr;
2336 }
2337 CHECK(h_class->IsRetired());
2338 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002339 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002340 }
2341
Brian Carlstromaded5f72011-10-07 17:15:04 -07002342 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002343 size_t index = 0;
2344 // Maximum number of yield iterations until we start sleeping.
2345 static const size_t kNumYieldIterations = 1000;
2346 // How long each sleep is in us.
2347 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002348 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002349 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002350 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002351 {
2352 ObjectTryLock<mirror::Class> lock(self, h_class);
2353 // Can not use a monitor wait here since it may block when returning and deadlock if another
2354 // thread has locked klass.
2355 if (lock.Acquired()) {
2356 // Check for circular dependencies between classes, the lock is required for SetStatus.
2357 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2358 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002359 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002360 return nullptr;
2361 }
2362 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002363 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002364 {
2365 // Handle wrapper deals with klass moving.
2366 ScopedThreadSuspension sts(self, kSuspended);
2367 if (index < kNumYieldIterations) {
2368 sched_yield();
2369 } else {
2370 usleep(kSleepDurationUS);
2371 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002372 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002373 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002375
Vladimir Marko72ab6842017-01-20 19:32:50 +00002376 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002377 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002378 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379 }
2380 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002381 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002382 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002383 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002384}
2385
Ian Rogers68b56852014-08-29 20:19:11 -07002386typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2387
2388// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002389ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002390 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002391 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002392 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002394 return ClassPathEntry(dex_file, dex_class_def);
2395 }
2396 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002397 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002398}
2399
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002400bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2401 Thread* self,
2402 const char* descriptor,
2403 size_t hash,
2404 Handle<mirror::ClassLoader> class_loader,
2405 ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002406 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002407 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002408 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002409 return true;
2410 }
2411
Calin Juravlecdd49122017-07-05 20:09:53 -07002412 if (IsPathOrDexClassLoader(soa, class_loader)) {
2413 // For regular path or dex class loader the search order is:
2414 // - parent
2415 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002416
Calin Juravlecdd49122017-07-05 20:09:53 -07002417 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2418 StackHandleScope<1> hs(self);
2419 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2420 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2421 return false; // One of the parents is not supported.
2422 }
2423 if (*result != nullptr) {
2424 return true; // Found the class up the chain.
2425 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002426
Calin Juravlecdd49122017-07-05 20:09:53 -07002427 // Search the current class loader classpath.
2428 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002429 return true;
2430 }
2431
Calin Juravlecdd49122017-07-05 20:09:53 -07002432 if (IsDelegateLastClassLoader(soa, class_loader)) {
2433 // For delegate last, the search order is:
2434 // - boot class path
2435 // - class loader dex files
2436 // - parent
2437 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2438 if (*result != nullptr) {
2439 return true; // The class is part of the boot class path.
2440 }
2441
2442 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2443 if (*result != nullptr) {
2444 return true; // Found the class in the current class loader
2445 }
2446
2447 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2448 StackHandleScope<1> hs(self);
2449 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2450 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2451 }
2452
2453 // Unsupported class loader.
2454 *result = nullptr;
2455 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002456}
2457
2458// Finds the class in the boot class loader.
2459// If the class is found the method returns the resolved class. Otherwise it returns null.
2460ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2461 const char* descriptor,
2462 size_t hash) {
2463 ObjPtr<mirror::Class> result = nullptr;
2464 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2465 if (pair.second != nullptr) {
2466 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2467 if (klass != nullptr) {
2468 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002469 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002470 result = DefineClass(self,
2471 descriptor,
2472 hash,
2473 ScopedNullHandle<mirror::ClassLoader>(),
2474 *pair.first,
2475 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002476 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002477 if (result == nullptr) {
2478 CHECK(self->IsExceptionPending()) << descriptor;
2479 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002480 }
2481 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002482 return result;
2483}
Andreas Gampef865ea92015-04-13 22:14:19 -07002484
Calin Juravle415dc3d2017-06-28 11:03:12 -07002485ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2486 ScopedObjectAccessAlreadyRunnable& soa,
2487 const char* descriptor,
2488 size_t hash,
2489 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002490 DCHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002491 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002492
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002493 ObjPtr<mirror::Class> ret;
2494 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2495 const DexFile::ClassDef* dex_class_def =
2496 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2497 if (dex_class_def != nullptr) {
2498 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2499 descriptor,
2500 hash,
2501 class_loader,
2502 *cp_dex_file,
2503 *dex_class_def);
2504 if (klass == nullptr) {
2505 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2506 soa.Self()->ClearException();
2507 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002508 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002509 ret = klass;
2510 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002511 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002512 return true; // Continue with the next DexFile.
2513 };
2514
2515 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2516 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002517}
2518
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002519mirror::Class* ClassLinker::FindClass(Thread* self,
2520 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002521 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002522 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002523 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002524 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002525 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002526 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002527 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2528 // for primitive classes that aren't backed by dex files.
2529 return FindPrimitiveClass(descriptor[0]);
2530 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002531 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002532 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002533 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002534 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002535 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002536 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002537 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002538 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002539 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002540 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002541 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002542 return DefineClass(self,
2543 descriptor,
2544 hash,
2545 ScopedNullHandle<mirror::ClassLoader>(),
2546 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002547 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002548 } else {
2549 // The boot class loader is searched ahead of the application class loader, failures are
2550 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2551 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002552 ObjPtr<mirror::Throwable> pre_allocated =
2553 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002554 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002555 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002556 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002557 }
2558 ObjPtr<mirror::Class> result_ptr;
2559 bool descriptor_equals;
2560 if (descriptor[0] == '[') {
2561 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2562 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2563 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2564 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002565 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002566 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002567 bool known_hierarchy =
2568 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2569 if (result_ptr != nullptr) {
2570 // The chain was understood and we found the class. We still need to add the class to
2571 // the class table to protect from racy programs that can try and redefine the path list
2572 // which would change the Class<?> returned for subsequent evaluation of const-class.
2573 DCHECK(known_hierarchy);
2574 DCHECK(result_ptr->DescriptorEquals(descriptor));
2575 descriptor_equals = true;
2576 } else {
2577 // Either the chain wasn't understood or the class wasn't found.
2578 //
2579 // If the chain was understood but we did not find the class, let the Java-side
2580 // rediscover all this and throw the exception with the right stack trace. Note that
2581 // the Java-side could still succeed for racy programs if another thread is actively
2582 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002583
Calin Juravleccd56952016-12-15 17:57:38 +00002584 if (!self->CanCallIntoJava()) {
2585 // Oops, we can't call into java so we can't run actual class-loader code.
2586 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002587 ObjPtr<mirror::Throwable> pre_allocated =
2588 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2589 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002590 return nullptr;
2591 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002592
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002593 // Inlined DescriptorToDot(descriptor) with extra validation.
2594 //
2595 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2596 // the DescriptorEquals() check below and give a confusing error message. For example,
2597 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2598 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2599 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2600 size_t descriptor_length = strlen(descriptor);
2601 if (UNLIKELY(descriptor[0] != 'L') ||
2602 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2603 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2604 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2605 return nullptr;
2606 }
2607 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2608 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2609
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002610 ScopedLocalRef<jobject> class_loader_object(
2611 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002612 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2613 {
2614 ScopedThreadStateChange tsc(self, kNative);
2615 ScopedLocalRef<jobject> class_name_object(
2616 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2617 if (class_name_object.get() == nullptr) {
2618 DCHECK(self->IsExceptionPending()); // OOME.
2619 return nullptr;
2620 }
2621 CHECK(class_loader_object.get() != nullptr);
2622 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2623 WellKnownClasses::java_lang_ClassLoader_loadClass,
2624 class_name_object.get()));
2625 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002626 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002627 // broken loader - throw NPE to be compatible with Dalvik
2628 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2629 class_name_string.c_str()).c_str());
2630 return nullptr;
2631 }
2632 result_ptr = soa.Decode<mirror::Class>(result.get());
2633 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002634 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002635 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002636 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002637
2638 if (self->IsExceptionPending()) {
2639 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2640 // However, to comply with the RI behavior, first check if another thread succeeded.
2641 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2642 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2643 self->ClearException();
2644 return EnsureResolved(self, descriptor, result_ptr);
2645 }
2646 return nullptr;
2647 }
2648
2649 // Try to insert the class to the class table, checking for mismatch.
2650 ObjPtr<mirror::Class> old;
2651 {
2652 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2653 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2654 old = class_table->Lookup(descriptor, hash);
2655 if (old == nullptr) {
2656 old = result_ptr; // For the comparison below, after releasing the lock.
2657 if (descriptor_equals) {
2658 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2659 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2660 } // else throw below, after releasing the lock.
2661 }
2662 }
2663 if (UNLIKELY(old != result_ptr)) {
2664 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2665 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2666 mirror::Class* loader_class = class_loader->GetClass();
2667 const char* loader_class_name =
2668 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2669 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2670 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2671 << DescriptorToDot(descriptor) << "\").";
2672 return EnsureResolved(self, descriptor, old);
2673 }
2674 if (UNLIKELY(!descriptor_equals)) {
2675 std::string result_storage;
2676 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2677 std::string loader_storage;
2678 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2679 ThrowNoClassDefFoundError(
2680 "Initiating class loader of type %s returned class %s instead of %s.",
2681 DescriptorToDot(loader_class_name).c_str(),
2682 DescriptorToDot(result_name).c_str(),
2683 DescriptorToDot(descriptor).c_str());
2684 return nullptr;
2685 }
2686 // success, return mirror::Class*
2687 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002688}
2689
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002690mirror::Class* ClassLinker::DefineClass(Thread* self,
2691 const char* descriptor,
2692 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002693 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002694 const DexFile& dex_file,
2695 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002696 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002697 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002698
Brian Carlstromaded5f72011-10-07 17:15:04 -07002699 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002700 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002701 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002702 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002703 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002704 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002705 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002706 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002707 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07002708 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002709 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002710 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002711 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07002712 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002713 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002714 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002715 }
2716
Andreas Gampefa4333d2017-02-14 11:10:34 -08002717 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002718 // Allocate a class with the status of not ready.
2719 // Interface object should get the right size here. Regular class will
2720 // figure out the right size later and be replaced with one of the right
2721 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002722 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002723 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002724 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002725 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002726 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002727 }
Alex Lightb0f11922017-01-23 14:25:17 -08002728 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2729 // nothing.
2730 DexFile const* new_dex_file = nullptr;
2731 DexFile::ClassDef const* new_class_def = nullptr;
2732 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2733 // will only be called once.
2734 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2735 klass,
2736 class_loader,
2737 dex_file,
2738 dex_class_def,
2739 &new_dex_file,
2740 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002741 // Check to see if an exception happened during runtime callbacks. Return if so.
2742 if (self->IsExceptionPending()) {
2743 return nullptr;
2744 }
Alex Lightb0f11922017-01-23 14:25:17 -08002745 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002746 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002747 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002748 return nullptr;
2749 }
2750 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002751 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002752
Jeff Hao848f70a2014-01-15 13:49:50 -08002753 // Mark the string class by setting its access flag.
2754 if (UNLIKELY(!init_done_)) {
2755 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2756 klass->SetStringClass();
2757 }
2758 }
2759
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002760 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002761 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002762 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002763 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002764
Mathieu Chartier590fee92013-09-13 13:46:47 -07002765 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002766 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002767 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002768 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2769 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002770 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002771 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002772
Mathieu Chartierc7853442015-03-27 14:35:38 -07002773 // Load the fields and other things after we are inserted in the table. This is so that we don't
2774 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2775 // other reason is that the field roots are only visited from the class table. So we need to be
2776 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002777 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002778 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002779 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002780 // An exception occured during load, set status to erroneous while holding klass' lock in case
2781 // notification is necessary.
2782 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002783 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002784 }
2785 return nullptr;
2786 }
2787
Brian Carlstromaded5f72011-10-07 17:15:04 -07002788 // Finish loading (if necessary) by finding parents
2789 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002790 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002791 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002792 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002793 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002794 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002795 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002796 }
2797 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002798
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002799 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002800 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002801 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002802
Brian Carlstromaded5f72011-10-07 17:15:04 -07002803 // Link the class (if necessary)
2804 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002805 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002806 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002807
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002808 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002809 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002810 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002811 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002812 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002813 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002814 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002815 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002816 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002817 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002818 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002819
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002820 // Instrumentation may have updated entrypoints for all methods of all
2821 // classes. However it could not update methods of this class while we
2822 // were loading it. Now the class is resolved, we can update entrypoints
2823 // as required by instrumentation.
2824 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2825 // We must be in the kRunnable state to prevent instrumentation from
2826 // suspending all threads to update entrypoints while we are doing it
2827 // for this class.
2828 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002829 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002830 }
2831
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002832 /*
2833 * We send CLASS_PREPARE events to the debugger from here. The
2834 * definition of "preparation" is creating the static fields for a
2835 * class and initializing them to the standard default values, but not
2836 * executing any code (that comes later, during "initialization").
2837 *
2838 * We did the static preparation in LinkClass.
2839 *
2840 * The class has been prepared and resolved but possibly not yet verified
2841 * at this point.
2842 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002843 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002844
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002845 // Notify native debugger of the new class and its layout.
2846 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2847
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002848 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002849}
2850
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002851uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2852 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002853 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002854 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002855 size_t num_8 = 0;
2856 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002857 size_t num_32 = 0;
2858 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002859 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002860 // We allow duplicate definitions of the same field in a class_data_item
2861 // but ignore the repeated indexes here, b/21868015.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002862 uint32_t last_field_idx = dex::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002863 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002864 uint32_t field_idx = it.GetMemberIndex();
2865 // Ordering enforced by DexFileVerifier.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002866 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
Vladimir Marko879d27b2016-03-15 20:31:50 +00002867 if (UNLIKELY(field_idx == last_field_idx)) {
2868 continue;
2869 }
2870 last_field_idx = field_idx;
2871 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002872 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002873 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002874 switch (c) {
2875 case 'L':
2876 case '[':
2877 num_ref++;
2878 break;
2879 case 'J':
2880 case 'D':
2881 num_64++;
2882 break;
2883 case 'I':
2884 case 'F':
2885 num_32++;
2886 break;
2887 case 'S':
2888 case 'C':
2889 num_16++;
2890 break;
2891 case 'B':
2892 case 'Z':
2893 num_8++;
2894 break;
2895 default:
2896 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002897 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002898 }
2899 }
2900 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002901 return mirror::Class::ComputeClassSize(false,
2902 0,
2903 num_8,
2904 num_16,
2905 num_32,
2906 num_64,
2907 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002908 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002909}
2910
Alex Lightfc49fec2018-01-16 22:28:36 +00002911// Special case to get oat code without overwriting a trampoline.
2912const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002913 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002914 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002915 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002916 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002917 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2918 if (code != nullptr) {
2919 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002920 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002921 if (method->IsNative()) {
2922 // No code and native? Use generic trampoline.
2923 return GetQuickGenericJniStub();
2924 }
2925 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002926}
2927
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002928bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2929 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2930 return false;
2931 }
2932
Elliott Hughes956af0f2014-12-11 14:34:28 -08002933 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002934 return true;
2935 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002936
2937 Runtime* runtime = Runtime::Current();
2938 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2939 if (instr->InterpretOnly()) {
2940 return true;
2941 }
2942
2943 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2944 // Doing this check avoids doing compiled/interpreter transitions.
2945 return true;
2946 }
2947
2948 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2949 // Force the use of interpreter when it is required by the debugger.
2950 return true;
2951 }
2952
Alex Light8f34aba2017-10-09 13:46:32 -07002953 if (Thread::Current()->IsAsyncExceptionPending()) {
2954 // Force use of interpreter to handle async-exceptions
2955 return true;
2956 }
2957
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002958 if (runtime->IsJavaDebuggable()) {
2959 // For simplicity, we ignore precompiled code and go to the interpreter
2960 // assuming we don't already have jitted code.
2961 // We could look at the oat file where `quick_code` is being defined,
2962 // and check whether it's been compiled debuggable, but we decided to
2963 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002964 jit::Jit* jit = Runtime::Current()->GetJit();
2965 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2966 }
2967
David Srbeckyf4480162016-03-16 00:06:24 +00002968 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002969 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002970 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002971 // since we want to JIT it (at first use) with extra stackmaps for native
2972 // debugging. We keep however all AOT code from the boot image,
2973 // since the JIT-at-first-use is blocking and would result in non-negligible
2974 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002975 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002976 }
2977
2978 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002979}
2980
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002981void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002982 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002983 if (klass->NumDirectMethods() == 0) {
2984 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002985 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002986 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002987 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002988 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002989 return; // OAT file unavailable.
2990 }
Ian Rogers19846512012-02-24 11:42:47 -08002991 }
Alex Light64ad14d2014-08-19 14:23:13 -07002992
Mathieu Chartierf8322842014-05-16 10:59:25 -07002993 const DexFile& dex_file = klass->GetDexFile();
2994 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002995 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002996 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002997 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002998 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002999 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07003000 it.SkipAllFields();
Ian Rogers97b52f82014-08-14 11:34:07 -07003001 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003002 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3003 klass->GetDexClassDefIndex(),
3004 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003005 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003006 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003007 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003008 if (!method->IsStatic()) {
3009 // Only update static methods.
3010 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003011 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003012 const void* quick_code = nullptr;
3013 if (has_oat_class) {
3014 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003015 quick_code = oat_method.GetQuickCode();
3016 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003017 // Check whether the method is native, in which case it's generic JNI.
3018 if (quick_code == nullptr && method->IsNative()) {
3019 quick_code = GetQuickGenericJniStub();
3020 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003021 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003022 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003023 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003024 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003025 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003026 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003027}
3028
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003029// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3030// method. Should only be called on non-invokable methods.
3031inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003032 DCHECK(method != nullptr);
3033 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003034 method->SetEntryPointFromQuickCompiledCodePtrSize(
3035 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3036 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003037}
3038
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003039static void LinkCode(ClassLinker* class_linker,
3040 ArtMethod* method,
3041 const OatFile::OatClass* oat_class,
3042 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003043 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003044 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003045 // The following code only applies to a non-compiler runtime.
3046 return;
3047 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003048 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003049 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003050 if (oat_class != nullptr) {
3051 // Every kind of method should at least get an invoke stub from the oat_method.
3052 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003053 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003054 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003055 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003056
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003057 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003058 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003059 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003060
Alex Light9139e002015-10-09 15:59:48 -07003061 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003062 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003063 return;
3064 }
Ian Rogers19846512012-02-24 11:42:47 -08003065
3066 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003067 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003068 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3069 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003070 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003071 } else if (quick_code == nullptr && method->IsNative()) {
3072 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003073 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003074 // Set entry point from compiled code if there's no code or in interpreter only mode.
3075 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003076 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003077
Ian Rogers62d6c772013-02-27 08:32:07 -08003078 if (method->IsNative()) {
3079 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003080 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003081
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003082 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003083 // We have a native method here without code. Then it should have either the generic JNI
3084 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3085 // TODO: this doesn't handle all the cases where trampolines may be installed.
3086 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003087 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3088 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003089 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003090 }
3091}
3092
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003093void ClassLinker::SetupClass(const DexFile& dex_file,
3094 const DexFile::ClassDef& dex_class_def,
3095 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003096 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003097 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003098 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003099 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003100 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003101 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003102
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003103 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003104 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003105 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003106 klass->SetAccessFlags(access_flags);
3107 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003108 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003109 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003110
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003111 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003112 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003113}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003114
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003115void ClassLinker::LoadClass(Thread* self,
3116 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003117 const DexFile::ClassDef& dex_class_def,
3118 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003119 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003120 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003121 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003122 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003123 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003124}
3125
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003126LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3127 LinearAlloc* allocator,
3128 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003129 if (length == 0) {
3130 return nullptr;
3131 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003132 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3133 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3134 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003135 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003136 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003137 CHECK(ret != nullptr);
3138 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3139 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003140}
3141
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003142LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3143 LinearAlloc* allocator,
3144 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003145 if (length == 0) {
3146 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003147 }
Vladimir Marko14632852015-08-17 12:07:23 +01003148 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3149 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003150 const size_t storage_size =
3151 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003152 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003153 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003154 CHECK(ret != nullptr);
3155 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003156 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003157 }
3158 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003159}
3160
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003161LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003162 if (class_loader == nullptr) {
3163 return Runtime::Current()->GetLinearAlloc();
3164 }
3165 LinearAlloc* allocator = class_loader->GetAllocator();
3166 DCHECK(allocator != nullptr);
3167 return allocator;
3168}
3169
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003170LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003171 if (class_loader == nullptr) {
3172 return Runtime::Current()->GetLinearAlloc();
3173 }
3174 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3175 LinearAlloc* allocator = class_loader->GetAllocator();
3176 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003177 RegisterClassLoader(class_loader);
3178 allocator = class_loader->GetAllocator();
3179 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003180 }
3181 return allocator;
3182}
3183
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003184void ClassLinker::LoadClassMembers(Thread* self,
3185 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003186 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003187 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003188 {
3189 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3190 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003191 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003192 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003193 // We allow duplicate definitions of the same field in a class_data_item
3194 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003195 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003196 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003197 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3198 allocator,
3199 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003200 size_t num_sfields = 0;
3201 uint32_t last_field_idx = 0u;
3202 for (; it.HasNextStaticField(); it.Next()) {
3203 uint32_t field_idx = it.GetMemberIndex();
3204 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3205 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3206 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003207 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003208 ++num_sfields;
3209 last_field_idx = field_idx;
3210 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003211 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003212
Mathieu Chartiere401d142015-04-22 13:56:20 -07003213 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003214 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3215 allocator,
3216 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003217 size_t num_ifields = 0u;
3218 last_field_idx = 0u;
3219 for (; it.HasNextInstanceField(); it.Next()) {
3220 uint32_t field_idx = it.GetMemberIndex();
3221 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3222 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3223 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003224 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003225 ++num_ifields;
3226 last_field_idx = field_idx;
3227 }
3228 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003229
Vladimir Marko23682bf2015-06-24 14:28:03 +01003230 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3231 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003232 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003233 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3234 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003235 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3236 if (sfields != nullptr) {
3237 sfields->SetSize(num_sfields);
3238 }
3239 if (ifields != nullptr) {
3240 ifields->SetSize(num_ifields);
3241 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003242 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003243 // Set the field arrays.
3244 klass->SetSFieldsPtr(sfields);
3245 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003246 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003247 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3248 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003249 bool has_oat_class = false;
3250 const OatFile::OatClass oat_class =
3251 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3252 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3253 : OatFile::OatClass::Invalid();
3254 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003255 klass->SetMethodsPtr(
3256 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3257 it.NumDirectMethods(),
3258 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003259 size_t class_def_method_index = 0;
Andreas Gampee2abbc62017-09-15 11:59:26 -07003260 uint32_t last_dex_method_index = dex::kDexNoIndex;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003261 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003262 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003263 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3264 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003265 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003266 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003267 uint32_t it_method_index = it.GetMemberIndex();
3268 if (last_dex_method_index == it_method_index) {
3269 // duplicate case
3270 method->SetMethodIndex(last_class_def_method_index);
3271 } else {
3272 method->SetMethodIndex(class_def_method_index);
3273 last_dex_method_index = it_method_index;
3274 last_class_def_method_index = class_def_method_index;
3275 }
3276 class_def_method_index++;
3277 }
3278 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3279 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003280 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003281 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003282 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003283 class_def_method_index++;
3284 }
3285 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003286 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003287 // Ensure that the card is marked so that remembered sets pick up native roots.
3288 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003289 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003290}
3291
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003292void ClassLinker::LoadField(const ClassDataItemIterator& it,
3293 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003294 ArtField* dst) {
3295 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003296 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003297 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003298
3299 // Get access flags from the DexFile. If this is a boot class path class,
3300 // also set its runtime hidden API access flags.
3301 uint32_t access_flags = it.GetFieldAccessFlags();
3302 if (klass->IsBootStrapClassLoaded()) {
3303 access_flags =
3304 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3305 }
3306 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003307}
3308
Mathieu Chartier268764d2016-09-13 12:09:38 -07003309void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003310 const ClassDataItemIterator& it,
3311 Handle<mirror::Class> klass,
3312 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003313 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003314 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003315 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003316
Mathieu Chartier268764d2016-09-13 12:09:38 -07003317 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003318 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003319 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003320 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003321
David Brazdilf6a8a552018-01-15 18:10:50 +00003322 // Get access flags from the DexFile. If this is a boot class path class,
3323 // also set its runtime hidden API access flags.
Andreas Gampe51829322014-08-25 15:05:04 -07003324 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003325
David Brazdilf6a8a552018-01-15 18:10:50 +00003326 if (klass->IsBootStrapClassLoaded()) {
3327 access_flags =
3328 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3329 }
3330
Ian Rogersdfb325e2013-10-30 01:00:44 -07003331 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003332 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003333 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3334 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003335 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003336 klass->SetFinalizable();
3337 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003338 std::string temp;
3339 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003340 // The Enum class declares a "final" finalize() method to prevent subclasses from
3341 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3342 // subclasses, so we exclude it here.
3343 // We also want to avoid setting the flag on Object, where we know that finalize() is
3344 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003345 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3346 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003347 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003348 }
3349 }
3350 }
3351 } else if (method_name[0] == '<') {
3352 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003353 bool is_init = (strcmp("<init>", method_name) == 0);
3354 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003355 if (UNLIKELY(!is_init && !is_clinit)) {
3356 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3357 } else {
3358 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3359 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003360 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003361 access_flags |= kAccConstructor;
3362 }
3363 }
3364 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003365 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3366 // Check if the native method is annotated with @FastNative or @CriticalNative.
3367 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3368 dex_file, dst->GetClassDef(), dex_method_idx);
3369 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003370 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003371}
3372
Ian Rogers7b078e82014-09-10 14:44:24 -07003373void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003374 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003375 self,
3376 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003377 Runtime::Current()->GetLinearAlloc());
3378 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003379 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003380}
3381
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003382void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003383 ObjPtr<mirror::DexCache> dex_cache) {
3384 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003385 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003386 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
3387 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003388}
3389
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003390void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003391 ObjPtr<mirror::DexCache> dex_cache,
3392 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003393 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003394 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003395 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003396 // For app images, the dex cache location may be a suffix of the dex file location since the
3397 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003398 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3399 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003400 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3401 std::string dex_file_location = dex_file.GetLocation();
3402 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003403 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003404 // Take suffix.
3405 const std::string dex_file_suffix = dex_file_location.substr(
3406 dex_file_location.length() - dex_cache_length,
3407 dex_cache_length);
3408 // Example dex_cache location is SettingsProvider.apk and
3409 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003410 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003411 const OatFile* oat_file =
3412 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003413 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3414 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3415 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3416 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003417 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003418 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3419 DexCacheData data = *it;
3420 if (self->IsJWeakCleared(data.weak_root)) {
3421 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003422 it = dex_caches_.erase(it);
3423 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003424 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003425 it->dex_file->GetOatDexFile() != nullptr &&
3426 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003427 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003428 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003429 ++it;
3430 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003431 }
Vladimir Markob066d432018-01-03 13:14:37 +00003432 if (initialize_oat_file_data) {
3433 // Initialize the .data.bimg.rel.ro section.
3434 if (!oat_file->GetBootImageRelocations().empty()) {
3435 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3436 CheckedCall(mprotect,
3437 "un-protect boot image relocations",
3438 reloc_begin,
3439 oat_file->DataBimgRelRoSize(),
3440 PROT_READ | PROT_WRITE);
3441 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3442 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3443 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3444 const_cast<uint32_t&>(relocation) += boot_image_begin;
3445 }
3446 CheckedCall(mprotect,
3447 "protect boot image relocations",
3448 reloc_begin,
3449 oat_file->DataBimgRelRoSize(),
3450 PROT_READ);
3451 }
3452
3453 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003454 // TODO: Pre-initialize from boot/app image?
3455 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3456 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3457 entry = resolution_method;
3458 }
3459 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003460 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003461 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003462 DexCacheData data;
3463 data.weak_root = dex_cache_jweak;
3464 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003465 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky440a9b32018-02-15 17:47:29 +00003466 AddNativeDebugInfoForDex(self, ArrayRef<const uint8_t>(data.dex_file->Begin(),
3467 data.dex_file->Size()));
Vladimir Markocd556b02017-02-03 11:47:34 +00003468 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003469 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3470 // path dex caches without an image.
3471 data.class_table->InsertStrongRoot(dex_cache);
3472 if (class_loader != nullptr) {
3473 // Since we added a strong root to the class table, do the write barrier as required for
3474 // remembered sets and generational GCs.
3475 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3476 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003477 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003478}
3479
Vladimir Markocd556b02017-02-03 11:47:34 +00003480ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3481 return data.IsValid()
3482 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3483 : nullptr;
3484}
3485
3486ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3487 Thread* self,
3488 ObjPtr<mirror::DexCache> dex_cache,
3489 const DexCacheData& data,
3490 ObjPtr<mirror::ClassLoader> class_loader) {
3491 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3492 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3493 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3494 "Attempt to register dex file %s with multiple class loaders",
3495 data.dex_file->GetLocation().c_str());
3496 return nullptr;
3497 }
3498 return dex_cache;
3499}
3500
Alex Light07f06212017-06-01 14:01:43 -07003501void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3502 ObjPtr<mirror::ClassLoader> class_loader) {
3503 Thread* self = Thread::Current();
3504 StackHandleScope<2> hs(self);
3505 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3506 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3507 const DexFile* dex_file = dex_cache->GetDexFile();
3508 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3509 if (kIsDebugBuild) {
3510 DexCacheData old_data;
3511 {
3512 ReaderMutexLock mu(self, *Locks::dex_lock_);
3513 old_data = FindDexCacheDataLocked(*dex_file);
3514 }
3515 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3516 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3517 << "been registered on dex file " << dex_file->GetLocation();
3518 }
3519 ClassTable* table;
3520 {
3521 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3522 table = InsertClassTableForClassLoader(h_class_loader.Get());
3523 }
3524 WriterMutexLock mu(self, *Locks::dex_lock_);
3525 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3526 table->InsertStrongRoot(h_dex_cache.Get());
3527 if (h_class_loader.Get() != nullptr) {
3528 // Since we added a strong root to the class table, do the write barrier as required for
3529 // remembered sets and generational GCs.
3530 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3531 }
3532}
3533
Vladimir Markocd556b02017-02-03 11:47:34 +00003534ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3535 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003536 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003537 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003538 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003539 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003540 old_data = FindDexCacheDataLocked(dex_file);
3541 }
3542 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3543 if (old_dex_cache != nullptr) {
3544 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003545 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003546 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3547 DCHECK(linear_alloc != nullptr);
3548 ClassTable* table;
3549 {
3550 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3551 table = InsertClassTableForClassLoader(class_loader);
3552 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003553 // Don't alloc while holding the lock, since allocation may need to
3554 // suspend all threads and another thread may need the dex_lock_ to
3555 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003556 StackHandleScope<3> hs(self);
3557 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003558 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003559 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3560 self,
3561 dex_file)));
3562 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003563 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003564 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003565 old_data = FindDexCacheDataLocked(dex_file);
3566 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003567 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003568 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3569 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3570 // that the arrays are null.
3571 mirror::DexCache::InitializeDexCache(self,
3572 h_dex_cache.Get(),
3573 h_location.Get(),
3574 &dex_file,
3575 linear_alloc,
3576 image_pointer_size_);
3577 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003578 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003579 }
3580 if (old_dex_cache != nullptr) {
3581 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3582 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003583 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003584 self->ClearException();
3585 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3586 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3587 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003588 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003589 self->AssertPendingOOMException();
3590 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003591 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003592 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003593 if (h_class_loader.Get() != nullptr) {
3594 // Since we added a strong root to the class table, do the write barrier as required for
3595 // remembered sets and generational GCs.
3596 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3597 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003598 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003599}
3600
Vladimir Markocd556b02017-02-03 11:47:34 +00003601bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003602 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003603 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003604}
3605
Vladimir Markocd556b02017-02-03 11:47:34 +00003606ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3607 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003608 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3609 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003610 if (dex_cache != nullptr) {
3611 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003612 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003613 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003614 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003615 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003616 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003617 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003618 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003619 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3620 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003621 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003622}
3623
Vladimir Markocd556b02017-02-03 11:47:34 +00003624ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3625 const DexFile* dex_file = dex_cache->GetDexFile();
3626 DCHECK(dex_file != nullptr);
3627 ReaderMutexLock mu(self, *Locks::dex_lock_);
3628 // Search assuming unique-ness of dex file.
3629 for (const DexCacheData& data : dex_caches_) {
3630 // Avoid decoding (and read barriers) other unrelated dex caches.
3631 if (data.dex_file == dex_file) {
3632 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3633 if (registered_dex_cache != nullptr) {
3634 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3635 return data.class_table;
3636 }
3637 }
3638 }
3639 return nullptr;
3640}
3641
3642ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3643 // Search assuming unique-ness of dex file.
3644 for (const DexCacheData& data : dex_caches_) {
3645 // Avoid decoding (and read barriers) other unrelated dex caches.
3646 if (data.dex_file == &dex_file) {
3647 return data;
3648 }
3649 }
3650 return DexCacheData();
3651}
3652
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003653mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003654 ObjPtr<mirror::Class> klass =
3655 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003656 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003657 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003658 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003659 }
3660 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003661}
3662
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003663mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003664 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003665 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003666 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003667 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003668 StackHandleScope<1> hs(self);
3669 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003670 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003671 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3672 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003673 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00003674 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003675 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003676 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3677 h_class.Get(),
3678 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003679 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003680 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003681}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003682
Brian Carlstrombe977852011-07-19 14:54:54 -07003683// Create an array class (i.e. the class object for the array, not the
3684// array itself). "descriptor" looks like "[C" or "[[[[B" or
3685// "[Ljava/lang/String;".
3686//
3687// If "descriptor" refers to an array of primitives, look up the
3688// primitive type's internally-generated class object.
3689//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003690// "class_loader" is the class loader of the class that's referring to
3691// us. It's used to ensure that we're looking for the element type in
3692// the right context. It does NOT become the class loader for the
3693// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003694//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003695// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003696mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003697 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003698 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003699 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003700 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003701 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3702 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003703 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003704 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003705 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003706 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3707 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003708 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003709 DCHECK(self->IsExceptionPending());
3710 return nullptr;
3711 } else {
3712 self->ClearException();
3713 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003714 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003715 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3716 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3717 return nullptr;
3718 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003719 // See if the component type is already loaded. Array classes are
3720 // always associated with the class loader of their underlying
3721 // element type -- an array of Strings goes with the loader for
3722 // java/lang/String -- so we need to look for it there. (The
3723 // caller should have checked for the existence of the class
3724 // before calling here, but they did so with *their* class loader,
3725 // not the component type's loader.)
3726 //
3727 // If we find it, the caller adds "loader" to the class' initiating
3728 // loader list, which should prevent us from going through this again.
3729 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003730 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003731 // are the same, because our caller (FindClass) just did the
3732 // lookup. (Even if we get this wrong we still have correct behavior,
3733 // because we effectively do this lookup again when we add the new
3734 // class to the hash table --- necessary because of possible races with
3735 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003736 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003737 ObjPtr<mirror::Class> new_class =
3738 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003739 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003740 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003741 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003742 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003743
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003744 // Fill out the fields in the Class.
3745 //
3746 // It is possible to execute some methods against arrays, because
3747 // all arrays are subclasses of java_lang_Object_, so we need to set
3748 // up a vtable. We can just point at the one in java_lang_Object_.
3749 //
3750 // Array classes are simple enough that we don't need to do a full
3751 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003752 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003753 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003754 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003755 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003756 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003757 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003758 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
3759 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
3760 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003761 } else if (strcmp(descriptor, "[C") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003762 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003763 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003764 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003765 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003766 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003767 }
3768 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003769 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003770 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003771 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003772 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003773 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003774 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003775 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003776 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003777 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003778 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003779 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003780 new_class->SetSuperClass(java_lang_Object);
3781 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003782 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003783 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003784 if (component_type->IsPrimitive()) {
3785 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3786 } else {
3787 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3788 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00003789 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003790 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3791 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3792 new_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003793 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003794 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003795 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003796
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003797 // All arrays have java/lang/Cloneable and java/io/Serializable as
3798 // interfaces. We need to set that up here, so that stuff like
3799 // "instanceof" works right.
3800 //
3801 // Note: The GC could run during the call to FindSystemClass,
3802 // so we need to make sure the class object is GC-valid while we're in
3803 // there. Do this by clearing the interface list so the GC will just
3804 // think that the entries are null.
3805
3806
3807 // Use the single, global copies of "interfaces" and "iftable"
3808 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003809 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003810 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003811 CHECK(array_iftable != nullptr);
3812 new_class->SetIfTable(array_iftable);
3813 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003814
Elliott Hughes00626c22013-06-14 15:04:14 -07003815 // Inherit access flags from the component type.
3816 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3817 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3818 access_flags &= kAccJavaFlagsMask;
3819 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003820 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003821 access_flags |= kAccAbstract | kAccFinal;
3822 access_flags &= ~kAccInterface;
3823
3824 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003825
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003826 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003827 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003828 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3829 // duplicate events in case of races. Array classes don't really follow dedicated
3830 // load and prepare, anyways.
3831 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3832 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3833
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003834 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003835 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003836 }
3837 // Another thread must have loaded the class after we
3838 // started but before we finished. Abandon what we've
3839 // done.
3840 //
3841 // (Yes, this happens.)
3842
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003843 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003844}
3845
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003846mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003847 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassRoots();
Ian Rogers62f05122014-03-21 11:21:29 -07003848 switch (type) {
3849 case 'B':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003850 return GetClassRoot(ClassRoot::kPrimitiveByte, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003851 case 'C':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003852 return GetClassRoot(ClassRoot::kPrimitiveChar, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003853 case 'D':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003854 return GetClassRoot(ClassRoot::kPrimitiveDouble, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003855 case 'F':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003856 return GetClassRoot(ClassRoot::kPrimitiveFloat, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003857 case 'I':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003858 return GetClassRoot(ClassRoot::kPrimitiveInt, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003859 case 'J':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003860 return GetClassRoot(ClassRoot::kPrimitiveLong, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003861 case 'S':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003862 return GetClassRoot(ClassRoot::kPrimitiveShort, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003863 case 'Z':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003864 return GetClassRoot(ClassRoot::kPrimitiveBoolean, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003865 case 'V':
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003866 return GetClassRoot(ClassRoot::kPrimitiveVoid, class_roots).Ptr();
Ian Rogers62f05122014-03-21 11:21:29 -07003867 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003868 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003869 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003870 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003871 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003872 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003873}
3874
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003875mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003876 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003877 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003878 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003879 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003880 source += " from ";
3881 source += dex_cache->GetLocation()->ToModifiedUtf8();
3882 }
3883 LOG(INFO) << "Loaded class " << descriptor << source;
3884 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003885 {
3886 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003887 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003888 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003889 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003890 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003891 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003892 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003893 VerifyObject(klass);
3894 class_table->InsertWithHash(klass, hash);
3895 if (class_loader != nullptr) {
3896 // This is necessary because we need to have the card dirtied for remembered sets.
3897 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3898 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003899 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003900 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003901 }
3902 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003903 if (kIsDebugBuild) {
3904 // Test that copied methods correctly can find their holder.
3905 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3906 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3907 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003908 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003909 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003910}
3911
Vladimir Marko1998cd02017-01-13 13:02:58 +00003912void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003913 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3914 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3915 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3916 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003917 }
3918}
3919
Alex Lighte64300b2015-12-15 15:02:47 -08003920// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003921void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003922 LengthPrefixedArray<ArtMethod>* new_methods) {
3923 klass->SetMethodsPtrUnchecked(new_methods,
3924 klass->NumDirectMethods(),
3925 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003926 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003927 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003928}
3929
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003930mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003931 const char* descriptor,
3932 ObjPtr<mirror::ClassLoader> class_loader) {
3933 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3934}
3935
3936mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003937 const char* descriptor,
3938 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003939 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003940 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3941 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3942 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003943 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003944 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003945 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003946 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003947 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003948 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003949}
3950
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003951class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3952 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08003953 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003954
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003955 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003956 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003957 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003958 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003959 if (class_table != nullptr) {
3960 class_table->FreezeSnapshot();
3961 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003962 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003963};
3964
3965void ClassLinker::MoveClassTableToPreZygote() {
3966 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003967 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003968 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003969 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003970}
3971
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003972// Look up classes by hash and descriptor and put all matching ones in the result array.
3973class LookupClassesVisitor : public ClassLoaderVisitor {
3974 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003975 LookupClassesVisitor(const char* descriptor,
3976 size_t hash,
3977 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003978 : descriptor_(descriptor),
3979 hash_(hash),
3980 result_(result) {}
3981
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003982 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003983 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003984 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003985 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003986 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3987 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003988 result_->push_back(klass);
3989 }
3990 }
3991
3992 private:
3993 const char* const descriptor_;
3994 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003995 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003996};
3997
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003998void ClassLinker::LookupClasses(const char* descriptor,
3999 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004000 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004001 Thread* const self = Thread::Current();
4002 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004003 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004004 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004005 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004006 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004007 result.push_back(klass);
4008 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004009 LookupClassesVisitor visitor(descriptor, hash, &result);
4010 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004011}
4012
Alex Lightf1f10492015-10-07 16:08:36 -07004013bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4014 Handle<mirror::Class> klass,
4015 Handle<mirror::Class> supertype) {
4016 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004017 DCHECK(klass != nullptr);
4018 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004019
Alex Lightf1f10492015-10-07 16:08:36 -07004020 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4021 VerifyClass(self, supertype);
4022 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004023
4024 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4025 // The supertype is either verified, or we soft failed at AOT time.
4026 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004027 return true;
4028 }
4029 // If we got this far then we have a hard failure.
4030 std::string error_msg =
4031 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004032 klass->PrettyDescriptor().c_str(),
4033 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004034 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004035 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004036 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004037 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004038 // Set during VerifyClass call (if at all).
4039 self->ClearException();
4040 }
4041 // Change into a verify error.
4042 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004043 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004044 self->GetException()->SetCause(cause.Get());
4045 }
4046 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4047 if (Runtime::Current()->IsAotCompiler()) {
4048 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4049 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004050 // Need to grab the lock to change status.
4051 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004052 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004053 return false;
4054}
4055
Andreas Gampecc1b5352016-12-01 16:58:38 -08004056// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
4057// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
4058// before.
4059static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
4060 REQUIRES_SHARED(Locks::mutator_lock_) {
4061 if (!klass->WasVerificationAttempted()) {
4062 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
4063 klass->SetVerificationAttempted();
4064 }
4065}
4066
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004067verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004068 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004069 {
4070 // TODO: assert that the monitor on the Class is held
4071 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004072
Andreas Gampe884f3b82016-03-30 19:52:58 -07004073 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004074 ClassStatus old_status = klass->GetStatus();
4075 while (old_status == ClassStatus::kVerifying ||
4076 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004077 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004078 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4079 // case we may see the same status again. b/62912904. This is why the check is
4080 // greater or equal.
4081 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004082 << "Class '" << klass->PrettyClass()
4083 << "' performed an illegal verification state transition from " << old_status
4084 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004085 old_status = klass->GetStatus();
4086 }
jeffhao98eacac2011-09-14 16:11:53 -07004087
Andreas Gampe884f3b82016-03-30 19:52:58 -07004088 // The class might already be erroneous, for example at compile time if we attempted to verify
4089 // this class as a parent to another.
4090 if (klass->IsErroneous()) {
4091 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004092 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004093 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004094
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004095 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004096 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004097 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004098 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004099 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004100
4101 // For AOT, don't attempt to re-verify if we have already found we should
4102 // verify at runtime.
4103 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004104 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004105 }
jeffhao98eacac2011-09-14 16:11:53 -07004106
Vladimir Marko2c64a832018-01-04 11:31:56 +00004107 if (klass->GetStatus() == ClassStatus::kResolved) {
4108 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004109 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004110 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004111 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004112 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004113 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004114 }
4115
4116 // Skip verification if disabled.
4117 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004118 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004119 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004120 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004121 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004122 }
4123
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004124 VLOG(class_linker) << "Beginning verification for class: "
4125 << klass->PrettyDescriptor()
4126 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4127
Ian Rogers9ffb0392012-09-10 11:56:50 -07004128 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004129 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004130 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4131 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004132 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004133 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004134 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004135 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004136
Alex Lightf1f10492015-10-07 16:08:36 -07004137 // Verify all default super-interfaces.
4138 //
4139 // (1) Don't bother if the superclass has already had a soft verification failure.
4140 //
4141 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4142 // recursive initialization by themselves. This is because when an interface is initialized
4143 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4144 // but choose not to for an optimization. If the interfaces is being verified due to a class
4145 // initialization (which would need all the default interfaces to be verified) the class code
4146 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004147 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004148 && !klass->IsInterface()) { // See (2)
4149 int32_t iftable_count = klass->GetIfTableCount();
4150 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4151 // Loop through all interfaces this class has defined. It doesn't matter the order.
4152 for (int32_t i = 0; i < iftable_count; i++) {
4153 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004154 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004155 // We only care if we have default interfaces and can skip if we are already verified...
4156 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4157 continue;
4158 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4159 // We had a hard failure while verifying this interface. Just return immediately.
4160 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004161 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004162 } else if (UNLIKELY(!iface->IsVerified())) {
4163 // We softly failed to verify the iface. Stop checking and clean up.
4164 // Put the iface into the supertype handle so we know what caused us to fail.
4165 supertype.Assign(iface.Get());
4166 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004167 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004168 }
4169 }
4170
Alex Lightf1f10492015-10-07 16:08:36 -07004171 // At this point if verification failed, then supertype is the "first" supertype that failed
4172 // verification (without a specific order). If verification succeeded, then supertype is either
4173 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004174 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004175 supertype.Get() == klass->GetSuperClass() ||
4176 !supertype->IsVerified());
4177
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004178 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004179 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004180 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004181 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004182
4183 VLOG(class_linker) << "Class preverified status for class "
4184 << klass->PrettyDescriptor()
4185 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4186 << ": "
4187 << preverified;
4188
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004189 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4190 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004191 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4192 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004193
Ian Rogers62d6c772013-02-27 08:32:07 -08004194 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004195 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004196 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004197 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004198 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004199
4200 // Verification is done, grab the lock again.
4201 ObjectLock<mirror::Class> lock(self, klass);
4202
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004203 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4204 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004205 VLOG(class_linker) << "Soft verification failure in class "
4206 << klass->PrettyDescriptor()
4207 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4208 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004209 }
Ian Rogers1f539342012-10-03 21:09:42 -07004210 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004211 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004212 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004213 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004214 // Even though there were no verifier failures we need to respect whether the super-class and
4215 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004216 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004217 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004218 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004219 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4220 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004221 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004222 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004223 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004224 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004225 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004226 // Soft failures at compile time should be retried at runtime. Soft
4227 // failures at runtime will be handled by slow paths in the generated
4228 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004229 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004230 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004231 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004232 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004233 // As this is a fake verified status, make sure the methods are _not_ marked
4234 // kAccSkipAccessChecks later.
4235 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004236 }
4237 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004238 } else {
David Sehr709b0702016-10-13 09:12:37 -07004239 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004240 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4241 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004242 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004243 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004244 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004245 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004246 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004247 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004248 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004249 // method.
4250 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004251 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004252 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004253
4254 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4255 // Never skip access checks if the verification soft fail is forced.
4256 // Mark the class as having a verification attempt to avoid re-running the verifier.
4257 klass->SetVerificationAttempted();
4258 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004259 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004260 }
Andreas Gampe48498592014-09-10 19:48:05 -07004261 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004262 // Done verifying. Notify the compiler about the verification status, in case the class
4263 // was verified implicitly (eg super class of a compiled class).
4264 if (Runtime::Current()->IsAotCompiler()) {
4265 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4266 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4267 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004268 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004269}
4270
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004271verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4272 Handle<mirror::Class> klass,
4273 verifier::HardFailLogMode log_level,
4274 std::string* error_msg) {
4275 Runtime* const runtime = Runtime::Current();
4276 return verifier::MethodVerifier::VerifyClass(self,
4277 klass.Get(),
4278 runtime->GetCompilerCallbacks(),
4279 runtime->IsAotCompiler(),
4280 log_level,
4281 error_msg);
4282}
4283
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004284bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004285 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004286 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004287 // If we're compiling, we can only verify the class using the oat file if
4288 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004289 // the compilation unit (app - dependencies). We will let the compiler callback
4290 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004291 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004292 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004293 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004294 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004295 return false;
4296 }
4297 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004298 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004299 return false;
4300 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004301 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004302
Richard Uhler07b3c232015-03-31 15:57:54 -07004303 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004304 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004305 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004306 return false;
4307 }
4308
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004309 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004310 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004311 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004312 return true;
4313 }
4314 // If we only verified a subset of the classes at compile time, we can end up with classes that
4315 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004316 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004317 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004318 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004319 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004320 // Compile time verification failed with a soft error. Compile time verification can fail
4321 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004322 // class ... {
4323 // Foo x;
4324 // .... () {
4325 // if (...) {
4326 // v1 gets assigned a type of resolved class Foo
4327 // } else {
4328 // v1 gets assigned a type of unresolved class Bar
4329 // }
4330 // iput x = v1
4331 // } }
4332 // when we merge v1 following the if-the-else it results in Conflict
4333 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4334 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4335 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4336 // at compile time).
4337 return false;
4338 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004339 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004340 // Compile time verification failed with a hard error. This is caused by invalid instructions
4341 // in the class. These errors are unrecoverable.
4342 return false;
4343 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004344 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004345 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4346 // not loading the class.
4347 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4348 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004349 return false;
4350 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004351 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004352 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004353 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004354 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004355 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004356}
4357
Alex Light5a559862016-01-29 12:24:48 -08004358void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004359 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004360 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004361 }
4362}
4363
Alex Light5a559862016-01-29 12:24:48 -08004364void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004365 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004366 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004367 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004368 return; // native or abstract method
4369 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004370 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004371 return; // nothing to process
4372 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004373 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004374 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004375 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4376 CatchHandlerIterator iterator(handlers_ptr);
4377 for (; iterator.HasNext(); iterator.Next()) {
4378 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4379 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004380 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004381 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004382 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004383 DCHECK(Thread::Current()->IsExceptionPending());
4384 Thread::Current()->ClearException();
4385 }
4386 }
4387 }
4388 handlers_ptr = iterator.EndDataPointer();
4389 }
4390}
4391
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004392mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4393 jstring name,
4394 jobjectArray interfaces,
4395 jobject loader,
4396 jobjectArray methods,
4397 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004398 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004399 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004400 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004401 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004402 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004403 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004404 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004405 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004406 DCHECK(temp_klass->GetClass() != nullptr);
4407 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004408 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4409 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004410 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4411 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4412 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4413 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004414 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004415 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004416 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004417 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004418 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004419 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004420
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004421 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004422 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004423
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004424 // Insert the class before loading the fields as the field roots
4425 // (ArtField::declaring_class_) are only visited from the class
4426 // table. There can't be any suspend points between inserting the
4427 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004428 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004429 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004430
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004431 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004432 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004433 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004434 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004435
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004436 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4437 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004438 ArtField& interfaces_sfield = sfields->At(0);
4439 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004440 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004441 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004442
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004443 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004444 ArtField& throws_sfield = sfields->At(1);
4445 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004446 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004447 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004448
Ian Rogers466bb252011-10-14 03:29:56 -07004449 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004450 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004451
Alex Lighte64300b2015-12-15 15:02:47 -08004452 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004453 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004454 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004455 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004456 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004457
4458 // Create the methods array.
4459 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4460 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004461 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4462 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004463 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004464 self->AssertPendingOOMException();
4465 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004466 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004467 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004468
4469 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004470 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004471
4472 // Create virtual method using specified prototypes.
4473 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004474 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004475 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004476 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004477 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004478 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4479 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004480 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004481
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004482 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004483 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004484 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004485 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004486 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004487
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004488 // At this point the class is loaded. Publish a ClassLoad event.
4489 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4490 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4491
4492 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004493 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004494 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004495 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004496 // Link the fields and virtual methods, creating vtable and iftables.
4497 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004498 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004499 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004500 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004501 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004502 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004503 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004504 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004505 CHECK(temp_klass->IsRetired());
4506 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004507
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004508 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004509 interfaces_sfield.SetObject<false>(
4510 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004511 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004512 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4513 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004514 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004515 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004516
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004517 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4518
Vladimir Marko305c38b2018-02-14 11:50:07 +00004519 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4520 // See also ClassLinker::EnsureInitialized().
4521 if (kBitstringSubtypeCheckEnabled) {
4522 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4523 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4524 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4525 }
4526
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004527 {
4528 // Lock on klass is released. Lock new class object.
4529 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004530 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004531 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004532
4533 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004534 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004535 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004536 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4537
Ian Rogersc2b44472011-12-14 21:17:17 -08004538 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004539 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4540 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004541 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004542 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004543
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004544 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004545 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004546 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004547 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004548 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004549
4550 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004551 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004552 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004553
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004554 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004555 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004556 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004557 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004558 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004559 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004560}
4561
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004562std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004563 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004564 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004565 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004566 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4567}
4568
Mathieu Chartiere401d142015-04-22 13:56:20 -07004569void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4570 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004571 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4572 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004573
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004574 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4575 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004576 ArtMethod* proxy_constructor = proxy_class->FindConstructor(
Vladimir Markoba118822017-06-12 15:41:56 +01004577 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004578 DCHECK(proxy_constructor != nullptr)
4579 << "Could not find <init> method in java.lang.reflect.Proxy";
4580
Jeff Haodb8a6642014-08-14 17:18:52 -07004581 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4582 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004583 DCHECK(out != nullptr);
4584 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004585 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004586 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004587 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004588 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4589 kAccPublic |
4590 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004591 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004592
4593 // Set the original constructor method.
4594 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004595}
4596
Mathieu Chartiere401d142015-04-22 13:56:20 -07004597void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004598 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004599 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4600 CHECK_STREQ(np->GetName(), "<init>");
4601 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004602 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004603}
4604
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004605void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004606 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004607 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004608 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004609 DCHECK(out != nullptr);
4610 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004611
Alex Lighte9dd04f2016-03-16 16:09:45 -07004612 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004613 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004614 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4615 // preference to the invocation handler.
4616 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4617 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004618 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4619 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004620 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4621
4622 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4623 // method they copy might (if it's a default method).
4624 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004625
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004626 // Set the original interface method.
4627 out->SetDataPtrSize(prototype, image_pointer_size_);
4628
Ian Rogers466bb252011-10-14 03:29:56 -07004629 // At runtime the method looks like a reference and argument saving method, clone the code
4630 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004631 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004632}
Jesse Wilson95caa792011-10-12 18:14:17 -04004633
Mathieu Chartiere401d142015-04-22 13:56:20 -07004634void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004635 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004636 CHECK(!prototype->IsFinal());
4637 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004638 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004639
4640 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4641 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004642 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004643 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004644}
4645
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004646bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004647 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004648 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004649 return true;
4650 }
4651 if (!can_init_statics) {
4652 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004653 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004654 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004655 return false;
4656 }
4657 // Check if there are encoded static values needing initialization.
4658 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004659 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004660 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004661 if (dex_class_def->static_values_off_ != 0) {
4662 return false;
4663 }
4664 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004665 // If we are a class we need to initialize all interfaces with default methods when we are
4666 // initialized. Check all of them.
4667 if (!klass->IsInterface()) {
4668 size_t num_interfaces = klass->GetIfTableCount();
4669 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004670 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004671 if (iface->HasDefaultMethods() &&
4672 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4673 return false;
4674 }
4675 }
4676 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004677 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004678 if (klass->IsInterface() || !klass->HasSuperClass()) {
4679 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004680 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004681 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004682 if (!can_init_parents && !super_class->IsInitialized()) {
4683 return false;
4684 }
4685 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004686}
4687
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004688bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4689 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004690 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4691
4692 // Are we already initialized and therefore done?
4693 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4694 // an initialized class will never change its state.
4695 if (klass->IsInitialized()) {
4696 return true;
4697 }
4698
4699 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004700 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004701 return false;
4702 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004703
Ian Rogers7b078e82014-09-10 14:44:24 -07004704 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004705 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004706 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004707 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004709 // Re-check under the lock in case another thread initialized ahead of us.
4710 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004711 return true;
4712 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004713
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004714 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004715 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004716 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004717 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004718 return false;
4719 }
4720
Vladimir Marko72ab6842017-01-20 19:32:50 +00004721 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4722 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004723
4724 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004725 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004726 if (!klass->IsVerified()) {
4727 // We failed to verify, expect either the klass to be erroneous or verification failed at
4728 // compile time.
4729 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004730 // The class is erroneous. This may be a verifier error, or another thread attempted
4731 // verification and/or initialization and failed. We can distinguish those cases by
4732 // whether an exception is already pending.
4733 if (self->IsExceptionPending()) {
4734 // Check that it's a VerifyError.
4735 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004736 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004737 } else {
4738 // Check that another thread attempted initialization.
4739 DCHECK_NE(0, klass->GetClinitThreadId());
4740 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4741 // Need to rethrow the previous failure now.
4742 ThrowEarlierClassFailure(klass.Get(), true);
4743 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004744 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004745 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004746 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004747 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004748 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004749 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004750 } else {
4751 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004752 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004753
4754 // A separate thread could have moved us all the way to initialized. A "simple" example
4755 // involves a subclass of the current class being initialized at the same time (which
4756 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004757 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004758 if (klass->IsInitialized()) {
4759 return true;
4760 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004761 }
4762
Vladimir Marko2c64a832018-01-04 11:31:56 +00004763 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07004764 // initializing higher up the stack or another thread has beat us
4765 // to initializing and we need to wait. Either way, this
4766 // invocation of InitializeClass will not be responsible for
4767 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004768 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004769 // Could have got an exception during verification.
4770 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004771 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004772 return false;
4773 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004774 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004775 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004776 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004777 return true;
4778 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004779 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004780 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004781 }
4782
Jeff Haoe2e40342017-07-19 10:45:18 -07004783 // Try to get the oat class's status for this class if the oat file is present. The compiler
4784 // tries to validate superclass descriptors, and writes the result into the oat file.
4785 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4786 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4787 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004788 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004789 const Runtime* runtime = Runtime::Current();
4790 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4791 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4792 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004793 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07004794 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004795 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004796 return false;
4797 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004798 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004799
Vladimir Marko2c64a832018-01-04 11:31:56 +00004800 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004801 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004802
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004803 // From here out other threads may observe that we're initializing and so changes of state
4804 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004805 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004806 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004807
4808 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004809 }
4810
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004811 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004812 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004813 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004814 if (!super_class->IsInitialized()) {
4815 CHECK(!super_class->IsInterface());
4816 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004817 StackHandleScope<1> hs(self);
4818 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004819 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004820 if (!super_initialized) {
4821 // The super class was verified ahead of entering initializing, we should only be here if
4822 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004823 // For the case of aot compiler, the super class might also be initializing but we don't
4824 // want to process circular dependencies in pre-compile.
4825 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004826 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004827 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004828 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004829 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004830 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004831 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004832 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004833 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004834 return false;
4835 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004836 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004837 }
4838
Alex Lighteb7c1442015-08-31 13:17:42 -07004839 if (!klass->IsInterface()) {
4840 // Initialize interfaces with default methods for the JLS.
4841 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004842 // Only setup the (expensive) handle scope if we actually need to.
4843 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004844 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004845 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4846 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004847 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004848 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004849 CHECK(handle_scope_iface->IsInterface());
4850 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4851 // We have already done this for this interface. Skip it.
4852 continue;
4853 }
4854 // We cannot just call initialize class directly because we need to ensure that ALL
4855 // interfaces with default methods are initialized. Non-default interface initialization
4856 // will not affect other non-default super-interfaces.
4857 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4858 handle_scope_iface,
4859 can_init_statics,
4860 can_init_parents);
4861 if (!iface_initialized) {
4862 ObjectLock<mirror::Class> lock(self, klass);
4863 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004864 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004865 return false;
4866 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004867 }
4868 }
4869 }
4870
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004871 const size_t num_static_fields = klass->NumStaticFields();
4872 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004873 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004874 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004875 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004876 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004877 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004878
4879 // Eagerly fill in static fields so that the we don't have to do as many expensive
4880 // Class::FindStaticField in ResolveField.
4881 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004882 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004883 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004884 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004885 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01004886 // Populating cache of a dex file which defines `klass` should always be allowed.
4887 DCHECK_EQ(hiddenapi::GetMemberAction(
4888 field, class_loader.Get(), dex_cache.Get(), hiddenapi::kNone), hiddenapi::kAllow);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004889 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004890 } else {
4891 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004892 }
4893 }
4894
Vladimir Markoe11dd502017-12-08 14:09:45 +00004895 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
4896 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07004897 this,
4898 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00004899 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers13735952014-10-08 12:43:28 -07004900 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004901 ClassDataItemIterator field_it(dex_file, class_data);
4902 if (value_it.HasNext()) {
4903 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004904 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004905 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004906 ArtField* field = ResolveField(
Vladimir Markoe11dd502017-12-08 14:09:45 +00004907 field_it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004908 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004909 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004910 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004911 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004912 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004913 if (self->IsExceptionPending()) {
4914 break;
4915 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004916 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004917 }
4918 }
4919 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004920
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004921
Mathieu Chartierda595be2016-08-10 13:57:39 -07004922 if (!self->IsExceptionPending()) {
4923 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4924 if (clinit != nullptr) {
4925 CHECK(can_init_statics);
4926 JValue result;
4927 clinit->Invoke(self, nullptr, 0, &result, "V");
4928 }
4929 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004930 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004931 uint64_t t1 = NanoTime();
4932
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004933 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004934 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004935 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004936
4937 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004938 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004939 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004940 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004941 } else if (Runtime::Current()->IsTransactionAborted()) {
4942 // The exception thrown when the transaction aborted has been caught and cleared
4943 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004944 VLOG(compiler) << "Return from class initializer of "
4945 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004946 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004947 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004948 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004949 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004950 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004951 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4952 RuntimeStats* thread_stats = self->GetStats();
4953 ++global_stats->class_init_count;
4954 ++thread_stats->class_init_count;
4955 global_stats->class_init_time_ns += (t1 - t0);
4956 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004957 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004958 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004959 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004960 std::string temp;
4961 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004962 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004963 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004964 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004965 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004966 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004967 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004968 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004969}
4970
Alex Lighteb7c1442015-08-31 13:17:42 -07004971// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4972// and perform the initialization only on those interfaces that contain default methods.
4973bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4974 Handle<mirror::Class> iface,
4975 bool can_init_statics,
4976 bool can_init_parents) {
4977 CHECK(iface->IsInterface());
4978 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004979 // Only create the (expensive) handle scope if we need it.
4980 if (UNLIKELY(num_direct_ifaces > 0)) {
4981 StackHandleScope<1> hs(self);
4982 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4983 // First we initialize all of iface's super-interfaces recursively.
4984 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004985 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004986 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004987 if (!super_iface->HasBeenRecursivelyInitialized()) {
4988 // Recursive step
4989 handle_super_iface.Assign(super_iface);
4990 if (!InitializeDefaultInterfaceRecursive(self,
4991 handle_super_iface,
4992 can_init_statics,
4993 can_init_parents)) {
4994 return false;
4995 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004996 }
4997 }
4998 }
4999
5000 bool result = true;
5001 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5002 // initialize if we don't have default methods.
5003 if (iface->HasDefaultMethods()) {
5004 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5005 }
5006
5007 // Mark that this interface has undergone recursive default interface initialization so we know we
5008 // can skip it on any later class initializations. We do this even if we are not a default
5009 // interface since we can still avoid the traversal. This is purely a performance optimization.
5010 if (result) {
5011 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005012 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5013 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5014 // initialization is a performance optimization (to avoid another idempotent visit
5015 // for other implementing classes/interfaces), and can be revisited later.
5016 ObjectTryLock<mirror::Class> lock(self, iface);
5017 if (lock.Acquired()) {
5018 iface->SetRecursivelyInitialized();
5019 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005020 }
5021 return result;
5022}
5023
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005024bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5025 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005026 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005027 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005028 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005029 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005030 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005031 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005032
5033 // When we wake up, repeat the test for init-in-progress. If
5034 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005035 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005036 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005037 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005038 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005039 return false;
5040 }
5041 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005042 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005043 continue;
5044 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005045 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005046 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005047 // Compile time initialization failed.
5048 return false;
5049 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005050 if (klass->IsErroneous()) {
5051 // The caller wants an exception, but it was thrown in a
5052 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005053 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005054 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005055 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005056 return false;
5057 }
5058 if (klass->IsInitialized()) {
5059 return true;
5060 }
David Sehr709b0702016-10-13 09:12:37 -07005061 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005062 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005063 }
Ian Rogers07140832014-09-30 15:43:59 -07005064 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005065}
5066
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005067static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5068 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005069 ArtMethod* method,
5070 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005071 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005072 DCHECK(Thread::Current()->IsExceptionPending());
5073 DCHECK(!m->IsProxyMethod());
5074 const DexFile* dex_file = m->GetDexFile();
5075 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5076 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005077 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005078 std::string return_type = dex_file->PrettyType(return_type_idx);
5079 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005080 ThrowWrappedLinkageError(klass.Get(),
5081 "While checking class %s method %s signature against %s %s: "
5082 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005083 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5084 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005085 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005086 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005087 return_type.c_str(), class_loader.c_str());
5088}
5089
5090static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5091 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005092 ArtMethod* method,
5093 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005094 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005095 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005096 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005097 DCHECK(Thread::Current()->IsExceptionPending());
5098 DCHECK(!m->IsProxyMethod());
5099 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005100 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5101 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005102 ThrowWrappedLinkageError(klass.Get(),
5103 "While checking class %s method %s signature against %s %s: "
5104 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005105 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5106 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005107 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005108 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005109 index, arg_type.c_str(), class_loader.c_str());
5110}
5111
5112static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5113 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005114 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005115 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005116 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005117 ThrowLinkageError(klass.Get(),
5118 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005119 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5120 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005121 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005122 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005123 error_msg.c_str());
5124}
5125
Ian Rogersb5fb2072014-12-02 17:22:02 -08005126static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005127 Handle<mirror::Class> klass,
5128 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005129 ArtMethod* method1,
5130 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005131 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005132 {
5133 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005134 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005135 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005136 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005137 return false;
5138 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005139 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005140 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005141 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005142 return false;
5143 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005144 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005145 ThrowSignatureMismatch(klass, super_klass, method1,
5146 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005147 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005148 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005149 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005150 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005151 return false;
5152 }
5153 }
5154 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5155 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5156 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005157 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005158 ThrowSignatureMismatch(klass, super_klass, method1,
5159 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005160 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005161 return false;
5162 }
5163 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005164 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005165 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005166 ThrowSignatureMismatch(klass, super_klass, method1,
5167 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005168 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005169 return false;
5170 }
5171 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005172 }
5173 uint32_t num_types = types1->Size();
5174 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005175 ThrowSignatureMismatch(klass, super_klass, method1,
5176 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005177 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005178 return false;
5179 }
5180 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005181 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005182 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005183 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005184 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005185 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005186 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005187 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005188 return false;
5189 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005190 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005191 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005192 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005193 if (UNLIKELY(other_param_type == nullptr)) {
5194 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005195 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005196 return false;
5197 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005198 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005199 ThrowSignatureMismatch(klass, super_klass, method1,
5200 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5201 i,
David Sehr709b0702016-10-13 09:12:37 -07005202 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005203 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005204 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005205 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005206 return false;
5207 }
5208 }
5209 return true;
5210}
5211
5212
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005213bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005214 if (klass->IsInterface()) {
5215 return true;
5216 }
Ian Rogers151f2212014-05-06 11:27:27 -07005217 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005218 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005219 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005220 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005221 if (klass->HasSuperClass() &&
5222 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005223 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005224 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005225 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5226 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5227 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005228 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5229 klass,
5230 super_klass,
5231 m,
5232 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005233 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005234 return false;
5235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005236 }
5237 }
5238 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005239 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005240 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5241 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5242 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005243 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005244 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5245 j, image_pointer_size_);
5246 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5247 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005248 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5249 klass,
5250 super_klass,
5251 m,
5252 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005253 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005254 return false;
5255 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005256 }
5257 }
5258 }
5259 }
5260 return true;
5261}
5262
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005263bool ClassLinker::EnsureInitialized(Thread* self,
5264 Handle<mirror::Class> c,
5265 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005266 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005267 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005268
Mathieu Chartier524507a2014-08-27 15:28:28 -07005269 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005270 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005271 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005272 return true;
5273 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005274 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5275 //
5276 // Ensure the bitstring is initialized before any of the class initialization
5277 // logic occurs. Once a class initializer starts running, objects can
5278 // escape into the heap and use the subtype checking code.
5279 //
5280 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5281 // can be used as a source for the IsSubClass check, and that all ancestors
5282 // of the class are Assigned (can be used as a target for IsSubClass check)
5283 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005284 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005285 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005286 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005287 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5288 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005289 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005290 if (!success) {
5291 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005292 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005293 }
5294 } else {
5295 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005296 }
5297 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005298}
5299
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005300void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5301 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005302 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005303 for (ArtField& field : new_class->GetIFields()) {
5304 if (field.GetDeclaringClass() == temp_class) {
5305 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005306 }
5307 }
5308
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005309 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005310 for (ArtField& field : new_class->GetSFields()) {
5311 if (field.GetDeclaringClass() == temp_class) {
5312 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005313 }
5314 }
5315
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005316 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005317 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005318 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005319 if (method.GetDeclaringClass() == temp_class) {
5320 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005321 }
5322 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005323
5324 // Make sure the remembered set and mod-union tables know that we updated some of the native
5325 // roots.
5326 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005327}
5328
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005329void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005330 CHECK(class_loader->GetAllocator() == nullptr);
5331 CHECK(class_loader->GetClassTable() == nullptr);
5332 Thread* const self = Thread::Current();
5333 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005334 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005335 // Create and set the class table.
5336 data.class_table = new ClassTable;
5337 class_loader->SetClassTable(data.class_table);
5338 // Create and set the linear allocator.
5339 data.allocator = Runtime::Current()->CreateLinearAlloc();
5340 class_loader->SetAllocator(data.allocator);
5341 // Add to the list so that we know to free the data later.
5342 class_loaders_.push_back(data);
5343}
5344
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005345ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005346 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005347 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005348 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005349 ClassTable* class_table = class_loader->GetClassTable();
5350 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005351 RegisterClassLoader(class_loader);
5352 class_table = class_loader->GetClassTable();
5353 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005354 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005355 return class_table;
5356}
5357
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005358ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005359 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005360}
5361
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005362static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005363 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005364 while (klass->HasSuperClass()) {
5365 klass = klass->GetSuperClass();
5366 if (klass->ShouldHaveImt()) {
5367 return klass->GetImt(pointer_size);
5368 }
5369 }
5370 return nullptr;
5371}
5372
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005373bool ClassLinker::LinkClass(Thread* self,
5374 const char* descriptor,
5375 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005376 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005377 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005378 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005379
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005380 if (!LinkSuperClass(klass)) {
5381 return false;
5382 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005383 ArtMethod* imt_data[ImTable::kSize];
5384 // If there are any new conflicts compared to super class.
5385 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005386 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005387 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005388 return false;
5389 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005390 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005391 return false;
5392 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005393 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005394 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005395 return false;
5396 }
5397 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005398 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005399
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005400 ImTable* imt = nullptr;
5401 if (klass->ShouldHaveImt()) {
5402 // If there are any new conflicts compared to the super class we can not make a copy. There
5403 // can be cases where both will have a conflict method at the same slot without having the same
5404 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5405 // will possibly create a table that is incorrect for either of the classes.
5406 // Same IMT with new_conflict does not happen very often.
5407 if (!new_conflict) {
5408 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5409 if (super_imt != nullptr) {
5410 bool imt_equals = true;
5411 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5412 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5413 }
5414 if (imt_equals) {
5415 imt = super_imt;
5416 }
5417 }
5418 }
5419 if (imt == nullptr) {
5420 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5421 imt = reinterpret_cast<ImTable*>(
5422 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5423 if (imt == nullptr) {
5424 return false;
5425 }
5426 imt->Populate(imt_data, image_pointer_size_);
5427 }
5428 }
5429
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005430 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5431 // We don't need to retire this class as it has no embedded tables or it was created the
5432 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005433 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005434
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005435 if (klass->ShouldHaveEmbeddedVTable()) {
5436 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005437 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005438 if (klass->ShouldHaveImt()) {
5439 klass->SetImt(imt, image_pointer_size_);
5440 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005441
5442 // Update CHA info based on whether we override methods.
5443 // Have to do this before setting the class as resolved which allows
5444 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005445 if (cha_ != nullptr) {
5446 cha_->UpdateAfterLoadingOf(klass);
5447 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005448
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005449 // This will notify waiters on klass that saw the not yet resolved
5450 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005451 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005452 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005453 } else {
5454 CHECK(!klass->IsResolved());
5455 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005456 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005457 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005458 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5459 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5460 // may not see any references to the target space and clean the card for a class if another
5461 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005462 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005463 klass->SetSFieldsPtrUnchecked(nullptr);
5464 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005465 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005466 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005467 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005468 return false;
5469 }
5470
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005471 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5472 ObjectLock<mirror::Class> lock(self, h_new_class);
5473 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005474
5475 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005476 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005477 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005478 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005479 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005480 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005481 if (class_loader != nullptr) {
5482 // We updated the class in the class table, perform the write barrier so that the GC knows
5483 // about the change.
5484 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5485 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005486 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005487 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005488 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5489 }
5490 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005491
Mingyao Yang063fc772016-08-02 11:02:54 -07005492 // Update CHA info based on whether we override methods.
5493 // Have to do this before setting the class as resolved which allows
5494 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005495 if (cha_ != nullptr) {
5496 cha_->UpdateAfterLoadingOf(h_new_class);
5497 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005498
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005499 // This will notify waiters on temp class that saw the not yet resolved class in the
5500 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005501 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005502
Vladimir Marko2c64a832018-01-04 11:31:56 +00005503 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005504 // This will notify waiters on new_class that saw the not yet resolved
5505 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005506 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005507 // Return the new class.
5508 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005509 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005510 return true;
5511}
5512
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005513bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005514 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005515 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005516 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5517 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005518 // Check that a class does not inherit from itself directly.
5519 //
5520 // TODO: This is a cheap check to detect the straightforward case
5521 // of a class extending itself (b/28685551), but we should do a
5522 // proper cycle detection on loaded classes, to detect all cases
5523 // of class circularity errors (b/28830038).
5524 if (super_class_idx == class_def.class_idx_) {
5525 ThrowClassCircularityError(klass.Get(),
5526 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005527 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005528 return false;
5529 }
5530
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005531 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005532 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005533 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005534 return false;
5535 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005536 // Verify
5537 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005538 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005539 super_class->PrettyDescriptor().c_str(),
5540 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005541 return false;
5542 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005543 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005544 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005545 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005546 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005547 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005548 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005549 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005550 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005551 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005552 DCHECK(Thread::Current()->IsExceptionPending());
5553 return false;
5554 }
5555 // Verify
5556 if (!klass->CanAccess(interface)) {
5557 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005558 ThrowIllegalAccessError(klass.Get(),
5559 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005560 interface->PrettyDescriptor().c_str(),
5561 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005562 return false;
5563 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005564 }
5565 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005566 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005567 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005568 return true;
5569}
5570
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005571bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005572 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005573 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005574 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5575 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005576 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005577 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005578 return false;
5579 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005580 return true;
5581 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005582 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005583 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005584 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005585 return false;
5586 }
5587 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005588 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005589 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5590 return false;
5591 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005592 if (super->IsFinal()) {
5593 ThrowVerifyError(klass.Get(),
5594 "Superclass %s of %s is declared final",
5595 super->PrettyDescriptor().c_str(),
5596 klass->PrettyDescriptor().c_str());
5597 return false;
5598 }
5599 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005600 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005601 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005602 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005603 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005604 return false;
5605 }
5606 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005607 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005608 super->PrettyDescriptor().c_str(),
5609 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005610 return false;
5611 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005612
Brian Carlstromf3632832014-05-20 15:36:53 -07005613 // Inherit kAccClassIsFinalizable from the superclass in case this
5614 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005615 if (super->IsFinalizable()) {
5616 klass->SetFinalizable();
5617 }
5618
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005619 // Inherit class loader flag form super class.
5620 if (super->IsClassLoaderClass()) {
5621 klass->SetClassLoaderClass();
5622 }
5623
Elliott Hughes2da50362011-10-10 16:57:08 -07005624 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005625 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005626 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005627 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005628 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005629 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005630 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005631 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005632 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005633 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005634 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005635 return false;
5636 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005637
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005638 if (kIsDebugBuild) {
5639 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005640 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005641 CHECK(super->IsResolved());
5642 super = super->GetSuperClass();
5643 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005644 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005645 return true;
5646}
5647
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005648// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005649bool ClassLinker::LinkMethods(Thread* self,
5650 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005651 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005652 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005653 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005654 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005655 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5656 // need to have default methods be in the virtuals array of each class but we don't set that up
5657 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005658 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005659 // Link virtual methods then interface methods.
5660 // We set up the interface lookup table first because we need it to determine if we need to update
5661 // any vtable entries with new default method implementations.
5662 return SetupInterfaceLookupTable(self, klass, interfaces)
5663 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005664 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005665}
5666
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005667// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5668// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5669// caches in the implementation below.
5670class MethodNameAndSignatureComparator FINAL : public ValueObject {
5671 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005672 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005673 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005674 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5675 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005676 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005677 }
5678
5679 const char* GetName() {
5680 if (name_ == nullptr) {
5681 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5682 }
5683 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005684 }
5685
Mathieu Chartiere401d142015-04-22 13:56:20 -07005686 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005687 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005688 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005689 const DexFile* other_dex_file = other->GetDexFile();
5690 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5691 if (dex_file_ == other_dex_file) {
5692 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5693 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005694 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005695 uint32_t other_name_len;
5696 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5697 &other_name_len);
5698 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5699 return false;
5700 }
5701 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5702 }
5703
5704 private:
5705 // Dex file for the method to compare against.
5706 const DexFile* const dex_file_;
5707 // MethodId for the method to compare against.
5708 const DexFile::MethodId* const mid_;
5709 // Lazily computed name from the dex file's strings.
5710 const char* name_;
5711 // Lazily computed name length.
5712 uint32_t name_len_;
5713};
5714
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005715class LinkVirtualHashTable {
5716 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005717 LinkVirtualHashTable(Handle<mirror::Class> klass,
5718 size_t hash_size,
5719 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005720 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005721 : klass_(klass),
5722 hash_size_(hash_size),
5723 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005724 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005725 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5726 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005727
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005728 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005729 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5730 virtual_method_index, image_pointer_size_);
5731 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005732 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005733 uint32_t index = hash % hash_size_;
5734 // Linear probe until we have an empty slot.
5735 while (hash_table_[index] != invalid_index_) {
5736 if (++index == hash_size_) {
5737 index = 0;
5738 }
5739 }
5740 hash_table_[index] = virtual_method_index;
5741 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005742
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005743 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005744 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005745 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005746 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005747 size_t index = hash % hash_size_;
5748 while (true) {
5749 const uint32_t value = hash_table_[index];
5750 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5751 // the block and can safely assume not found.
5752 if (value == invalid_index_) {
5753 break;
5754 }
5755 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005756 ArtMethod* virtual_method =
5757 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5758 if (comparator->HasSameNameAndSignature(
5759 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005760 hash_table_[index] = removed_index_;
5761 return value;
5762 }
5763 }
5764 if (++index == hash_size_) {
5765 index = 0;
5766 }
5767 }
5768 return GetNotFoundIndex();
5769 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005770
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005771 static uint32_t GetNotFoundIndex() {
5772 return invalid_index_;
5773 }
5774
5775 private:
5776 static const uint32_t invalid_index_;
5777 static const uint32_t removed_index_;
5778
5779 Handle<mirror::Class> klass_;
5780 const size_t hash_size_;
5781 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005782 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005783};
5784
5785const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5786const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5787
Stephen Hines1ddd9132017-02-08 01:51:18 -08005788bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005789 Thread* self,
5790 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005791 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005792 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005793 if (klass->IsInterface()) {
5794 // No vtable.
5795 if (!IsUint<16>(num_virtual_methods)) {
5796 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5797 return false;
5798 }
5799 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005800 // Assign each method an IMT index and set the default flag.
5801 for (size_t i = 0; i < num_virtual_methods; ++i) {
5802 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5803 m->SetMethodIndex(i);
5804 if (!m->IsAbstract()) {
5805 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5806 has_defaults = true;
5807 }
5808 }
5809 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5810 // during initialization. This is a performance optimization. We could simply traverse the
5811 // virtual_methods_ array again during initialization.
5812 if (has_defaults) {
5813 klass->SetHasDefaultMethods();
5814 }
5815 return true;
5816 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005817 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5818 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005819 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005820 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005821 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005822 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005823 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005824 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005825 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005826 return false;
5827 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005828 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005829 vtable->SetElementPtrSize(
5830 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005831 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005832 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5833 // might give us new default methods). If no new interfaces then we can skip the rest since
5834 // the class cannot override any of the super-class's methods. This is required for
5835 // correctness since without it we might not update overridden default method vtable entries
5836 // correctly.
5837 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005838 klass->SetVTable(vtable.Get());
5839 return true;
5840 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005841 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005842 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005843 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005844 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005845 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5846 // might give us new default methods). See comment above.
5847 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005848 klass->SetVTable(super_vtable);
5849 return true;
5850 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005851 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5852 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005853 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005854 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005855 return false;
5856 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005857 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005858 // How the algorithm works:
5859 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5860 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5861 // method which has not been matched to a vtable method, and j if the virtual method at the
5862 // index overrode the super virtual method at index j.
5863 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5864 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5865 // the need for the initial vtable which we later shrink back down).
5866 // 3. Add non overridden methods to the end of the vtable.
5867 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005868 // + 1 so that even if we only have new default methods we will still be able to use this hash
5869 // table (i.e. it will never have 0 size).
5870 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005871 uint32_t* hash_table_ptr;
5872 std::unique_ptr<uint32_t[]> hash_heap_storage;
5873 if (hash_table_size <= kMaxStackHash) {
5874 hash_table_ptr = reinterpret_cast<uint32_t*>(
5875 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5876 } else {
5877 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5878 hash_table_ptr = hash_heap_storage.get();
5879 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005880 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005881 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005882 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005883 DCHECK(klass->GetVirtualMethodDuringLinking(
5884 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005885 hash_table.Add(i);
5886 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005887 // 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 -07005888 // the hash table.
5889 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005890 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005891 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005892 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5893 super_method->GetAccessFlags())) {
5894 // Continue on to the next method since this one is package private and canot be overridden.
5895 // Before Android 4.1, the package-private method super_method might have been incorrectly
5896 // overridden.
5897 continue;
5898 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005899 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005900 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005901 // We remove the method so that subsequent lookups will be faster by making the hash-map
5902 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005903 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5904 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005905 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5906 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005907 if (super_method->IsFinal()) {
5908 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5909 virtual_method->PrettyMethod().c_str(),
5910 super_method->GetDeclaringClassDescriptor());
5911 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005912 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005913 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5914 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005915 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005916 // We didn't directly override this method but we might through default methods...
5917 // Check for default method update.
5918 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005919 switch (FindDefaultMethodImplementation(self,
5920 super_method,
5921 klass,
5922 /*out*/&default_method)) {
5923 case DefaultMethodSearchResult::kDefaultConflict: {
5924 // A conflict was found looking for default methods. Note this (assuming it wasn't
5925 // pre-existing) in the translations map.
5926 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5927 // Don't generate another conflict method to reduce memory use as an optimization.
5928 default_translations->insert(
5929 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5930 }
5931 break;
5932 }
5933 case DefaultMethodSearchResult::kAbstractFound: {
5934 // No conflict but method is abstract.
5935 // We note that this vtable entry must be made abstract.
5936 if (UNLIKELY(!super_method->IsAbstract())) {
5937 default_translations->insert(
5938 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5939 }
5940 break;
5941 }
5942 case DefaultMethodSearchResult::kDefaultFound: {
5943 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5944 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5945 // Found a default method implementation that is new.
5946 // TODO Refactor this add default methods to virtuals here and not in
5947 // LinkInterfaceMethods maybe.
5948 // The problem is default methods might override previously present
5949 // default-method or miranda-method vtable entries from the superclass.
5950 // Unfortunately we need these to be entries in this class's virtuals. We do not
5951 // give these entries there until LinkInterfaceMethods so we pass this map around
5952 // to let it know which vtable entries need to be updated.
5953 // Make a note that vtable entry j must be updated, store what it needs to be updated
5954 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5955 // then.
5956 default_translations->insert(
5957 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005958 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5959 << " overridden by default "
5960 << default_method->PrettyMethod()
5961 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005962 }
5963 break;
5964 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005965 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005966 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005967 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005968 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005969 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005970 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005971 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005972 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5973 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005974 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005975 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005976 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005977 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005978 local_method->SetMethodIndex(actual_count);
5979 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005980 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005981 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005982 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005983 return false;
5984 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005985 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005986 CHECK_LE(actual_count, max_count);
5987 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005988 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005989 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005990 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005991 return false;
5992 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005993 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005994 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005995 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005996 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005997 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005998 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5999 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006000 return false;
6001 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006002 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006003 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006004 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006005 return false;
6006 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006007 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006008 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6009 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006010 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006011 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006012 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006013 }
6014 return true;
6015}
6016
Alex Light9139e002015-10-09 15:59:48 -07006017// Determine if the given iface has any subinterface in the given list that declares the method
6018// specified by 'target'.
6019//
6020// Arguments
6021// - self: The thread we are running on
6022// - target: A comparator that will match any method that overrides the method we are checking for
6023// - iftable: The iftable we are searching for an overriding method on.
6024// - ifstart: The index of the interface we are checking to see if anything overrides
6025// - iface: The interface we are checking to see if anything overrides.
6026// - image_pointer_size:
6027// The image pointer size.
6028//
6029// Returns
6030// - True: There is some method that matches the target comparator defined in an interface that
6031// is a subtype of iface.
6032// - False: There is no method that matches the target comparator in any interface that is a subtype
6033// of iface.
6034static bool ContainsOverridingMethodOf(Thread* self,
6035 MethodNameAndSignatureComparator& target,
6036 Handle<mirror::IfTable> iftable,
6037 size_t ifstart,
6038 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006039 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006040 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006041 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006042 DCHECK(iface != nullptr);
6043 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006044 DCHECK_GE(ifstart, 0u);
6045 DCHECK_LT(ifstart, iftable->Count());
6046 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6047 DCHECK(iface->IsInterface());
6048
6049 size_t iftable_count = iftable->Count();
6050 StackHandleScope<1> hs(self);
6051 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6052 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6053 // Skip ifstart since our current interface obviously cannot override itself.
6054 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006055 // Iterate through every method on this interface. The order does not matter.
6056 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006057 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006058 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006059 // Check if the i'th interface is a subtype of this one.
6060 if (iface->IsAssignableFrom(current_iface.Get())) {
6061 return true;
6062 }
6063 break;
6064 }
6065 }
6066 }
6067 return false;
6068}
6069
Alex Lighteb7c1442015-08-31 13:17:42 -07006070// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006071// out_default_method and returns kDefaultFound on success. If no default method was found return
6072// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6073// default_method conflict) it will return kDefaultConflict.
6074ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6075 Thread* self,
6076 ArtMethod* target_method,
6077 Handle<mirror::Class> klass,
6078 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006079 DCHECK(self != nullptr);
6080 DCHECK(target_method != nullptr);
6081 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006082
6083 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006084
6085 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6086 // table. This lets us walk the table backwards when searching for default methods. The first one
6087 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6088 // track of it and then continue checking all other interfaces, since we need to throw an error if
6089 // we encounter conflicting default method implementations (one is not a subtype of the other).
6090 //
6091 // The order of unrelated interfaces does not matter and is not defined.
6092 size_t iftable_count = klass->GetIfTableCount();
6093 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006094 // No interfaces. We have already reset out to null so just return kAbstractFound.
6095 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006096 }
6097
Alex Light9139e002015-10-09 15:59:48 -07006098 StackHandleScope<3> hs(self);
6099 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006100 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006101 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006102 MethodNameAndSignatureComparator target_name_comparator(
6103 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6104 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006105 for (size_t k = iftable_count; k != 0; ) {
6106 --k;
6107
Alex Lighteb7c1442015-08-31 13:17:42 -07006108 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006109
6110 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006111 // Iterate through every declared method on this interface. The order does not matter.
6112 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6113 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006114 // Skip abstract methods and methods with different names.
6115 if (current_method->IsAbstract() ||
6116 !target_name_comparator.HasSameNameAndSignature(
6117 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6118 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006119 } else if (!current_method->IsPublic()) {
6120 // The verifier should have caught the non-public method for dex version 37. Just warn and
6121 // skip it since this is from before default-methods so we don't really need to care that it
6122 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006123 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6124 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006125 << "This will be a fatal error in subsequent versions of android. "
6126 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006127 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006128 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006129 // We have multiple default impls of the same method. This is a potential default conflict.
6130 // We need to check if this possibly conflicting method is either a superclass of the chosen
6131 // default implementation or is overridden by a non-default interface method. In either case
6132 // there is no conflict.
6133 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6134 !ContainsOverridingMethodOf(self,
6135 target_name_comparator,
6136 iftable,
6137 k,
6138 iface,
6139 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006140 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006141 << current_method->PrettyMethod() << " and "
6142 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6143 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006144 *out_default_method = nullptr;
6145 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006146 } else {
6147 break; // Continue checking at the next interface.
6148 }
6149 } else {
Alex Light9139e002015-10-09 15:59:48 -07006150 // chosen_iface == null
6151 if (!ContainsOverridingMethodOf(self,
6152 target_name_comparator,
6153 iftable,
6154 k,
6155 iface,
6156 image_pointer_size_)) {
6157 // Don't set this as the chosen interface if something else is overriding it (because that
6158 // other interface would be potentially chosen instead if it was default). If the other
6159 // interface was abstract then we wouldn't select this interface as chosen anyway since
6160 // the abstract method masks it.
6161 *out_default_method = current_method;
6162 chosen_iface.Assign(iface.Get());
6163 // We should now finish traversing the graph to find if we have default methods that
6164 // conflict.
6165 } else {
David Sehr709b0702016-10-13 09:12:37 -07006166 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6167 << "' was "
6168 << "skipped because it was overridden by an abstract method in a "
6169 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006170 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006171 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006172 break;
6173 }
6174 }
Alex Light9139e002015-10-09 15:59:48 -07006175 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006176 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6177 << "' selected "
6178 << "as the implementation for '" << target_method->PrettyMethod()
6179 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006180 return DefaultMethodSearchResult::kDefaultFound;
6181 } else {
6182 return DefaultMethodSearchResult::kAbstractFound;
6183 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006184}
6185
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006186ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006187 ArtMethod* conflict_method,
6188 ArtMethod* interface_method,
6189 ArtMethod* method,
6190 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006191 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006192 Runtime* const runtime = Runtime::Current();
6193 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6194 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6195
6196 // Create a new entry if the existing one is the shared conflict method.
6197 ArtMethod* new_conflict_method = new_entry
6198 ? runtime->CreateImtConflictMethod(linear_alloc)
6199 : conflict_method;
6200
6201 // Allocate a new table. Note that we will leak this table at the next conflict,
6202 // but that's a tradeoff compared to making the table fixed size.
6203 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006204 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6205 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006206 if (data == nullptr) {
6207 LOG(ERROR) << "Failed to allocate conflict table";
6208 return conflict_method;
6209 }
6210 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6211 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006212 method,
6213 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006214
6215 // Do a fence to ensure threads see the data in the table before it is assigned
6216 // to the conflict method.
6217 // Note that there is a race in the presence of multiple threads and we may leak
6218 // memory from the LinearAlloc, but that's a tradeoff compared to using
6219 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006220 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006221 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006222 return new_conflict_method;
6223}
6224
Vladimir Marko921094a2017-01-12 18:37:06 +00006225bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6226 Handle<mirror::Class> klass,
6227 Handle<mirror::IfTable> iftable) {
6228 DCHECK(!klass->IsInterface());
6229 const bool has_superclass = klass->HasSuperClass();
6230 const bool extend_super_iftable = has_superclass;
6231 const size_t ifcount = klass->GetIfTableCount();
6232 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6233 for (size_t i = 0; i < ifcount; ++i) {
6234 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6235 if (num_methods > 0) {
6236 const bool is_super = i < super_ifcount;
6237 // This is an interface implemented by a super-class. Therefore we can just copy the method
6238 // array from the superclass.
6239 const bool super_interface = is_super && extend_super_iftable;
6240 ObjPtr<mirror::PointerArray> method_array;
6241 if (super_interface) {
6242 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6243 DCHECK(if_table != nullptr);
6244 DCHECK(if_table->GetMethodArray(i) != nullptr);
6245 // If we are working on a super interface, try extending the existing method array.
6246 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6247 } else {
6248 method_array = AllocPointerArray(self, num_methods);
6249 }
6250 if (UNLIKELY(method_array == nullptr)) {
6251 self->AssertPendingOOMException();
6252 return false;
6253 }
6254 iftable->SetMethodArray(i, method_array);
6255 }
6256 }
6257 return true;
6258}
6259
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006260void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6261 ArtMethod* imt_conflict_method,
6262 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006263 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006264 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006265 // Place method in imt if entry is empty, place conflict otherwise.
6266 if (*imt_ref == unimplemented_method) {
6267 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006268 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006269 // If we are not a conflict and we have the same signature and name as the imt
6270 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006271 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6272 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006273 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006274 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006275 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006276 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006277 *imt_ref = current_method;
6278 } else {
Alex Light9139e002015-10-09 15:59:48 -07006279 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006280 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006281 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006282 } else {
6283 // Place the default conflict method. Note that there may be an existing conflict
6284 // method in the IMT, but it could be one tailored to the super class, with a
6285 // specific ImtConflictTable.
6286 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006287 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006288 }
6289}
6290
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006291void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006292 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6293 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006294 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006295 Runtime* const runtime = Runtime::Current();
6296 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6297 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006298 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006299 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006300 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006301 FillIMTFromIfTable(klass->GetIfTable(),
6302 unimplemented_method,
6303 conflict_method,
6304 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006305 /*create_conflict_tables*/true,
6306 /*ignore_copied_methods*/false,
6307 &new_conflict,
6308 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006309 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006310 if (!klass->ShouldHaveImt()) {
6311 return;
6312 }
6313 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6314 // we can just use the same pointer.
6315 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006316 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006317 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6318 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6319 bool same = true;
6320 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6321 ArtMethod* method = imt_data[i];
6322 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6323 if (method != super_method) {
6324 bool is_conflict_table = method->IsRuntimeMethod() &&
6325 method != unimplemented_method &&
6326 method != conflict_method;
6327 // Verify conflict contents.
6328 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6329 super_method != unimplemented_method &&
6330 super_method != conflict_method;
6331 if (!is_conflict_table || !super_conflict_table) {
6332 same = false;
6333 } else {
6334 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6335 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6336 same = same && table1->Equals(table2, image_pointer_size_);
6337 }
6338 }
6339 }
6340 if (same) {
6341 imt = super_imt;
6342 }
6343 }
6344 if (imt == nullptr) {
6345 imt = klass->GetImt(image_pointer_size_);
6346 DCHECK(imt != nullptr);
6347 imt->Populate(imt_data, image_pointer_size_);
6348 } else {
6349 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006350 }
6351}
6352
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006353ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6354 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006355 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006356 void* data = linear_alloc->Alloc(Thread::Current(),
6357 ImtConflictTable::ComputeSize(count,
6358 image_pointer_size));
6359 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6360}
6361
6362ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6363 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6364}
6365
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006366void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006367 ArtMethod* unimplemented_method,
6368 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006369 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006370 bool create_conflict_tables,
6371 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006372 /*out*/bool* new_conflict,
6373 /*out*/ArtMethod** imt) {
6374 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006375 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006376 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006377 const size_t num_virtuals = interface->NumVirtualMethods();
6378 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6379 // Virtual methods can be larger than the if table methods if there are default methods.
6380 DCHECK_GE(num_virtuals, method_array_count);
6381 if (kIsDebugBuild) {
6382 if (klass->IsInterface()) {
6383 DCHECK_EQ(method_array_count, 0u);
6384 } else {
6385 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6386 }
6387 }
6388 if (method_array_count == 0) {
6389 continue;
6390 }
6391 auto* method_array = if_table->GetMethodArray(i);
6392 for (size_t j = 0; j < method_array_count; ++j) {
6393 ArtMethod* implementation_method =
6394 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6395 if (ignore_copied_methods && implementation_method->IsCopied()) {
6396 continue;
6397 }
6398 DCHECK(implementation_method != nullptr);
6399 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6400 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6401 // or interface methods in the IMT here they will not create extra conflicts since we compare
6402 // names and signatures in SetIMTRef.
6403 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006404 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006405
6406 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6407 // the same implementation method, keep track of this to avoid creating a conflict table in
6408 // this case.
6409
6410 // Conflict table size for each IMT slot.
6411 ++conflict_counts[imt_index];
6412
6413 SetIMTRef(unimplemented_method,
6414 imt_conflict_method,
6415 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006416 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006417 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006418 }
6419 }
6420
6421 if (create_conflict_tables) {
6422 // Create the conflict tables.
6423 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006424 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006425 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006426 if (imt[i] == imt_conflict_method) {
6427 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6428 if (new_table != nullptr) {
6429 ArtMethod* new_conflict_method =
6430 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6431 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6432 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006433 } else {
6434 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006435 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006436 }
6437 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006438 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006439 }
6440 }
6441
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006442 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006443 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006444 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6445 // Virtual methods can be larger than the if table methods if there are default methods.
6446 if (method_array_count == 0) {
6447 continue;
6448 }
6449 auto* method_array = if_table->GetMethodArray(i);
6450 for (size_t j = 0; j < method_array_count; ++j) {
6451 ArtMethod* implementation_method =
6452 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6453 if (ignore_copied_methods && implementation_method->IsCopied()) {
6454 continue;
6455 }
6456 DCHECK(implementation_method != nullptr);
6457 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006458 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006459 if (!imt[imt_index]->IsRuntimeMethod() ||
6460 imt[imt_index] == unimplemented_method ||
6461 imt[imt_index] == imt_conflict_method) {
6462 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006463 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006464 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6465 const size_t num_entries = table->NumEntries(image_pointer_size_);
6466 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6467 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006468 }
6469 }
6470 }
6471}
6472
Alex Lighteb7c1442015-08-31 13:17:42 -07006473// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6474// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006475static bool NotSubinterfaceOfAny(
6476 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6477 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006478 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006479 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006480 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006481 for (ObjPtr<mirror::Class> c : classes) {
6482 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006483 return false;
6484 }
6485 }
6486 return true;
6487}
6488
6489// Fills in and flattens the interface inheritance hierarchy.
6490//
6491// By the end of this function all interfaces in the transitive closure of to_process are added to
6492// the iftable and every interface precedes all of its sub-interfaces in this list.
6493//
6494// all I, J: Interface | I <: J implies J precedes I
6495//
6496// (note A <: B means that A is a subtype of B)
6497//
6498// This returns the total number of items in the iftable. The iftable might be resized down after
6499// this call.
6500//
6501// We order this backwards so that we do not need to reorder superclass interfaces when new
6502// interfaces are added in subclass's interface tables.
6503//
6504// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6505// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6506// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6507// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006508static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006509 size_t super_ifcount,
6510 std::vector<mirror::Class*> to_process)
6511 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006512 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006513 // This is the set of all class's already in the iftable. Used to make checking if a class has
6514 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006515 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006516 // The first super_ifcount elements are from the superclass. We note that they are already added.
6517 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006518 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006519 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6520 classes_in_iftable.insert(iface);
6521 }
6522 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006523 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006524 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6525 // At this point in the loop current-iface-list has the invariant that:
6526 // for every pair of interfaces I,J within it:
6527 // if index_of(I) < index_of(J) then I is not a subtype of J
6528
6529 // If we have already seen this element then all of its super-interfaces must already be in the
6530 // current-iface-list so we can skip adding it.
6531 if (!ContainsElement(classes_in_iftable, interface)) {
6532 // We haven't seen this interface so add all of its super-interfaces onto the
6533 // current-iface-list, skipping those already on it.
6534 int32_t ifcount = interface->GetIfTableCount();
6535 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006536 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006537 if (!ContainsElement(classes_in_iftable, super_interface)) {
6538 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6539 classes_in_iftable.insert(super_interface);
6540 iftable->SetInterface(filled_ifcount, super_interface);
6541 filled_ifcount++;
6542 }
6543 }
6544 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6545 // Place this interface onto the current-iface-list after all of its super-interfaces.
6546 classes_in_iftable.insert(interface);
6547 iftable->SetInterface(filled_ifcount, interface);
6548 filled_ifcount++;
6549 } else if (kIsDebugBuild) {
6550 // Check all super-interfaces are already in the list.
6551 int32_t ifcount = interface->GetIfTableCount();
6552 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006553 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006554 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006555 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6556 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006557 }
6558 }
6559 }
6560 if (kIsDebugBuild) {
6561 // Check that the iftable is ordered correctly.
6562 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006563 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006564 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006565 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006566 // !(if_a <: if_b)
6567 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006568 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6569 << ") extends "
6570 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006571 << "interface list.";
6572 }
6573 }
6574 }
6575 return filled_ifcount;
6576}
6577
6578bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6579 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6580 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006581 const bool has_superclass = klass->HasSuperClass();
6582 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006583 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006584 const size_t num_interfaces =
6585 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006586 if (num_interfaces == 0) {
6587 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006588 if (LIKELY(has_superclass)) {
6589 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6590 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006591 // Class implements no interfaces.
6592 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006593 return true;
6594 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006595 // Class implements same interfaces as parent, are any of these not marker interfaces?
6596 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006597 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006598 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006599 if (super_iftable->GetMethodArrayCount(i) > 0) {
6600 has_non_marker_interface = true;
6601 break;
6602 }
6603 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006604 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006605 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006606 klass->SetIfTable(super_iftable);
6607 return true;
6608 }
6609 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006610 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006611 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006612 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006613 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006614 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006615 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006616 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006617 if (UNLIKELY(!interface->IsInterface())) {
6618 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006619 ThrowIncompatibleClassChangeError(klass.Get(),
6620 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006621 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006622 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6623 return false;
6624 }
6625 ifcount += interface->GetIfTableCount();
6626 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006627 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006628 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006629 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006630 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006631 return false;
6632 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006633 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006634 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006635 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006636 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006637 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006638 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006639 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006640 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006641
6642 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6643 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6644 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006645 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006646
6647 size_t new_ifcount;
6648 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006649 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006650 std::vector<mirror::Class*> to_add;
6651 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006652 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006653 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006654 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006655 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006656
6657 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006658 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006659
Ian Rogers7b078e82014-09-10 14:44:24 -07006660 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006661
Ian Rogersb52b01a2012-01-12 17:01:38 -08006662 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006663 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006664 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006665 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006666 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006667 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006668 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006669 return false;
6670 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006671 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006672 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006673 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006674 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006675 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006676 return true;
6677}
6678
Alex Light1f3925d2016-09-07 12:04:20 -07006679// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6680// of methods must be unique.
6681static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6682 return nullptr;
6683}
6684
6685template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006686static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006687 const ScopedArenaVector<ArtMethod*>& list,
6688 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006689 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006690 for (ArtMethod* method : list) {
6691 if (cmp.HasSameNameAndSignature(method)) {
6692 return method;
6693 }
6694 }
Alex Light1f3925d2016-09-07 12:04:20 -07006695 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006696}
6697
Alex Light1f3925d2016-09-07 12:04:20 -07006698// Check that all vtable entries are present in this class's virtuals or are the same as a
6699// superclasses vtable entry.
6700static void CheckClassOwnsVTableEntries(Thread* self,
6701 Handle<mirror::Class> klass,
6702 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006703 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006704 StackHandleScope<2> hs(self);
6705 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006706 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006707 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006708 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006709 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6710 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6711 CHECK(m != nullptr);
6712
Alex Lighta41a30782017-03-29 11:33:19 -07006713 if (m->GetMethodIndexDuringLinking() != i) {
6714 LOG(WARNING) << m->PrettyMethod()
6715 << " has an unexpected method index for its spot in the vtable for class"
6716 << klass->PrettyClass();
6717 }
Alex Lighte64300b2015-12-15 15:02:47 -08006718 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6719 auto is_same_method = [m] (const ArtMethod& meth) {
6720 return &meth == m;
6721 };
Alex Light3f980532017-03-17 15:10:32 -07006722 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6723 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6724 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6725 << klass->PrettyClass() << " or any of its superclasses!";
6726 }
Alex Lighte64300b2015-12-15 15:02:47 -08006727 }
6728}
6729
Alex Light1f3925d2016-09-07 12:04:20 -07006730// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6731// method is overridden in a subclass.
6732static void CheckVTableHasNoDuplicates(Thread* self,
6733 Handle<mirror::Class> klass,
6734 PointerSize pointer_size)
6735 REQUIRES_SHARED(Locks::mutator_lock_) {
6736 StackHandleScope<1> hs(self);
6737 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6738 int32_t num_entries = vtable->GetLength();
6739 for (int32_t i = 0; i < num_entries; i++) {
6740 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6741 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6742 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6743 vtable_entry->GetAccessFlags())) {
6744 continue;
6745 }
6746 MethodNameAndSignatureComparator name_comparator(
6747 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006748 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006749 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006750 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6751 other_entry->GetAccessFlags())) {
6752 continue;
6753 }
Alex Light3f980532017-03-17 15:10:32 -07006754 if (vtable_entry == other_entry ||
6755 name_comparator.HasSameNameAndSignature(
6756 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6757 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6758 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6759 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6760 << other_entry->PrettyMethod() << " (0x" << std::hex
6761 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6762 }
Alex Light1f3925d2016-09-07 12:04:20 -07006763 }
6764 }
6765}
6766
6767static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6768 REQUIRES_SHARED(Locks::mutator_lock_) {
6769 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6770 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6771}
6772
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006773void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6774 ArtMethod* unimplemented_method,
6775 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006776 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006777 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006778 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006779 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006780 if (super_class->ShouldHaveImt()) {
6781 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6782 for (size_t i = 0; i < ImTable::kSize; ++i) {
6783 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006784 }
6785 } else {
6786 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006787 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006788 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006789 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006790 FillIMTFromIfTable(if_table,
6791 unimplemented_method,
6792 imt_conflict_method,
6793 klass.Get(),
6794 /*create_conflict_table*/false,
6795 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006796 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006797 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006798 }
6799 }
6800}
6801
Vladimir Marko921094a2017-01-12 18:37:06 +00006802class ClassLinker::LinkInterfaceMethodsHelper {
6803 public:
6804 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6805 Handle<mirror::Class> klass,
6806 Thread* self,
6807 Runtime* runtime)
6808 : class_linker_(class_linker),
6809 klass_(klass),
6810 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6811 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6812 self_(self),
6813 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6814 allocator_(&stack_),
6815 default_conflict_methods_(allocator_.Adapter()),
6816 overriding_default_conflict_methods_(allocator_.Adapter()),
6817 miranda_methods_(allocator_.Adapter()),
6818 default_methods_(allocator_.Adapter()),
6819 overriding_default_methods_(allocator_.Adapter()),
6820 move_table_(allocator_.Adapter()) {
6821 }
6822
6823 ArtMethod* FindMethod(ArtMethod* interface_method,
6824 MethodNameAndSignatureComparator& interface_name_comparator,
6825 ArtMethod* vtable_impl)
6826 REQUIRES_SHARED(Locks::mutator_lock_);
6827
6828 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6829 MethodNameAndSignatureComparator& interface_name_comparator)
6830 REQUIRES_SHARED(Locks::mutator_lock_);
6831
6832 bool HasNewVirtuals() const {
6833 return !(miranda_methods_.empty() &&
6834 default_methods_.empty() &&
6835 overriding_default_methods_.empty() &&
6836 overriding_default_conflict_methods_.empty() &&
6837 default_conflict_methods_.empty());
6838 }
6839
6840 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6841
6842 ObjPtr<mirror::PointerArray> UpdateVtable(
6843 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6844 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6845
6846 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6847
6848 void UpdateIMT(ArtMethod** out_imt);
6849
6850 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6851 if (kIsDebugBuild) {
6852 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6853 // Check that there are no stale methods are in the dex cache array.
6854 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6855 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006856 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6857 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006858 CHECK(move_table_.find(m) == move_table_.end() ||
6859 // The original versions of copied methods will still be present so allow those too.
6860 // Note that if the first check passes this might fail to GetDeclaringClass().
6861 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6862 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6863 [m] (ArtMethod& meth) {
6864 return &meth == m;
6865 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6866 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6867 }
6868 }
6869 }
6870
6871 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6872 LengthPrefixedArray<ArtMethod>* methods) {
6873 if (kIsDebugBuild) {
6874 CHECK(methods != nullptr);
6875 // Put some random garbage in old methods to help find stale pointers.
6876 if (methods != old_methods && old_methods != nullptr) {
6877 // Need to make sure the GC is not running since it could be scanning the methods we are
6878 // about to overwrite.
6879 ScopedThreadStateChange tsc(self_, kSuspended);
6880 gc::ScopedGCCriticalSection gcs(self_,
6881 gc::kGcCauseClassLinker,
6882 gc::kCollectorTypeClassLinker);
6883 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6884 method_size_,
6885 method_alignment_);
6886 memset(old_methods, 0xFEu, old_size);
6887 }
6888 }
6889 }
6890
6891 private:
6892 size_t NumberOfNewVirtuals() const {
6893 return miranda_methods_.size() +
6894 default_methods_.size() +
6895 overriding_default_conflict_methods_.size() +
6896 overriding_default_methods_.size() +
6897 default_conflict_methods_.size();
6898 }
6899
6900 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6901 return !klass_->IsInterface();
6902 }
6903
6904 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6905 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6906 << "Interfaces should only have default-conflict methods appended to them.";
6907 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6908 << miranda_methods_.size()
6909 << " default_methods=" << default_methods_.size()
6910 << " overriding_default_methods=" << overriding_default_methods_.size()
6911 << " default_conflict_methods=" << default_conflict_methods_.size()
6912 << " overriding_default_conflict_methods="
6913 << overriding_default_conflict_methods_.size();
6914 }
6915
6916 ClassLinker* class_linker_;
6917 Handle<mirror::Class> klass_;
6918 size_t method_alignment_;
6919 size_t method_size_;
6920 Thread* const self_;
6921
6922 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6923 // the virtual methods array.
6924 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6925 // during cross compilation.
6926 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6927 ArenaStack stack_;
6928 ScopedArenaAllocator allocator_;
6929
6930 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6931 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6932 ScopedArenaVector<ArtMethod*> miranda_methods_;
6933 ScopedArenaVector<ArtMethod*> default_methods_;
6934 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6935
6936 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6937};
6938
6939ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6940 ArtMethod* interface_method,
6941 MethodNameAndSignatureComparator& interface_name_comparator,
6942 ArtMethod* vtable_impl) {
6943 ArtMethod* current_method = nullptr;
6944 switch (class_linker_->FindDefaultMethodImplementation(self_,
6945 interface_method,
6946 klass_,
6947 /*out*/&current_method)) {
6948 case DefaultMethodSearchResult::kDefaultConflict: {
6949 // Default method conflict.
6950 DCHECK(current_method == nullptr);
6951 ArtMethod* default_conflict_method = nullptr;
6952 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6953 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6954 default_conflict_method = vtable_impl;
6955 } else {
6956 // See if we already have a conflict method for this method.
6957 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6958 interface_name_comparator,
6959 default_conflict_methods_,
6960 overriding_default_conflict_methods_);
6961 if (LIKELY(preexisting_conflict != nullptr)) {
6962 // We already have another conflict we can reuse.
6963 default_conflict_method = preexisting_conflict;
6964 } else {
6965 // Note that we do this even if we are an interface since we need to create this and
6966 // cannot reuse another classes.
6967 // Create a new conflict method for this to use.
6968 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6969 new(default_conflict_method) ArtMethod(interface_method,
6970 class_linker_->GetImagePointerSize());
6971 if (vtable_impl == nullptr) {
6972 // Save the conflict method. We need to add it to the vtable.
6973 default_conflict_methods_.push_back(default_conflict_method);
6974 } else {
6975 // Save the conflict method but it is already in the vtable.
6976 overriding_default_conflict_methods_.push_back(default_conflict_method);
6977 }
6978 }
6979 }
6980 current_method = default_conflict_method;
6981 break;
6982 } // case kDefaultConflict
6983 case DefaultMethodSearchResult::kDefaultFound: {
6984 DCHECK(current_method != nullptr);
6985 // Found a default method.
6986 if (vtable_impl != nullptr &&
6987 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6988 // We found a default method but it was the same one we already have from our
6989 // superclass. Don't bother adding it to our vtable again.
6990 current_method = vtable_impl;
6991 } else if (LIKELY(FillTables())) {
6992 // Interfaces don't need to copy default methods since they don't have vtables.
6993 // Only record this default method if it is new to save space.
6994 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6995 // would make lookup for interface super much faster. (We would only need to scan
6996 // the iftable to find if there is a NSME or AME.)
6997 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6998 default_methods_,
6999 overriding_default_methods_);
7000 if (old == nullptr) {
7001 // We found a default method implementation and there were no conflicts.
7002 if (vtable_impl == nullptr) {
7003 // Save the default method. We need to add it to the vtable.
7004 default_methods_.push_back(current_method);
7005 } else {
7006 // Save the default method but it is already in the vtable.
7007 overriding_default_methods_.push_back(current_method);
7008 }
7009 } else {
7010 CHECK(old == current_method) << "Multiple default implementations selected!";
7011 }
7012 }
7013 break;
7014 } // case kDefaultFound
7015 case DefaultMethodSearchResult::kAbstractFound: {
7016 DCHECK(current_method == nullptr);
7017 // Abstract method masks all defaults.
7018 if (vtable_impl != nullptr &&
7019 vtable_impl->IsAbstract() &&
7020 !vtable_impl->IsDefaultConflicting()) {
7021 // We need to make this an abstract method but the version in the vtable already is so
7022 // don't do anything.
7023 current_method = vtable_impl;
7024 }
7025 break;
7026 } // case kAbstractFound
7027 }
7028 return current_method;
7029}
7030
7031ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7032 ArtMethod* interface_method,
7033 MethodNameAndSignatureComparator& interface_name_comparator) {
7034 // Find out if there is already a miranda method we can use.
7035 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7036 miranda_methods_);
7037 if (miranda_method == nullptr) {
7038 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7039 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7040 CHECK(miranda_method != nullptr);
7041 // Point the interface table at a phantom slot.
7042 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7043 miranda_methods_.push_back(miranda_method);
7044 }
7045 return miranda_method;
7046}
7047
7048void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7049 LogNewVirtuals();
7050
7051 const size_t old_method_count = klass_->NumMethods();
7052 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7053 DCHECK_NE(old_method_count, new_method_count);
7054
7055 // Attempt to realloc to save RAM if possible.
7056 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7057 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7058 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7059 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7060 // CopyFrom has internal read barriers.
7061 //
7062 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7063 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7064 method_size_,
7065 method_alignment_);
7066 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7067 method_size_,
7068 method_alignment_);
7069 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7070 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007071 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007072 self_, old_methods, old_methods_ptr_size, new_size));
7073 CHECK(methods != nullptr); // Native allocation failure aborts.
7074
7075 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7076 if (methods != old_methods) {
7077 // Maps from heap allocated miranda method to linear alloc miranda method.
7078 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7079 // Copy over the old methods.
7080 for (auto& m : klass_->GetMethods(pointer_size)) {
7081 move_table_.emplace(&m, &*out);
7082 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7083 // barriers when it copies.
7084 out->CopyFrom(&m, pointer_size);
7085 ++out;
7086 }
7087 }
7088 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7089 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7090 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007091 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7092 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007093 ArtMethod& new_method = *out;
7094 new_method.CopyFrom(mir_method, pointer_size);
7095 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7096 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7097 << "Miranda method should be abstract!";
7098 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007099 // Update the entry in the method array, as the array will be used for future lookups,
7100 // where thread suspension is allowed.
7101 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7102 // would not see them.
7103 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007104 ++out;
7105 }
7106 // We need to copy the default methods into our own method table since the runtime requires that
7107 // every method on a class's vtable be in that respective class's virtual method table.
7108 // NOTE This means that two classes might have the same implementation of a method from the same
7109 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7110 // default method found on a class with one found on the declaring interface directly and must
7111 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007112 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7113 &overriding_default_methods_}) {
7114 for (size_t i = 0; i < methods_vec->size(); ++i) {
7115 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007116 ArtMethod& new_method = *out;
7117 new_method.CopyFrom(def_method, pointer_size);
7118 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7119 // verified yet it shouldn't have methods that are skipping access checks.
7120 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7121 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007122 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007123 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7124 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7125 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7126 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007127 // Update the entry in the method array, as the array will be used for future lookups,
7128 // where thread suspension is allowed.
7129 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7130 // would not see them.
7131 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007132 ++out;
7133 }
7134 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007135 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7136 &overriding_default_conflict_methods_}) {
7137 for (size_t i = 0; i < methods_vec->size(); ++i) {
7138 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007139 ArtMethod& new_method = *out;
7140 new_method.CopyFrom(conf_method, pointer_size);
7141 // This is a type of default method (there are default method impls, just a conflict) so
7142 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7143 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7144 // methods that are skipping access checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007145 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007146 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7147 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7148 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7149 DCHECK(new_method.IsDefaultConflicting());
7150 // The actual method might or might not be marked abstract since we just copied it from a
7151 // (possibly default) interface method. We need to set it entry point to be the bridge so
7152 // that the compiler will not invoke the implementation of whatever method we copied from.
7153 EnsureThrowsInvocationError(class_linker_, &new_method);
7154 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007155 // Update the entry in the method array, as the array will be used for future lookups,
7156 // where thread suspension is allowed.
7157 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7158 // would not see them.
7159 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007160 ++out;
7161 }
7162 }
7163 methods->SetSize(new_method_count);
7164 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7165}
7166
7167ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7168 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7169 ObjPtr<mirror::PointerArray> old_vtable) {
7170 // Update the vtable to the new method structures. We can skip this for interfaces since they
7171 // do not have vtables.
7172 const size_t old_vtable_count = old_vtable->GetLength();
7173 const size_t new_vtable_count = old_vtable_count +
7174 miranda_methods_.size() +
7175 default_methods_.size() +
7176 default_conflict_methods_.size();
7177
7178 ObjPtr<mirror::PointerArray> vtable =
7179 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7180 if (UNLIKELY(vtable == nullptr)) {
7181 self_->AssertPendingOOMException();
7182 return nullptr;
7183 }
7184
7185 size_t vtable_pos = old_vtable_count;
7186 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7187 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7188 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7189 default_conflict_methods_,
7190 miranda_methods_}) {
7191 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007192 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007193 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7194 // fields are references into the dex file the method was defined in. Since the ArtMethod
7195 // does not store that information it uses declaring_class_->dex_cache_.
7196 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7197 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7198 ++vtable_pos;
7199 }
7200 }
7201 DCHECK_EQ(vtable_pos, new_vtable_count);
7202
7203 // Update old vtable methods. We use the default_translations map to figure out what each
7204 // vtable entry should be updated to, if they need to be at all.
7205 for (size_t i = 0; i < old_vtable_count; ++i) {
7206 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7207 // Try and find what we need to change this method to.
7208 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007209 if (translation_it != default_translations.end()) {
7210 if (translation_it->second.IsInConflict()) {
7211 // Find which conflict method we are to use for this method.
7212 MethodNameAndSignatureComparator old_method_comparator(
7213 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7214 // We only need to look through overriding_default_conflict_methods since this is an
7215 // overridden method we are fixing up here.
7216 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7217 old_method_comparator, overriding_default_conflict_methods_);
7218 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7219 translated_method = new_conflict_method;
7220 } else if (translation_it->second.IsAbstract()) {
7221 // Find which miranda method we are to use for this method.
7222 MethodNameAndSignatureComparator old_method_comparator(
7223 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7224 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7225 miranda_methods_);
7226 DCHECK(miranda_method != nullptr);
7227 translated_method = miranda_method;
7228 } else {
7229 // Normal default method (changed from an older default or abstract interface method).
7230 DCHECK(translation_it->second.IsTranslation());
7231 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007232 auto it = move_table_.find(translated_method);
7233 DCHECK(it != move_table_.end());
7234 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007235 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007236 } else {
7237 auto it = move_table_.find(translated_method);
7238 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007239 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007240
7241 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007242 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007243 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007244 if (kIsDebugBuild) {
7245 auto* methods = klass_->GetMethodsPtr();
7246 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007247 reinterpret_cast<uintptr_t>(translated_method));
7248 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007249 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7250 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007251 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007252 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007253 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007254 }
7255 }
7256 klass_->SetVTable(vtable.Ptr());
7257 return vtable;
7258}
7259
7260void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7261 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7262 const size_t ifcount = klass_->GetIfTableCount();
7263 // Go fix up all the stale iftable pointers.
7264 for (size_t i = 0; i < ifcount; ++i) {
7265 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7266 auto* method_array = iftable->GetMethodArray(i);
7267 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7268 DCHECK(m != nullptr) << klass_->PrettyClass();
7269 auto it = move_table_.find(m);
7270 if (it != move_table_.end()) {
7271 auto* new_m = it->second;
7272 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7273 method_array->SetElementPtrSize(j, new_m, pointer_size);
7274 }
7275 }
7276 }
7277}
7278
7279void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7280 // Fix up IMT next.
7281 for (size_t i = 0; i < ImTable::kSize; ++i) {
7282 auto it = move_table_.find(out_imt[i]);
7283 if (it != move_table_.end()) {
7284 out_imt[i] = it->second;
7285 }
7286 }
7287}
7288
Alex Light705ad492015-09-21 11:36:30 -07007289// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007290bool ClassLinker::LinkInterfaceMethods(
7291 Thread* self,
7292 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007293 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007294 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007295 ArtMethod** out_imt) {
7296 StackHandleScope<3> hs(self);
7297 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007298
7299 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007300 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007301 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007302 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007303 const size_t ifcount = klass->GetIfTableCount();
7304
Vladimir Marko921094a2017-01-12 18:37:06 +00007305 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007306
7307 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7308 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007309 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007310 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007311 const bool extend_super_iftable = has_superclass;
7312 if (has_superclass && fill_tables) {
7313 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007314 unimplemented_method,
7315 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007316 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007317 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007318 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007319 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7320 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007321 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007322 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7323 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007324 }
7325 }
7326
Vladimir Marko921094a2017-01-12 18:37:06 +00007327 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7328
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007329 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007330 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007331 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7332 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7333 // they will already be null. This has the additional benefit that the declarer of a miranda
7334 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007335 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007336 --i;
Alex Light9139e002015-10-09 15:59:48 -07007337 DCHECK_LT(i, ifcount);
7338
Alex Light705ad492015-09-21 11:36:30 -07007339 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007340 if (num_methods > 0) {
7341 StackHandleScope<2> hs2(self);
7342 const bool is_super = i < super_ifcount;
7343 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007344 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7345 // conflict methods. Just set this as nullptr in those cases.
7346 Handle<mirror::PointerArray> method_array(fill_tables
7347 ? hs2.NewHandle(iftable->GetMethodArray(i))
7348 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007349
Alex Lighte64300b2015-12-15 15:02:47 -08007350 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007351 ScopedNullHandle<mirror::PointerArray> null_handle;
7352 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007353 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007354
Alex Light9139e002015-10-09 15:59:48 -07007355 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7356 // and confusing. Default methods should always look through all the superclasses
7357 // because they are the last choice of an implementation. We get around this by looking
7358 // at the super-classes iftable methods (copied into method_array previously) when we are
7359 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007360 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007361 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007362 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007363 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007364 using_virtuals = true;
7365 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7366 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007367 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007368 // For a new interface, however, we need the whole vtable in case a new
7369 // interface method is implemented in the whole superclass.
7370 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007371 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007372 input_vtable_array = vtable;
7373 input_array_length = input_vtable_array->GetLength();
7374 }
Alex Lighte64300b2015-12-15 15:02:47 -08007375
Alex Lighteb7c1442015-08-31 13:17:42 -07007376 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007377 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007378 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007379 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007380 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007381 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007382 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007383 // For each method listed in the interface's method list, find the
7384 // matching method in our class's method list. We want to favor the
7385 // subclass over the superclass, which just requires walking
7386 // back from the end of the vtable. (This only matters if the
7387 // superclass defines a private method and this class redefines
7388 // it -- otherwise it would use the same vtable slot. In .dex files
7389 // those don't end up in the virtual method table, so it shouldn't
7390 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007391 //
7392 // To find defaults we need to do the same but also go over interfaces.
7393 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007394 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007395 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007396 ArtMethod* vtable_method = using_virtuals ?
7397 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007398 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7399 ArtMethod* vtable_method_for_name_comparison =
7400 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007401 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007402 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007403 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007404 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7405 // allocations.
7406 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007407 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007408 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007409 vtable_method->PrettyMethod().c_str(),
7410 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007411 return false;
Alex Light9139e002015-10-09 15:59:48 -07007412 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007413 // We might have a newer, better, default method for this, so we just skip it. If we
7414 // are still using this we will select it again when scanning for default methods. To
7415 // obviate the need to copy the method again we will make a note that we already found
7416 // a default here.
7417 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007418 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007419 break;
7420 } else {
7421 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007422 if (LIKELY(fill_tables)) {
7423 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7424 // Place method in imt if entry is empty, place conflict otherwise.
7425 SetIMTRef(unimplemented_method,
7426 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007427 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007428 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007429 /*out*/imt_ptr);
7430 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007431 break;
7432 }
7433 }
Alex Light9139e002015-10-09 15:59:48 -07007434 }
7435 // Continue on to the next method if we are done.
7436 if (LIKELY(found_impl)) {
7437 continue;
7438 } else if (LIKELY(super_interface)) {
7439 // Don't look for a default implementation when the super-method is implemented directly
7440 // by the class.
7441 //
7442 // See if we can use the superclasses method and skip searching everything else.
7443 // Note: !found_impl && super_interface
7444 CHECK(extend_super_iftable);
7445 // If this is a super_interface method it is possible we shouldn't override it because a
7446 // superclass could have implemented it directly. We get the method the superclass used
7447 // to implement this to know if we can override it with a default method. Doing this is
7448 // safe since we know that the super_iftable is filled in so we can simply pull it from
7449 // there. We don't bother if this is not a super-classes interface since in that case we
7450 // have scanned the entire vtable anyway and would have found it.
7451 // TODO This is rather dirty but it is faster than searching through the entire vtable
7452 // every time.
7453 ArtMethod* supers_method =
7454 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7455 DCHECK(supers_method != nullptr);
7456 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007457 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007458 // The method is not overridable by a default method (i.e. it is directly implemented
7459 // in some class). Therefore move onto the next interface method.
7460 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007461 } else {
7462 // If the super-classes method is override-able by a default method we need to keep
7463 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7464 // 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 -07007465 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7466 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7467 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007468 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007469 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7470 << " and not 'nullptr' or "
7471 << supers_method->PrettyMethod()
7472 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007473 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007474 }
7475 }
7476 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007477 ArtMethod* current_method = helper.FindMethod(interface_method,
7478 interface_name_comparator,
7479 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007480 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007481 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007482 // We could not find an implementation for this method and since it is a brand new
7483 // interface we searched the entire vtable (and all default methods) for an
7484 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007485 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7486 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007487 }
7488
7489 if (current_method != nullptr) {
7490 // We found a default method implementation. Record it in the iftable and IMT.
7491 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7492 SetIMTRef(unimplemented_method,
7493 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007494 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007495 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007496 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007497 }
7498 }
Alex Light705ad492015-09-21 11:36:30 -07007499 } // For each method in interface end.
7500 } // if (num_methods > 0)
7501 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007502 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007503 if (helper.HasNewVirtuals()) {
7504 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7505 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7506 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7507
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007508 // 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 -07007509 // suspension assert.
7510 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007511
Alex Light705ad492015-09-21 11:36:30 -07007512 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007513 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007514 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007515 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007516 return false;
7517 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007518 helper.UpdateIfTable(iftable);
7519 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007520 }
Alex Light705ad492015-09-21 11:36:30 -07007521
Vladimir Marko921094a2017-01-12 18:37:06 +00007522 helper.CheckNoStaleMethodsInDexCache();
7523 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007524 } else {
7525 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007526 }
Alex Light705ad492015-09-21 11:36:30 -07007527 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007528 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007529 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007530 return true;
7531}
7532
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007533bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007534 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007535 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007536}
7537
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007538bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007539 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007540 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007541}
7542
Brian Carlstromdbc05252011-09-09 01:59:59 -07007543struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007544 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007545 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007546 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007547 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007548 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007549 // 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 -07007550 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7551 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007552 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007553 if (type1 == Primitive::kPrimNot) {
7554 // Reference always goes first.
7555 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007556 }
Vladimir Markod5777482014-11-12 17:02:02 +00007557 if (type2 == Primitive::kPrimNot) {
7558 // Reference always goes first.
7559 return false;
7560 }
7561 size_t size1 = Primitive::ComponentSize(type1);
7562 size_t size2 = Primitive::ComponentSize(type2);
7563 if (size1 != size2) {
7564 // Larger primitive types go first.
7565 return size1 > size2;
7566 }
7567 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7568 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007569 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007570 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7571 // by name and for equal names by type id index.
7572 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7573 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007574 }
7575};
7576
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007577bool ClassLinker::LinkFields(Thread* self,
7578 Handle<mirror::Class> klass,
7579 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007580 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007581 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007582 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007583 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7584 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007585
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007586 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007587 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007588 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007589 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007590 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007591 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007592 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007593 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007594 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007595 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007596 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007597 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007598
David Sehr709b0702016-10-13 09:12:37 -07007599 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007600
Brian Carlstromdbc05252011-09-09 01:59:59 -07007601 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007602 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007603 //
7604 // The overall sort order order is:
7605 // 1) All object reference fields, sorted alphabetically.
7606 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7607 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7608 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7609 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7610 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7611 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7612 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7613 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7614 //
7615 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7616 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007617 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007618 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007619 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007620 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007621 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007622 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007623 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7624 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007625
Fred Shih381e4ca2014-08-25 17:24:27 -07007626 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007627 size_t current_field = 0;
7628 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007629 FieldGaps gaps;
7630
Brian Carlstromdbc05252011-09-09 01:59:59 -07007631 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007632 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007633 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007634 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007635 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007636 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007637 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007638 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7639 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007640 MemberOffset old_offset = field_offset;
7641 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7642 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7643 }
Roland Levillain14d90572015-07-16 10:52:26 +01007644 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007645 grouped_and_sorted_fields.pop_front();
7646 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007647 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007648 field_offset = MemberOffset(field_offset.Uint32Value() +
7649 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007650 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007651 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7652 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007653 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7654 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7655 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7656 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007657 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7658 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007659 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007660
Elliott Hughesadb460d2011-10-05 17:02:34 -07007661 // 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 -07007662 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007663 // We know there are no non-reference fields in the Reference classes, and we know
7664 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007665 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007666 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007667 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007668 --num_reference_fields;
7669 }
7670
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007671 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007672 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007673 if (is_static) {
7674 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007675 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007676 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007677 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007678 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007679 if (num_reference_fields == 0 || super_class == nullptr) {
7680 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007681 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007682 if (super_class == nullptr ||
7683 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7684 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007685 }
7686 }
7687 if (kIsDebugBuild) {
7688 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7689 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007690 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007691 while (cur_super != nullptr) {
7692 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7693 cur_super = cur_super->GetSuperClass();
7694 }
7695 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007696 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007697 } else {
7698 // Check that there is at least num_reference_fields other than Object.class.
7699 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007700 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007701 }
7702 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007703 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007704 std::string temp;
7705 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7706 size_t previous_size = klass->GetObjectSize();
7707 if (previous_size != 0) {
7708 // Make sure that we didn't originally have an incorrect size.
7709 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007710 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007711 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007712 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007713 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007714
7715 if (kIsDebugBuild) {
7716 // Make sure that the fields array is ordered by name but all reference
7717 // offsets are at the beginning as far as alignment allows.
7718 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007719 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007720 : klass->GetFirstReferenceInstanceFieldOffset();
7721 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7722 num_reference_fields *
7723 sizeof(mirror::HeapReference<mirror::Object>));
7724 MemberOffset current_ref_offset = start_ref_offset;
7725 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007726 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007727 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007728 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7729 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007730 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007731 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007732 // NOTE: The field names can be the same. This is not possible in the Java language
7733 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007734 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007735 }
7736 Primitive::Type type = field->GetTypeAsPrimitiveType();
7737 bool is_primitive = type != Primitive::kPrimNot;
7738 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7739 strcmp("referent", field->GetName()) == 0) {
7740 is_primitive = true; // We lied above, so we have to expect a lie here.
7741 }
7742 MemberOffset offset = field->GetOffsetDuringLinking();
7743 if (is_primitive) {
7744 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7745 // Shuffled before references.
7746 size_t type_size = Primitive::ComponentSize(type);
7747 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7748 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7749 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7750 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7751 }
7752 } else {
7753 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7754 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7755 sizeof(mirror::HeapReference<mirror::Object>));
7756 }
7757 }
7758 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7759 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007760 return true;
7761}
7762
Vladimir Marko76649e82014-11-10 18:32:59 +00007763// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007764void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007765 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007766 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007767 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007768 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007769 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007770 // Compute reference offsets unless our superclass overflowed.
7771 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7772 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007773 if (num_reference_fields != 0u) {
7774 // All of the fields that contain object references are guaranteed be grouped in memory
7775 // starting at an appropriately aligned address after super class object data.
7776 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7777 sizeof(mirror::HeapReference<mirror::Object>));
7778 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007779 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007780 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007781 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007782 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007783 reference_offsets |= (0xffffffffu << start_bit) &
7784 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007785 }
7786 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007787 }
7788 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007789 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007790}
7791
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007792ObjPtr<mirror::String> ClassLinker::ResolveString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007793 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007794 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007795 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007796 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007797 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007798 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007799 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007800 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07007801 uint32_t utf16_length;
7802 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007803 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007804 if (string != nullptr) {
7805 dex_cache->SetResolvedString(string_idx, string);
7806 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007807 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007808}
7809
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007810ObjPtr<mirror::String> ClassLinker::LookupString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007811 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007812 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007813 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007814 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007815 return resolved;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007816 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007817 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007818 uint32_t utf16_length;
7819 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007820 ObjPtr<mirror::String> string =
7821 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007822 if (string != nullptr) {
7823 dex_cache->SetResolvedString(string_idx, string);
7824 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007825 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007826}
7827
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007828ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
7829 ObjPtr<mirror::DexCache> dex_cache,
7830 ObjPtr<mirror::ClassLoader> class_loader) {
7831 const DexFile& dex_file = *dex_cache->GetDexFile();
7832 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7833 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7834 ObjPtr<mirror::Class> type = nullptr;
7835 if (descriptor[1] == '\0') {
7836 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7837 // for primitive classes that aren't backed by dex files.
7838 type = FindPrimitiveClass(descriptor[0]);
7839 } else {
7840 Thread* const self = Thread::Current();
7841 DCHECK(self != nullptr);
7842 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7843 // Find the class in the loaded classes table.
7844 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
7845 }
7846 if (type != nullptr) {
7847 if (type->IsResolved()) {
7848 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07007849 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007850 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007851 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007852 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007853 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007854}
7855
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007856ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
7857 Handle<mirror::DexCache> dex_cache,
7858 Handle<mirror::ClassLoader> class_loader) {
7859 Thread* self = Thread::Current();
7860 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
7861 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
7862 if (resolved != nullptr) {
7863 // TODO: we used to throw here if resolved's class loader was not the
7864 // boot class loader. This was to permit different classes with the
7865 // same name to be loaded simultaneously by different loaders
7866 dex_cache->SetResolvedType(type_idx, resolved);
7867 } else {
7868 CHECK(self->IsExceptionPending())
7869 << "Expected pending exception for failed resolution of: " << descriptor;
7870 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7871 StackHandleScope<1> hs(self);
7872 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01007873 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007874 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7875 self->ClearException();
7876 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7877 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007878 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007879 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007880 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007881 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00007882 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007883}
7884
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007885ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
7886 ObjPtr<mirror::DexCache> dex_cache,
7887 ObjPtr<mirror::ClassLoader> class_loader,
7888 uint32_t method_idx) {
7889 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7890 // functions can optimize the search if the dex_cache is the same as the DexCache
7891 // of the class, with fall-back to name and signature search otherwise.
7892 ArtMethod* resolved = nullptr;
7893 if (klass->IsInterface()) {
7894 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7895 } else {
7896 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7897 }
7898 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00007899 if (resolved != nullptr &&
Narayan Kamathf5f1f802018-04-03 15:23:46 +01007900 hiddenapi::GetMemberAction(
7901 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00007902 resolved = nullptr;
7903 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007904 if (resolved != nullptr) {
7905 // In case of jmvti, the dex file gets verified before being registered, so first
7906 // check if it's registered before checking class tables.
7907 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007908 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
7909 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007910 << "DexFile referrer: " << dex_file.GetLocation()
7911 << " ClassLoader: " << DescribeLoaders(class_loader, "");
7912 // Be a good citizen and update the dex cache to speed subsequent calls.
7913 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007914 // Disable the following invariant check as the verifier breaks it. b/73760543
7915 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7916 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
7917 // << "Method: " << resolved->PrettyMethod() << ", "
7918 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
7919 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007920 }
7921 return resolved;
7922}
7923
David Brazdil4525e0b2018-04-05 16:57:32 +01007924// Returns true if `method` is either null or hidden.
7925// Does not print any warnings if it is hidden.
7926static bool CheckNoSuchMethod(ArtMethod* method,
7927 ObjPtr<mirror::DexCache> dex_cache,
7928 ObjPtr<mirror::ClassLoader> class_loader)
7929 REQUIRES_SHARED(Locks::mutator_lock_) {
7930 return method == nullptr ||
7931 hiddenapi::GetMemberAction(method,
7932 class_loader,
7933 dex_cache,
7934 hiddenapi::kNone) // do not print warnings
7935 == hiddenapi::kDeny;
7936}
7937
7938ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
7939 ObjPtr<mirror::DexCache> dex_cache,
7940 ObjPtr<mirror::ClassLoader> class_loader,
7941 uint32_t method_idx) {
7942 if (klass->IsInterface()) {
7943 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7944 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
7945 } else {
7946 // If there was an interface method with the same signature, we would have
7947 // found it in the "copied" methods. Only DCHECK that the interface method
7948 // really does not exist.
7949 if (kIsDebugBuild) {
7950 ArtMethod* method =
7951 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7952 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
7953 }
7954 return nullptr;
7955 }
7956}
7957
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007958template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00007959ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007960 Handle<mirror::DexCache> dex_cache,
7961 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007962 ArtMethod* referrer,
7963 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007964 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007965 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007966 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007967 PointerSize pointer_size = image_pointer_size_;
7968 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007969 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007970 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7971 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007972 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7973 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007974 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007975 return resolved;
7976 }
Vladimir Marko89011192017-12-11 13:45:05 +00007977 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007978 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007979 ObjPtr<mirror::Class> klass = nullptr;
7980 if (valid_dex_cache_method) {
7981 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7982 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007983 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007984 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007985 // We normaly should not end up here. However the verifier currently doesn't guarantee
7986 // the invariant of having the klass in the class table. b/73760543
7987 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007988 }
Vladimir Markoba118822017-06-12 15:41:56 +01007989 } else {
7990 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007991 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01007992 if (klass == nullptr) {
7993 DCHECK(Thread::Current()->IsExceptionPending());
7994 return nullptr;
7995 }
7996 }
7997
7998 // Check if the invoke type matches the class type.
7999 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
8000 CheckInvokeClassMismatch</* kThrow */ true>(
8001 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008002 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008003 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008004 }
Vladimir Markoba118822017-06-12 15:41:56 +01008005
8006 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008007 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008008 }
Vladimir Markoba118822017-06-12 15:41:56 +01008009
8010 // Note: We can check for IllegalAccessError only if we have a referrer.
8011 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8012 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8013 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8014 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8015 resolved,
8016 dex_cache.Get(),
8017 method_idx,
8018 type)) {
8019 DCHECK(Thread::Current()->IsExceptionPending());
8020 return nullptr;
8021 }
8022 }
8023
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008024 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008025 if (LIKELY(resolved != nullptr) &&
8026 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8027 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008028 return resolved;
8029 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008030 // If we had a method, or if we can find one with another lookup type,
8031 // it's an incompatible-class-change error.
8032 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008033 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008034 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008035 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008036 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008037 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008038 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008039 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8040 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008041 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008042 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008043 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008044 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008045 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008046}
8047
Vladimir Marko89011192017-12-11 13:45:05 +00008048ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008049 Handle<mirror::DexCache> dex_cache,
8050 Handle<mirror::ClassLoader> class_loader) {
8051 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008052 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008053 if (resolved != nullptr) {
8054 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008055 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8056 return resolved;
8057 }
8058 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008059 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
8060 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008061 if (klass == nullptr) {
8062 Thread::Current()->AssertPendingException();
8063 return nullptr;
8064 }
8065 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008066 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8067 } else {
8068 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008069 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008070 if (resolved != nullptr &&
Narayan Kamathf5f1f802018-04-03 15:23:46 +01008071 hiddenapi::GetMemberAction(
8072 resolved, class_loader.Get(), dex_cache.Get(), hiddenapi::kLinking) == hiddenapi::kDeny) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008073 resolved = nullptr;
8074 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008075 return resolved;
8076}
8077
Vladimir Markof44d36c2017-03-14 14:18:46 +00008078ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8079 ObjPtr<mirror::DexCache> dex_cache,
8080 ObjPtr<mirror::ClassLoader> class_loader,
8081 bool is_static) {
8082 const DexFile& dex_file = *dex_cache->GetDexFile();
8083 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8084 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8085 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008086 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008087 }
8088 if (klass == nullptr) {
8089 // The class has not been resolved yet, so the field is also unresolved.
8090 return nullptr;
8091 }
8092 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008093
David Brazdil1ab0fa82018-05-04 11:28:03 +01008094 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008095}
8096
Vladimir Markoe11dd502017-12-08 14:09:45 +00008097ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008098 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008099 Handle<mirror::ClassLoader> class_loader,
8100 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008101 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008102 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008103 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008104 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008105 return resolved;
8106 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008107 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008108 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008109 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008110 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008111 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008112 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008113 }
8114
David Brazdil1ab0fa82018-05-04 11:28:03 +01008115 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008116 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008117 const char* name = dex_file.GetFieldName(field_id);
8118 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008119 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008120 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008121 return resolved;
8122}
8123
Vladimir Markoe11dd502017-12-08 14:09:45 +00008124ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008125 Handle<mirror::DexCache> dex_cache,
8126 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008127 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008128 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008129 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008130 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008131 return resolved;
8132 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008133 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008134 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008135 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008136 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008137 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008138 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008139 }
8140
David Brazdil1ab0fa82018-05-04 11:28:03 +01008141 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8142 if (resolved == nullptr) {
8143 const char* name = dex_file.GetFieldName(field_id);
8144 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008145 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008146 }
8147 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008148}
8149
David Brazdil1ab0fa82018-05-04 11:28:03 +01008150ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8151 ObjPtr<mirror::DexCache> dex_cache,
8152 ObjPtr<mirror::ClassLoader> class_loader,
8153 uint32_t field_idx,
8154 bool is_static) {
8155 ArtField* resolved = nullptr;
8156 Thread* self = is_static ? Thread::Current() : nullptr;
8157 const DexFile& dex_file = *dex_cache->GetDexFile();
8158
8159 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8160 : klass->FindInstanceField(dex_cache, field_idx);
8161
8162 if (resolved == nullptr) {
8163 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8164 const char* name = dex_file.GetFieldName(field_id);
8165 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8166 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8167 : klass->FindInstanceField(name, type);
8168 }
8169
8170 if (resolved != nullptr &&
8171 hiddenapi::GetMemberAction(
8172 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
8173 resolved = nullptr;
8174 }
8175
8176 if (resolved != nullptr) {
8177 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8178 }
8179
8180 return resolved;
8181}
8182
8183ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8184 ObjPtr<mirror::DexCache> dex_cache,
8185 ObjPtr<mirror::ClassLoader> class_loader,
8186 uint32_t field_idx) {
8187 ArtField* resolved = nullptr;
8188 Thread* self = Thread::Current();
8189 const DexFile& dex_file = *dex_cache->GetDexFile();
8190 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8191
8192 const char* name = dex_file.GetFieldName(field_id);
8193 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8194 resolved = mirror::Class::FindField(self, klass, name, type);
8195
8196 if (resolved != nullptr &&
8197 hiddenapi::GetMemberAction(
8198 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
8199 resolved = nullptr;
8200 }
8201
8202 if (resolved != nullptr) {
8203 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8204 }
8205
8206 return resolved;
8207}
8208
Vladimir Markoaf940202017-12-08 15:01:18 +00008209ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8210 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008211 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008212 Handle<mirror::DexCache> dex_cache,
8213 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008214 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008215 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008216
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008217 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008218 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008219 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008220 }
8221
Narayan Kamath25352fc2016-08-03 12:46:58 +01008222 StackHandleScope<4> hs(self);
8223
8224 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008225 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008226 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8227 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008228 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008229 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008230 DCHECK(self->IsExceptionPending());
8231 return nullptr;
8232 }
8233
8234 // Then resolve the argument types.
8235 //
8236 // TODO: Is there a better way to figure out the number of method arguments
8237 // other than by looking at the shorty ?
8238 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8239
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008240 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008241 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008242 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8243 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008244 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008245 DCHECK(self->IsExceptionPending());
8246 return nullptr;
8247 }
8248
8249 DexFileParameterIterator it(dex_file, proto_id);
8250 int32_t i = 0;
8251 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8252 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008253 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008254 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008255 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008256 DCHECK(self->IsExceptionPending());
8257 return nullptr;
8258 }
8259
8260 method_params->Set(i++, param_class.Get());
8261 }
8262
8263 DCHECK(!it.HasNext());
8264
8265 Handle<mirror::MethodType> type = hs.NewHandle(
8266 mirror::MethodType::Create(self, return_type, method_params));
8267 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8268
8269 return type.Get();
8270}
8271
Vladimir Markoaf940202017-12-08 15:01:18 +00008272ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008273 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008274 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008275 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008276 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8277 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008278 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008279}
8280
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008281mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8282 Thread* self,
8283 const DexFile::MethodHandleItem& method_handle,
8284 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008285 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008286 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8287 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008288 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008289 bool is_static;
8290 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008291 switch (handle_type) {
8292 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008293 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008294 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008295 is_static = true;
8296 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008297 break;
8298 }
8299 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008300 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008301 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008302 is_static = true;
8303 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008304 break;
8305 }
8306 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008307 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008308 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008309 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008310 num_params = 2;
8311 break;
8312 }
8313 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008314 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008315 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008316 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008317 num_params = 1;
8318 break;
8319 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008320 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008321 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008322 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008323 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008324 case DexFile::MethodHandleType::kInvokeInterface:
8325 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008326 }
8327
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008328 ArtField* target_field =
8329 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8330 if (LIKELY(target_field != nullptr)) {
8331 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8332 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8333 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8334 ThrowIllegalAccessErrorField(referring_class, target_field);
8335 return nullptr;
8336 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008337 if (UNLIKELY(is_put && target_field->IsFinal())) {
8338 ThrowIllegalAccessErrorField(referring_class, target_field);
8339 return nullptr;
8340 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008341 } else {
8342 DCHECK(Thread::Current()->IsExceptionPending());
8343 return nullptr;
8344 }
8345
8346 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008347 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8348 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8349 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8350 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008351 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008352 DCHECK(self->IsExceptionPending());
8353 return nullptr;
8354 }
8355
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008356 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008357 Handle<mirror::Class> return_type;
8358 switch (handle_type) {
8359 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008360 method_params->Set(0, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008361 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8362 break;
8363 }
8364 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008365 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008366 break;
8367 }
8368 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008369 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008370 method_params->Set(1, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008371 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8372 break;
8373 }
8374 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008375 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008376 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008377 break;
8378 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008379 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008380 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008381 case DexFile::MethodHandleType::kInvokeConstructor:
8382 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008383 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008384 UNREACHABLE();
8385 }
8386
8387 for (int32_t i = 0; i < num_params; ++i) {
8388 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8389 DCHECK(self->IsExceptionPending());
8390 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008391 }
8392 }
8393
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008394 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008395 DCHECK(self->IsExceptionPending());
8396 return nullptr;
8397 }
8398
8399 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008400 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8401 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008402 DCHECK(self->IsExceptionPending());
8403 return nullptr;
8404 }
Orion Hodson631827d2017-04-10 14:53:47 +01008405
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008406 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8407 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8408}
8409
8410mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8411 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008412 const DexFile::MethodHandleItem& method_handle,
8413 ArtMethod* referrer) {
8414 DexFile::MethodHandleType handle_type =
8415 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8416 mirror::MethodHandle::Kind kind;
8417 uint32_t receiver_count = 0;
8418 ArtMethod* target_method = nullptr;
8419 switch (handle_type) {
8420 case DexFile::MethodHandleType::kStaticPut:
8421 case DexFile::MethodHandleType::kStaticGet:
8422 case DexFile::MethodHandleType::kInstancePut:
8423 case DexFile::MethodHandleType::kInstanceGet:
8424 UNREACHABLE();
8425 case DexFile::MethodHandleType::kInvokeStatic: {
8426 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8427 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008428 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8429 method_handle.field_or_method_idx_,
8430 referrer,
8431 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008432 break;
8433 }
8434 case DexFile::MethodHandleType::kInvokeInstance: {
8435 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8436 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008437 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8438 method_handle.field_or_method_idx_,
8439 referrer,
8440 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008441 break;
8442 }
8443 case DexFile::MethodHandleType::kInvokeConstructor: {
8444 // Constructors are currently implemented as a transform. They
8445 // are special cased later in this method.
8446 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8447 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008448 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8449 method_handle.field_or_method_idx_,
8450 referrer,
8451 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008452 break;
8453 }
8454 case DexFile::MethodHandleType::kInvokeDirect: {
8455 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8456 receiver_count = 1;
8457 StackHandleScope<2> hs(self);
8458 // A constant method handle with type kInvokeDirect can refer to
8459 // a method that is private or to a method in a super class. To
8460 // disambiguate the two options, we resolve the method ignoring
8461 // the invocation type to determine if the method is private. We
8462 // then resolve again specifying the intended invocation type to
8463 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008464 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008465 hs.NewHandle(referrer->GetDexCache()),
8466 hs.NewHandle(referrer->GetClassLoader()));
8467 if (UNLIKELY(target_method == nullptr)) {
8468 break;
8469 }
8470
8471 if (target_method->IsPrivate()) {
8472 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008473 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8474 method_handle.field_or_method_idx_,
8475 referrer,
8476 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008477 } else {
8478 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008479 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8480 method_handle.field_or_method_idx_,
8481 referrer,
8482 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008483 if (UNLIKELY(target_method == nullptr)) {
8484 break;
8485 }
8486 // Find the method specified in the parent in referring class
8487 // so invoke-super invokes the method in the parent of the
8488 // referrer.
8489 target_method =
8490 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8491 kRuntimePointerSize);
8492 }
8493 break;
8494 }
8495 case DexFile::MethodHandleType::kInvokeInterface: {
8496 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8497 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008498 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8499 method_handle.field_or_method_idx_,
8500 referrer,
8501 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008502 break;
8503 }
Orion Hodson631827d2017-04-10 14:53:47 +01008504 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008505
8506 if (UNLIKELY(target_method == nullptr)) {
8507 DCHECK(Thread::Current()->IsExceptionPending());
8508 return nullptr;
8509 }
8510
8511 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8512 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8513 uint32_t access_flags = target_method->GetAccessFlags();
8514 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8515 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8516 return nullptr;
8517 }
8518
8519 // Calculate the number of parameters from the method shorty. We add the
8520 // receiver count (0 or 1) and deduct one for the return value.
8521 uint32_t shorty_length;
8522 target_method->GetShorty(&shorty_length);
8523 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8524
8525 StackHandleScope<7> hs(self);
8526 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8527 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8528 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8529 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8530 if (method_params.Get() == nullptr) {
8531 DCHECK(self->IsExceptionPending());
8532 return nullptr;
8533 }
8534
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008535 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008536 if (receiver_count != 0) {
8537 // Insert receiver
8538 method_params->Set(index++, target_method->GetDeclaringClass());
8539 }
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008540 DexFileParameterIterator it(*target_method->GetDexFile(), target_method->GetPrototype());
8541 Handle<mirror::DexCache> target_method_dex_cache(hs.NewHandle(target_method->GetDexCache()));
8542 Handle<mirror::ClassLoader> target_method_class_loader(hs.NewHandle(target_method->GetClassLoader()));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008543 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008544 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008545 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008546 ObjPtr<mirror::Class> klass = ResolveType(type_idx,
8547 target_method_dex_cache,
8548 target_method_class_loader);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008549 if (nullptr == klass) {
8550 DCHECK(self->IsExceptionPending());
8551 return nullptr;
8552 }
8553 method_params->Set(index++, klass);
8554 it.Next();
8555 }
8556
Vladimir Markob45528c2017-07-27 14:14:28 +01008557 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008558 if (UNLIKELY(return_type.IsNull())) {
8559 DCHECK(self->IsExceptionPending());
8560 return nullptr;
8561 }
8562
8563 Handle<mirror::MethodType>
8564 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8565 if (UNLIKELY(method_type.IsNull())) {
8566 DCHECK(self->IsExceptionPending());
8567 return nullptr;
8568 }
8569
8570 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8571 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8572 Handle<mirror::MethodHandlesLookup> lookup =
8573 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8574 return lookup->FindConstructor(self, constructor_class, method_type);
8575 }
8576
8577 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8578 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8579}
8580
Vladimir Markoaf940202017-12-08 15:01:18 +00008581ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8582 uint32_t method_handle_idx,
8583 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008584 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008585 const DexFile* const dex_file = referrer->GetDexFile();
8586 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8587 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8588 case DexFile::MethodHandleType::kStaticPut:
8589 case DexFile::MethodHandleType::kStaticGet:
8590 case DexFile::MethodHandleType::kInstancePut:
8591 case DexFile::MethodHandleType::kInstanceGet:
8592 return ResolveMethodHandleForField(self, method_handle, referrer);
8593 case DexFile::MethodHandleType::kInvokeStatic:
8594 case DexFile::MethodHandleType::kInvokeInstance:
8595 case DexFile::MethodHandleType::kInvokeConstructor:
8596 case DexFile::MethodHandleType::kInvokeDirect:
8597 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008598 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008599 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008600}
8601
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008602bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8603 return (entry_point == GetQuickResolutionStub()) ||
8604 (quick_resolution_trampoline_ == entry_point);
8605}
8606
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008607bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8608 return (entry_point == GetQuickToInterpreterBridge()) ||
8609 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8610}
8611
8612bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8613 return (entry_point == GetQuickGenericJniStub()) ||
8614 (quick_generic_jni_trampoline_ == entry_point);
8615}
8616
David Sehra49e0532017-08-25 08:05:29 -07008617bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8618 return entry_point == GetJniDlsymLookupStub();
8619}
8620
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008621const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8622 return GetQuickGenericJniStub();
8623}
8624
Mathieu Chartiere401d142015-04-22 13:56:20 -07008625void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008626 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008627 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8628 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008629 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008630 }
8631}
8632
Alex Lightdb01a092017-04-03 15:39:55 -07008633void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8634 DCHECK(method->IsObsolete());
8635 // We cannot mess with the entrypoints of native methods because they are used to determine how
8636 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8637 if (!method->IsNative()) {
8638 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8639 }
8640}
8641
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008642void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008643 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008644 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008645 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8646 << NumNonZygoteClasses() << "\n";
8647}
8648
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008649class CountClassesVisitor : public ClassLoaderVisitor {
8650 public:
8651 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8652
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008653 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008654 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008655 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008656 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008657 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8658 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008659 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008660 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008661
8662 size_t num_zygote_classes;
8663 size_t num_non_zygote_classes;
8664};
8665
8666size_t ClassLinker::NumZygoteClasses() const {
8667 CountClassesVisitor visitor;
8668 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008669 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008670}
8671
8672size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008673 CountClassesVisitor visitor;
8674 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008675 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008676}
8677
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008678size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008679 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008680 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008681 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008682}
8683
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008684pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008685 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008686}
8687
8688pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008689 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008690}
8691
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008692void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008693 DCHECK(!init_done_);
8694
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008695 DCHECK(klass != nullptr);
8696 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008697
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008698 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008699 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008700 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
8701 int32_t index = static_cast<int32_t>(class_root);
8702 DCHECK(class_roots->Get(index) == nullptr);
8703 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008704}
8705
Calin Juravle7865ac72017-06-28 11:03:12 -07008706jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
Andreas Gampe473191c2017-12-28 16:55:31 -08008707 const std::vector<const DexFile*>& dex_files,
8708 jclass loader_class,
8709 jobject parent_loader) {
Calin Juravle7865ac72017-06-28 11:03:12 -07008710 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8711 WellKnownClasses::dalvik_system_PathClassLoader) ||
8712 self->GetJniEnv()->IsSameObject(loader_class,
8713 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8714
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008715 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8716 // We could move the jobject to the callers, but all call-sites do this...
8717 ScopedObjectAccessUnchecked soa(self);
8718
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008719 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008720 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008721
Mathieu Chartierc7853442015-03-27 14:35:38 -07008722 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008723 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008724
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008725 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008726 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008727 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008728 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008729 mirror::ObjectArray<mirror::Object>::Alloc(self,
8730 dex_elements_class.Get(),
8731 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008732 Handle<mirror::Class> h_dex_element_class =
8733 hs.NewHandle(dex_elements_class->GetComponentType());
8734
Mathieu Chartierc7853442015-03-27 14:35:38 -07008735 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008736 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008737 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008738
Andreas Gampe08883de2016-11-08 13:20:52 -08008739 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00008740 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008741
Andreas Gampe08883de2016-11-08 13:20:52 -08008742 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00008743 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008744
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008745 // Fill the elements array.
8746 int32_t index = 0;
8747 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008748 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008749
Calin Juravle7865ac72017-06-28 11:03:12 -07008750 // CreateWellKnownClassLoader is only used by gtests and compiler.
8751 // 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 -07008752 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8753 self,
8754 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008755 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008756 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008757
Mathieu Chartier3738e982017-05-12 16:07:28 -07008758 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8759 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008760 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008761 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008762 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008763 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008764
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008765 Handle<mirror::String> h_file_name = hs2.NewHandle(
8766 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008767 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008768 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8769
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008770 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008771 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008772 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008773
8774 h_dex_elements->Set(index, h_element.Get());
8775 index++;
8776 }
8777 DCHECK_EQ(index, h_dex_elements->GetLength());
8778
8779 // Create DexPathList.
8780 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008781 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008782 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008783 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008784 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08008785 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
8786 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
8787 // elements.
8788 {
8789 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
8790 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
8791 DCHECK(native_lib_dirs != nullptr);
8792 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
8793 DCHECK(list_class != nullptr);
8794 {
8795 StackHandleScope<1> h_list_scope(self);
8796 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
8797 bool list_init = EnsureInitialized(self, h_list_class, true, true);
8798 DCHECK(list_init);
8799 list_class = h_list_class.Get();
8800 }
8801 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
8802 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
8803 // is fine for testing. While it violates a Java-code invariant (the elementData field is
8804 // normally never null), as long as one does not try to add elements, this will still
8805 // work.
8806 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
8807 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008808
Calin Juravle7865ac72017-06-28 11:03:12 -07008809 // Create the class loader..
8810 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8811 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8812 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008813 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008814 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008815 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008816 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008817 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008818
8819 // Make a pretend boot-classpath.
8820 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008821 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008822 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008823 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008824 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008825 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008826 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008827
8828 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8829 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8830 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8831 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008832
8833 // Make it a global ref and return.
8834 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008835 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008836 return soa.Env()->NewGlobalRef(local_ref.get());
8837}
8838
Calin Juravle7865ac72017-06-28 11:03:12 -07008839jobject ClassLinker::CreatePathClassLoader(Thread* self,
8840 const std::vector<const DexFile*>& dex_files) {
8841 return CreateWellKnownClassLoader(self,
8842 dex_files,
8843 WellKnownClasses::dalvik_system_PathClassLoader,
8844 nullptr);
8845}
8846
Andreas Gampe8ac75952015-06-02 21:01:45 -07008847void ClassLinker::DropFindArrayClassCache() {
8848 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8849 find_array_class_cache_next_victim_ = 0;
8850}
8851
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008852void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008853 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008854 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008855 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008856 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8857 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008858 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008859 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008860 }
8861 }
8862}
8863
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03008864void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
8865 for (const ClassLoaderData& data : class_loaders_) {
8866 LinearAlloc* alloc = data.allocator;
8867 if (alloc != nullptr && !visitor->Visit(alloc)) {
8868 break;
8869 }
8870 }
8871}
8872
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008873void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8874 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008875 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008876 Thread* const self = Thread::Current();
8877 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008878 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008879 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008880 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008881 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8882 // class table was modified.
8883 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8884 }
8885}
8886
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008887void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008888 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008889 std::vector<ClassLoaderData> to_delete;
8890 // Do the delete outside the lock to avoid lock violation in jit code cache.
8891 {
8892 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8893 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8894 const ClassLoaderData& data = *it;
8895 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008896 ObjPtr<mirror::ClassLoader> class_loader =
8897 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008898 if (class_loader != nullptr) {
8899 ++it;
8900 } else {
8901 VLOG(class_linker) << "Freeing class loader";
8902 to_delete.push_back(data);
8903 it = class_loaders_.erase(it);
8904 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008905 }
8906 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008907 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03008908 // CHA unloading analysis and SingleImplementaion cleanups are required.
8909 DeleteClassLoader(self, data, true /*cleanup_cha*/);
Mathieu Chartier65975772016-08-05 10:46:36 -07008910 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008911}
8912
Vladimir Marko21300532017-01-24 18:06:55 +00008913class GetResolvedClassesVisitor : public ClassVisitor {
8914 public:
8915 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8916 : result_(result),
8917 ignore_boot_classes_(ignore_boot_classes),
8918 last_resolved_classes_(result->end()),
8919 last_dex_file_(nullptr),
8920 vlog_is_on_(VLOG_IS_ON(class_linker)),
8921 extra_stats_(),
8922 last_extra_stats_(extra_stats_.end()) { }
8923
8924 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8925 if (!klass->IsProxyClass() &&
8926 !klass->IsArrayClass() &&
8927 klass->IsResolved() &&
8928 !klass->IsErroneousResolved() &&
8929 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8930 const DexFile& dex_file = klass->GetDexFile();
8931 if (&dex_file != last_dex_file_) {
8932 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008933 DexCacheResolvedClasses resolved_classes(
8934 dex_file.GetLocation(),
8935 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8936 dex_file.GetLocationChecksum(),
8937 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008938 last_resolved_classes_ = result_->find(resolved_classes);
8939 if (last_resolved_classes_ == result_->end()) {
8940 last_resolved_classes_ = result_->insert(resolved_classes).first;
8941 }
8942 }
8943 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8944 if (UNLIKELY(vlog_is_on_) && added) {
8945 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8946 if (last_extra_stats_ == extra_stats_.end() ||
8947 last_extra_stats_->first != resolved_classes) {
8948 last_extra_stats_ = extra_stats_.find(resolved_classes);
8949 if (last_extra_stats_ == extra_stats_.end()) {
8950 last_extra_stats_ =
8951 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8952 }
8953 }
8954 }
8955 }
8956 return true;
8957 }
8958
8959 void PrintStatistics() const {
8960 if (vlog_is_on_) {
8961 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8962 auto it = extra_stats_.find(std::addressof(resolved_classes));
8963 DCHECK(it != extra_stats_.end());
8964 const ExtraStats& extra_stats = it->second;
8965 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8966 << " has " << resolved_classes.GetClasses().size() << " / "
8967 << extra_stats.number_of_class_defs_ << " resolved classes";
8968 }
8969 }
8970 }
8971
8972 private:
8973 struct ExtraStats {
8974 explicit ExtraStats(uint32_t number_of_class_defs)
8975 : number_of_class_defs_(number_of_class_defs) {}
8976 uint32_t number_of_class_defs_;
8977 };
8978
8979 std::set<DexCacheResolvedClasses>* result_;
8980 bool ignore_boot_classes_;
8981 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8982 const DexFile* last_dex_file_;
8983
8984 // Statistics.
8985 bool vlog_is_on_;
8986 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8987 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8988};
8989
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008990std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008991 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008992 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008993 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008994 std::set<DexCacheResolvedClasses> ret;
8995 VLOG(class_linker) << "Collecting resolved classes";
8996 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008997 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8998 VisitClasses(&visitor);
8999 if (VLOG_IS_ON(class_linker)) {
9000 visitor.PrintStatistics();
9001 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009002 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009003 return ret;
9004}
9005
Mathieu Chartier65975772016-08-05 10:46:36 -07009006class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9007 public:
9008 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9009 : method_(method),
9010 pointer_size_(pointer_size) {}
9011
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009012 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07009013 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9014 holder_ = klass;
9015 }
9016 // Return false to stop searching if holder_ is not null.
9017 return holder_ == nullptr;
9018 }
9019
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009020 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009021 const ArtMethod* const method_;
9022 const PointerSize pointer_size_;
9023};
9024
9025mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
9026 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9027 CHECK(method->IsCopied());
9028 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9029 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009030 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07009031}
9032
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009033mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9034 return down_cast<mirror::IfTable*>(
9035 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009036 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009037 ifcount * mirror::IfTable::kMax));
9038}
9039
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009040// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009041template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009042 uint32_t method_idx,
9043 Handle<mirror::DexCache> dex_cache,
9044 Handle<mirror::ClassLoader> class_loader,
9045 ArtMethod* referrer,
9046 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009047template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009048 uint32_t method_idx,
9049 Handle<mirror::DexCache> dex_cache,
9050 Handle<mirror::ClassLoader> class_loader,
9051 ArtMethod* referrer,
9052 InvokeType type);
9053
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009054} // namespace art