blob: 6daad88a4887306a33839492abe2cc913a7b76ef [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 Sehr8f4b0562018-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 Sehr8f4b0562018-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"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070054#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000055#include "compiler_callbacks.h"
Vladimir Marko45310912018-04-05 14:49:24 +010056#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080057#include "debugger.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080058#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080059#include "dex/dex_file-inl.h"
60#include "dex/dex_file_exception_helpers.h"
61#include "dex/dex_file_loader.h"
David Sehr0225f8e2018-01-31 08:52:24 +000062#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070063#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070064#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070065#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070066#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080067#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000068#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070069#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070070#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070071#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070072#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000073#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070074#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070075#include "handle_scope-inl.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070076#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080077#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070078#include "imt_conflict_table.h"
79#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070080#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070081#include "interpreter/interpreter.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070082#include "java_vm_ext.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"
Calin Juravle33083d62017-01-18 15:29:12 -080086#include "jit/profile_compilation_info.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080087#include "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"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700119#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800120#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700121#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700122#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700123#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700124#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100125#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800126#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700127#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700128
129namespace art {
130
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800131using android::base::StringPrintf;
132
Mathieu Chartierc7853442015-03-27 14:35:38 -0700133static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700134static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700135
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700136static void ThrowNoClassDefFoundError(const char* fmt, ...)
137 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700138 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700139static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700140 va_list args;
141 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000143 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800144 va_end(args);
145}
146
Andreas Gampe99babb62015-11-02 16:20:00 -0800147static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700148 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700149 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700150 StackHandleScope<1> hs(self);
151 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700152 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700153 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700154
155 if (exception_class == nullptr) {
156 // No exc class ~ no <init>-with-string.
157 CHECK(self->IsExceptionPending());
158 self->ClearException();
159 return false;
160 }
161
Vladimir Markoba118822017-06-12 15:41:56 +0100162 ArtMethod* exception_init_method = exception_class->FindConstructor(
163 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700164 return exception_init_method != nullptr;
165}
166
Alex Lightd6251582016-10-31 11:12:30 -0700167static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700168 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700169 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
170 if (ext == nullptr) {
171 return nullptr;
172 } else {
173 return ext->GetVerifyError();
174 }
175}
176
177// Helper for ThrowEarlierClassFailure. Throws the stored error.
178static void HandleEarlierVerifyError(Thread* self,
179 ClassLinker* class_linker,
180 ObjPtr<mirror::Class> c)
181 REQUIRES_SHARED(Locks::mutator_lock_) {
182 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800183 DCHECK(obj != nullptr);
184 self->AssertNoPendingException();
185 if (obj->IsClass()) {
186 // Previous error has been stored as class. Create a new exception of that type.
187
188 // It's possible the exception doesn't have a <init>(String).
189 std::string temp;
190 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
191
192 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700193 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800194 } else {
195 self->ThrowNewException(descriptor, nullptr);
196 }
197 } else {
198 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700199 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800200 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700201 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800202 CHECK(throwable_class->IsAssignableFrom(error_class));
203 self->SetException(obj->AsThrowable());
204 }
205 self->AssertPendingException();
206}
207
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700208void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700209 // The class failed to initialize on a previous attempt, so we want to throw
210 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
211 // failed in verification, in which case v2 5.4.1 says we need to re-throw
212 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800213 Runtime* const runtime = Runtime::Current();
214 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700215 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700216 if (GetVerifyError(c) != nullptr) {
217 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800218 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700219 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800220 } else {
221 extra = verify_error->AsThrowable()->Dump();
222 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700223 }
David Sehr709b0702016-10-13 09:12:37 -0700224 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
225 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700226 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700227
David Sehr709b0702016-10-13 09:12:37 -0700228 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800229 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800230 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700231 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700232 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000233 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700234 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700235 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800236 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800237 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800238 }
Alex Lightd6251582016-10-31 11:12:30 -0700239 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
240 // might have meant to go down the earlier if statement with the original error but it got
241 // swallowed by the OOM so we end up here.
242 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800243 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
244 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
245 // exception will be a cause.
246 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700247 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700248 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700249 }
250}
251
Brian Carlstromb23eab12014-10-08 17:55:21 -0700252static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700253 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700254 if (VLOG_IS_ON(class_linker)) {
255 std::string temp;
256 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000257 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700258 }
259}
260
261static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700262 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700263 Thread* self = Thread::Current();
264 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700265
266 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700267 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700268
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800269 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
270 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
271 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800272 std::string tmp;
Alex Lightcfda88f2018-02-26 10:09:39 -0800273 LOG(kIsDebugBuild ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
274 << " failed initialization: "
275 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800276 }
277
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700278 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700279 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
280 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700281
Elliott Hughesa4f94742012-05-29 16:28:38 -0700282 // We only wrap non-Error exceptions; an Error can just be used as-is.
283 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000284 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700285 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700286 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700287}
288
Fred Shih381e4ca2014-08-25 17:24:27 -0700289// Gap between two fields in object layout.
290struct FieldGap {
291 uint32_t start_offset; // The offset from the start of the object.
292 uint32_t size; // The gap size of 1, 2, or 4 bytes.
293};
294struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800295 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700296 }
297 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
298 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800299 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700300 // Note that the priority queue returns the largest element, so operator()
301 // should return true if lhs is less than rhs.
302 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700303 }
304};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700305typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700306
307// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800308static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700309 DCHECK(gaps != nullptr);
310
311 uint32_t current_offset = gap_start;
312 while (current_offset != gap_end) {
313 size_t remaining = gap_end - current_offset;
314 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
315 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
316 current_offset += sizeof(uint32_t);
317 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
318 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
319 current_offset += sizeof(uint16_t);
320 } else {
321 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
322 current_offset += sizeof(uint8_t);
323 }
324 DCHECK_LE(current_offset, gap_end) << "Overran gap";
325 }
326}
327// Shuffle fields forward, making use of gaps whenever possible.
328template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000329static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700330 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700331 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700332 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700333 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700334 DCHECK(current_field_idx != nullptr);
335 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700336 DCHECK(gaps != nullptr);
337 DCHECK(field_offset != nullptr);
338
339 DCHECK(IsPowerOfTwo(n));
340 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700341 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700342 Primitive::Type type = field->GetTypeAsPrimitiveType();
343 if (Primitive::ComponentSize(type) < n) {
344 break;
345 }
346 if (!IsAligned<n>(field_offset->Uint32Value())) {
347 MemberOffset old_offset = *field_offset;
348 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
349 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
350 }
David Sehr709b0702016-10-13 09:12:37 -0700351 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700352 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700353 if (!gaps->empty() && gaps->top().size >= n) {
354 FieldGap gap = gaps->top();
355 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100356 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700357 field->SetOffset(MemberOffset(gap.start_offset));
358 if (gap.size > n) {
359 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
360 }
361 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100362 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700363 field->SetOffset(*field_offset);
364 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
365 }
366 ++(*current_field_idx);
367 }
368}
369
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800370ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700371 : boot_class_table_(new ClassTable()),
372 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800373 class_roots_(nullptr),
374 array_iftable_(nullptr),
375 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700376 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000377 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700378 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800379 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800380 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100381 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800382 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700383 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700384 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
385 // For CHA disabled during Aot, see b/34193647.
386
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700387 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700388 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
389 "Array cache size wrong.");
390 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700391}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700392
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800393void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700394 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800395 if (c2 == nullptr) {
396 LOG(FATAL) << "Could not find class " << descriptor;
397 UNREACHABLE();
398 }
399 if (c1.Get() != c2) {
400 std::ostringstream os1, os2;
401 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
402 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
403 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
404 << ". This is most likely the result of a broken build. Make sure that "
405 << "libcore and art projects match.\n\n"
406 << os1.str() << "\n\n" << os2.str();
407 UNREACHABLE();
408 }
409}
410
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800411bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
412 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800413 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700414
Mathieu Chartiere401d142015-04-22 13:56:20 -0700415 Thread* const self = Thread::Current();
416 Runtime* const runtime = Runtime::Current();
417 gc::Heap* const heap = runtime->GetHeap();
418
Jeff Haodcdc85b2015-12-04 14:06:18 -0800419 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700420 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700421
Mathieu Chartiere401d142015-04-22 13:56:20 -0700422 // Use the pointer size from the runtime since we are probably creating the image.
423 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
424
Elliott Hughes30646832011-10-13 16:59:46 -0700425 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700426 // 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 -0800427 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700428 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700429 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700430 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700431 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800432 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700433 mirror::Class::SetClassClass(java_lang_Class.Get());
434 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700435 if (kUseBakerReadBarrier) {
436 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800437 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700438 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700439 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800440 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700441 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700442
Elliott Hughes418d20f2011-09-22 14:00:39 -0700443 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700444 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700445 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700447 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700448
Ian Rogers23435d02012-09-24 11:23:12 -0700449 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700450 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700451 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800452 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700453 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700454 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000455 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700456
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700457 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800458 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
459 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
460 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
461 java_lang_Object.Get(),
462 java_lang_Object->GetObjectSize(),
463 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700464
Igor Murashkin86083f72017-10-27 10:59:04 -0700465 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000466 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700467 // It might seem the lock here is unnecessary, however all the SubtypeCheck
468 // functions are annotated to require locks all the way down.
469 //
470 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
471 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000472 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
473 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700474 }
475
Ian Rogers23435d02012-09-24 11:23:12 -0700476 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700477 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478 AllocClass(self, java_lang_Class.Get(),
479 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700480 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700481
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700482 // Setup the char (primitive) class to be used for char[].
483 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700484 AllocClass(self, java_lang_Class.Get(),
485 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700486 // The primitive char class won't be initialized by
487 // InitializePrimitiveClass until line 459, but strings (and
488 // internal char arrays) will be allocated before that and the
489 // component size, which is computed from the primitive type, needs
490 // to be set here.
491 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700492
Ian Rogers23435d02012-09-24 11:23:12 -0700493 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700494 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700495 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700496 char_array_class->SetComponentType(char_class.Get());
497 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700500 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700501 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700502 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700503 mirror::String::SetClass(java_lang_String.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000504 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400505
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700506 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700507 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700508 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700509 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
510 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000511 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700512
Ian Rogers23435d02012-09-24 11:23:12 -0700513 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700514 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700515 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
516 kClassRootsMax));
517 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700518 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
519 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
520 SetClassRoot(kClassArrayClass, class_array_class.Get());
521 SetClassRoot(kObjectArrayClass, object_array_class.Get());
522 SetClassRoot(kCharArrayClass, char_array_class.Get());
523 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700524 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525
Mathieu Chartier6beced42016-11-15 15:51:31 -0800526 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
527 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
528
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700530 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
531 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
532 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
533 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
534 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
535 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
536 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
537 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700538
Ian Rogers23435d02012-09-24 11:23:12 -0700539 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700540 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700541
Ian Rogers23435d02012-09-24 11:23:12 -0700542 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700543 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700544 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700546 mirror::IntArray::SetArrayClass(int_array_class.Get());
547 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700548
Mathieu Chartierc7853442015-03-27 14:35:38 -0700549 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
550 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700551 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700552 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
553 mirror::LongArray::SetArrayClass(long_array_class.Get());
554 SetClassRoot(kLongArrayClass, long_array_class.Get());
555
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700556 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700557
Ian Rogers52813c92012-10-11 11:50:38 -0700558 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700559 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700560 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700561 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100562 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700563 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000564 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700565
Alex Lightd6251582016-10-31 11:12:30 -0700566
567 // Setup dalvik.system.ClassExt
568 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
569 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
570 SetClassRoot(kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
571 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000572 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700573
Mathieu Chartier66f19252012-09-18 08:57:04 -0700574 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700575 Handle<mirror::Class> object_array_string(hs.NewHandle(
576 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700577 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700578 object_array_string->SetComponentType(java_lang_String.Get());
579 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700580
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000581 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700582 // Create runtime resolution and imt conflict methods.
583 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000584 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
585 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700586
Ian Rogers23435d02012-09-24 11:23:12 -0700587 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
588 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
589 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800590 if (boot_class_path.empty()) {
591 *error_msg = "Boot classpath is empty.";
592 return false;
593 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800594 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800595 if (dex_file.get() == nullptr) {
596 *error_msg = "Null dex file.";
597 return false;
598 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700599 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800600 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700601 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602
603 // now we can use FindSystemClass
604
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700605 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700606 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
607 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700608
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700609 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
610 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700611 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800612 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700613 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700614 quick_resolution_trampoline_ = GetQuickResolutionStub();
615 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
616 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700617 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700618
Alex Lightd6251582016-10-31 11:12:30 -0700619 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000620 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800621 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700622 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000623 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800624 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000625 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800626 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700627 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000628 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700629 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
630 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700631
Ian Rogers23435d02012-09-24 11:23:12 -0700632 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800633 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800634 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700635
Ian Rogers98379392014-02-24 16:53:16 -0800636 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800637 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700638
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800639 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700640
Ian Rogers98379392014-02-24 16:53:16 -0800641 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800642 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700643
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800644 CheckSystemClass(self, int_array_class, "[I");
645 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700646
Ian Rogers98379392014-02-24 16:53:16 -0800647 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800648 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Ian Rogers98379392014-02-24 16:53:16 -0800650 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800651 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800653 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
654 // in class_table_.
655 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700656
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800657 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
658 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659
Ian Rogers23435d02012-09-24 11:23:12 -0700660 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700661 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800662 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700663 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800664 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700665 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
666 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700667 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
668 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700669
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700670 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
671 // suspension.
672 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000673 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700674 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000675 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700676 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000677 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700678 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000679 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700680
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700681 CHECK_EQ(object_array_string.Get(),
682 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700683
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800684 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700685
Ian Rogers23435d02012-09-24 11:23:12 -0700686 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700687 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700688
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700689 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700690 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
691 CHECK(class_root != nullptr);
692 SetClassRoot(kJavaLangReflectField, class_root);
693 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700694
695 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700696 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
697 CHECK(class_root != nullptr);
698 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
699 mirror::Field::SetArrayClass(class_root);
700
701 // Create java.lang.reflect.Constructor.class root and array root.
702 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
703 CHECK(class_root != nullptr);
704 SetClassRoot(kJavaLangReflectConstructor, class_root);
705 mirror::Constructor::SetClass(class_root);
706 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
707 CHECK(class_root != nullptr);
708 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
709 mirror::Constructor::SetArrayClass(class_root);
710
711 // Create java.lang.reflect.Method.class root and array root.
712 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
713 CHECK(class_root != nullptr);
714 SetClassRoot(kJavaLangReflectMethod, class_root);
715 mirror::Method::SetClass(class_root);
716 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
717 CHECK(class_root != nullptr);
718 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
719 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700720
Orion Hodson005ac512017-10-24 15:43:43 +0100721 // Create java.lang.invoke.CallSite.class root
722 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
723 CHECK(class_root != nullptr);
724 SetClassRoot(kJavaLangInvokeCallSite, class_root);
725 mirror::CallSite::SetClass(class_root);
726
Narayan Kamathafa48272016-08-03 12:46:58 +0100727 // Create java.lang.invoke.MethodType.class root
728 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
729 CHECK(class_root != nullptr);
730 SetClassRoot(kJavaLangInvokeMethodType, class_root);
731 mirror::MethodType::SetClass(class_root);
732
733 // Create java.lang.invoke.MethodHandleImpl.class root
734 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
735 CHECK(class_root != nullptr);
736 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
737 mirror::MethodHandleImpl::SetClass(class_root);
738
Orion Hodsonc069a302017-01-18 09:23:12 +0000739 // Create java.lang.invoke.MethodHandles.Lookup.class root
740 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
741 CHECK(class_root != nullptr);
742 SetClassRoot(kJavaLangInvokeMethodHandlesLookup, class_root);
743 mirror::MethodHandlesLookup::SetClass(class_root);
744
Orion Hodson005ac512017-10-24 15:43:43 +0100745 // Create java.lang.invoke.VarHandle.class root
746 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000747 CHECK(class_root != nullptr);
Orion Hodson005ac512017-10-24 15:43:43 +0100748 SetClassRoot(kJavaLangInvokeVarHandle, class_root);
749 mirror::VarHandle::SetClass(class_root);
750
751 // Create java.lang.invoke.FieldVarHandle.class root
752 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
753 CHECK(class_root != nullptr);
754 SetClassRoot(kJavaLangInvokeFieldVarHandle, class_root);
755 mirror::FieldVarHandle::SetClass(class_root);
756
757 // Create java.lang.invoke.ArrayElementVarHandle.class root
758 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
759 CHECK(class_root != nullptr);
760 SetClassRoot(kJavaLangInvokeArrayElementVarHandle, class_root);
761 mirror::ArrayElementVarHandle::SetClass(class_root);
762
763 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
764 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
765 CHECK(class_root != nullptr);
766 SetClassRoot(kJavaLangInvokeByteArrayViewVarHandle, class_root);
767 mirror::ByteArrayViewVarHandle::SetClass(class_root);
768
769 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
770 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
771 CHECK(class_root != nullptr);
772 SetClassRoot(kJavaLangInvokeByteBufferViewVarHandle, class_root);
773 mirror::ByteBufferViewVarHandle::SetClass(class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000774
Narayan Kamath000e1882016-10-24 17:14:25 +0100775 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
776 CHECK(class_root != nullptr);
777 SetClassRoot(kDalvikSystemEmulatedStackFrame, class_root);
778 mirror::EmulatedStackFrame::SetClass(class_root);
779
Brian Carlstrom1f870082011-08-23 16:02:11 -0700780 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700781 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000782 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800783 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700784 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700785 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
786 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700787 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700788 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700789 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700790 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700791 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700792 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700793 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700794 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700795 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700796 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700797 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700798 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700799
Ian Rogers23435d02012-09-24 11:23:12 -0700800 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700801 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700802 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700803 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
804 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700805
jeffhao8cd6dda2012-02-22 10:15:34 -0800806 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700807 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800808 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800809 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700810 SetClassRoot(kJavaLangClassNotFoundException,
811 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800812 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700813 SetClassRoot(kJavaLangStackTraceElementArrayClass,
814 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800815 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700816
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700817 // Create conflict tables that depend on the class linker.
818 runtime->FixupConflictTables();
819
Ian Rogers98379392014-02-24 16:53:16 -0800820 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700821
Brian Carlstroma004aa92012-02-08 18:05:09 -0800822 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800823
824 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700825}
826
Ian Rogers98379392014-02-24 16:53:16 -0800827void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800828 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700829
830 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700831 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700832 // as the types of the field can't be resolved prior to the runtime being
833 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700834 StackHandleScope<2> hs(self);
835 Handle<mirror::Class> java_lang_ref_Reference = hs.NewHandle(GetClassRoot(kJavaLangRefReference));
836 Handle<mirror::Class> java_lang_ref_FinalizerReference =
837 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800838
Mathieu Chartierc7853442015-03-27 14:35:38 -0700839 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700840 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
841 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700842
Mathieu Chartierc7853442015-03-27 14:35:38 -0700843 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700844 CHECK_STREQ(queue->GetName(), "queue");
845 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700846
Mathieu Chartierc7853442015-03-27 14:35:38 -0700847 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700848 CHECK_STREQ(queueNext->GetName(), "queueNext");
849 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700850
Mathieu Chartierc7853442015-03-27 14:35:38 -0700851 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700852 CHECK_STREQ(referent->GetName(), "referent");
853 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700854
Mathieu Chartierc7853442015-03-27 14:35:38 -0700855 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700856 CHECK_STREQ(zombie->GetName(), "zombie");
857 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700858
Brian Carlstroma663ea52011-08-19 23:33:41 -0700859 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700860 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700861 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700862 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700863 CHECK(klass != nullptr);
864 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700865 // note SetClassRoot does additional validation.
866 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700867 }
868
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700869 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700870
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700871 // disable the slow paths in FindClass and CreatePrimitiveClass now
872 // that Object, Class, and Object[] are setup
873 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700874
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800875 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700876}
877
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700878void ClassLinker::RunRootClinits() {
879 Thread* self = Thread::Current();
880 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700881 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700882 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700883 StackHandleScope<1> hs(self);
884 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700885 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700886 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700887 }
888 }
889}
890
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200891// Set image methods' entry point to interpreter.
892class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
893 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700894 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200895 : image_pointer_size_(image_pointer_size) {}
896
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700897 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200898 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
899 CHECK(method->GetDeclaringClass() != nullptr);
900 }
901 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
902 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
903 image_pointer_size_);
904 }
905 }
906
907 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700908 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200909
910 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
911};
912
Jeff Haodcdc85b2015-12-04 14:06:18 -0800913struct TrampolineCheckData {
914 const void* quick_resolution_trampoline;
915 const void* quick_imt_conflict_trampoline;
916 const void* quick_generic_jni_trampoline;
917 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700918 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800919 ArtMethod* m;
920 bool error;
921};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800922
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800923bool ClassLinker::InitFromBootImage(std::string* error_msg) {
924 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700925 CHECK(!init_done_);
926
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700927 Runtime* const runtime = Runtime::Current();
928 Thread* const self = Thread::Current();
929 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800930 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
931 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700932 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
933 if (!ValidPointerSize(pointer_size_unchecked)) {
934 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800935 return false;
936 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700937 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800938 if (!runtime->IsAotCompiler()) {
939 // Only the Aot compiler supports having an image with a different pointer size than the
940 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
941 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700942 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800943 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700944 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800945 sizeof(void*));
946 return false;
947 }
948 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800949 std::vector<const OatFile*> oat_files =
950 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
951 DCHECK(!oat_files.empty());
952 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800953 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
954 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700955 GetStoreValueByKey(OatHeader::kImageLocationKey);
956 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800957 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
958 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
959 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
960 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
961 if (kIsDebugBuild) {
962 // Check that the other images use the same trampoline.
963 for (size_t i = 1; i < oat_files.size(); ++i) {
964 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
965 const void* ith_quick_resolution_trampoline =
966 ith_oat_header.GetQuickResolutionTrampoline();
967 const void* ith_quick_imt_conflict_trampoline =
968 ith_oat_header.GetQuickImtConflictTrampoline();
969 const void* ith_quick_generic_jni_trampoline =
970 ith_oat_header.GetQuickGenericJniTrampoline();
971 const void* ith_quick_to_interpreter_bridge_trampoline =
972 ith_oat_header.GetQuickToInterpreterBridge();
973 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
974 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
975 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
976 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
977 // Make sure that all methods in this image do not contain those trampolines as
978 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
979 TrampolineCheckData data;
980 data.error = false;
981 data.pointer_size = GetImagePointerSize();
982 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
983 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
984 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
985 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
986 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700987 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
988 if (obj->IsClass()) {
989 ObjPtr<mirror::Class> klass = obj->AsClass();
990 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
991 const void* entrypoint =
992 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
993 if (entrypoint == data.quick_resolution_trampoline ||
994 entrypoint == data.quick_imt_conflict_trampoline ||
995 entrypoint == data.quick_generic_jni_trampoline ||
996 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
997 data.m = &m;
998 data.error = true;
999 return;
1000 }
1001 }
1002 }
1003 };
1004 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001005 if (data.error) {
1006 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001007 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001008 *error_msg = "Found an ArtMethod with a bad entrypoint";
1009 return false;
1010 }
1011 }
1012 }
1013 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001014
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001015 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1016 down_cast<mirror::ObjectArray<mirror::Class>*>(
1017 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
1018 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001019
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001020 // Special case of setting up the String class early so that we can test arbitrary objects
1021 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001022 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001023
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001024 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001025 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001026 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1027 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001028 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1029 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001030
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001031 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001032 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001033 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001034 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001035 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1036 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001037 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1038 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1039 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1040 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Orion Hodson005ac512017-10-24 15:43:43 +01001041 mirror::CallSite::SetClass(GetClassRoot(kJavaLangInvokeCallSite));
Narayan Kamathafa48272016-08-03 12:46:58 +01001042 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Orion Hodsonc069a302017-01-18 09:23:12 +00001043 mirror::MethodHandlesLookup::SetClass(GetClassRoot(kJavaLangInvokeMethodHandlesLookup));
Orion Hodson005ac512017-10-24 15:43:43 +01001044 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
1045 mirror::VarHandle::SetClass(GetClassRoot(kJavaLangInvokeVarHandle));
1046 mirror::FieldVarHandle::SetClass(GetClassRoot(kJavaLangInvokeFieldVarHandle));
1047 mirror::ArrayElementVarHandle::SetClass(GetClassRoot(kJavaLangInvokeArrayElementVarHandle));
1048 mirror::ByteArrayViewVarHandle::SetClass(GetClassRoot(kJavaLangInvokeByteArrayViewVarHandle));
1049 mirror::ByteBufferViewVarHandle::SetClass(GetClassRoot(kJavaLangInvokeByteBufferViewVarHandle));
Fred Shih4ee7a662014-07-11 09:59:27 -07001050 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001051 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1052 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1053 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1054 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1055 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1056 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1057 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1058 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1059 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1060 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Narayan Kamath000e1882016-10-24 17:14:25 +01001061 mirror::EmulatedStackFrame::SetClass(GetClassRoot(kDalvikSystemEmulatedStackFrame));
Alex Lightd6251582016-10-31 11:12:30 -07001062 mirror::ClassExt::SetClass(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001063
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001064 for (gc::space::ImageSpace* image_space : spaces) {
1065 // Boot class loader, use a null handle.
1066 std::vector<std::unique_ptr<const DexFile>> dex_files;
1067 if (!AddImageSpace(image_space,
1068 ScopedNullHandle<mirror::ClassLoader>(),
1069 /*dex_elements*/nullptr,
1070 /*dex_location*/nullptr,
1071 /*out*/&dex_files,
1072 error_msg)) {
1073 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 // Append opened dex files at the end.
1076 boot_dex_files_.insert(boot_dex_files_.end(),
1077 std::make_move_iterator(dex_files.begin()),
1078 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001079 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001080 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1081 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1082 }
Ian Rogers98379392014-02-24 16:53:16 -08001083 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001084
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001085 VLOG(startup) << __FUNCTION__ << " exiting";
1086 return true;
1087}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001088
Jeff Hao5872d7c2016-04-27 11:07:41 -07001089bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001090 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001091 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001092 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1093 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001094}
1095
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001096static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1097 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001098 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001099 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001100 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001101 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001102 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001103 DCHECK(dex_file_field != nullptr);
1104 DCHECK(dex_file_name_field != nullptr);
1105 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001106 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001107 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001108 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001109 // Null dex file means it was probably a jar with no dex files, return a null string.
1110 *out_name = nullptr;
1111 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001113 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001115 *out_name = name_object->AsString();
1116 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001118 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001119}
1120
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001121static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001122 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001123 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001124 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 DCHECK(out_dex_file_names != nullptr);
1126 DCHECK(error_msg != nullptr);
1127 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampee8320ea2018-02-20 18:24:55 -08001128 StackHandleScope<1> hs(soa.Self());
1129 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Jeff Hao5872d7c2016-04-27 11:07:41 -07001130 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001131 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1132 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001133 *error_msg = StringPrintf("Unknown class loader type %s",
1134 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001135 // Unsupported class loader.
1136 return false;
1137 }
Andreas Gampee8320ea2018-02-20 18:24:55 -08001138 // Get element names. Sets error to true on failure.
1139 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1140 REQUIRES_SHARED(Locks::mutator_lock_) {
1141 if (element == nullptr) {
1142 *error_msg = "Null dex element";
1143 *error = true; // Null element is a critical error.
1144 return false; // Had an error, stop the visit.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001145 }
Andreas Gampee8320ea2018-02-20 18:24:55 -08001146 ObjPtr<mirror::String> name;
1147 if (!GetDexPathListElementName(element, &name)) {
1148 *error_msg = "Invalid dex path list element";
1149 *error = false; // Invalid element is not a critical error.
1150 return false; // Stop the visit.
1151 }
1152 if (name != nullptr) {
1153 out_dex_file_names->push_front(name.Ptr());
1154 }
1155 return true; // Continue with the next Element.
1156 };
1157 bool error = VisitClassLoaderDexElements(soa, handle, add_element_names, /* error */ false);
1158 if (error) {
1159 // An error occurred during DexPathList Element visiting.
1160 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001161 }
1162 class_loader = class_loader->GetParent();
1163 }
1164 return true;
1165}
1166
Alexey Grebenkinab2ce842018-02-01 19:09:59 +03001167class CHAOnDeleteUpdateClassVisitor {
1168 public:
1169 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1170 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1171 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1172 self_(Thread::Current()) {}
1173
1174 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1175 // This class is going to be unloaded. Tell CHA about it.
1176 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1177 return true;
1178 }
1179 private:
1180 const LinearAlloc* allocator_;
1181 const ClassHierarchyAnalysis* cha_;
1182 const PointerSize pointer_size_;
1183 const Thread* self_;
1184};
1185
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001186class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1187 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001188 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001189 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1190
1191 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001192 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001193 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001194 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001195 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001196 }
1197 }
1198
1199 private:
1200 gc::accounting::HeapBitmap* const live_bitmap_;
1201};
1202
Chang Xingba17dbd2017-06-28 21:27:56 +00001203class FixupInternVisitor {
1204 public:
1205 ALWAYS_INLINE ObjPtr<mirror::Object> TryInsertIntern(mirror::Object* obj) const
1206 REQUIRES_SHARED(Locks::mutator_lock_) {
1207 if (obj != nullptr && obj->IsString()) {
1208 const auto intern = Runtime::Current()->GetInternTable()->InternStrong(obj->AsString());
1209 return intern;
1210 }
1211 return obj;
1212 }
1213
1214 ALWAYS_INLINE void VisitRootIfNonNull(
1215 mirror::CompressedReference<mirror::Object>* root) const
1216 REQUIRES_SHARED(Locks::mutator_lock_) {
1217 if (!root->IsNull()) {
1218 VisitRoot(root);
1219 }
1220 }
1221
1222 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1223 REQUIRES_SHARED(Locks::mutator_lock_) {
1224 root->Assign(TryInsertIntern(root->AsMirrorPtr()));
1225 }
1226
1227 // Visit Class Fields
1228 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1229 MemberOffset offset,
1230 bool is_static ATTRIBUTE_UNUSED) const
1231 REQUIRES_SHARED(Locks::mutator_lock_) {
1232 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1233 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1234 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1235 // Updating images, don't do a read barrier.
1236 // Only string fields are fixed, don't do a verify.
1237 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1238 offset);
1239 obj->SetFieldObject<false, false>(offset, TryInsertIntern(ref));
1240 }
1241 }
1242
1243 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1244 ObjPtr<mirror::Reference> ref) const
1245 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1246 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1247 }
1248
1249 void operator()(mirror::Object* obj) const
1250 REQUIRES_SHARED(Locks::mutator_lock_) {
1251 if (obj->IsDexCache()) {
1252 obj->VisitReferences<true, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1253 } else {
1254 // Don't visit native roots for non-dex-cache
1255 obj->VisitReferences<false, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1256 }
1257 }
1258};
1259
Andreas Gampe2af99022017-04-25 08:32:59 -07001260// new_class_set is the set of classes that were read from the class table section in the image.
1261// If there was no class table section, it is null.
1262// Note: using a class here to avoid having to make ClassLinker internals public.
1263class AppImageClassLoadersAndDexCachesHelper {
1264 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001265 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001266 ClassLinker* class_linker,
1267 gc::space::ImageSpace* space,
1268 Handle<mirror::ClassLoader> class_loader,
1269 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001270 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001271 REQUIRES(!Locks::dex_lock_)
1272 REQUIRES_SHARED(Locks::mutator_lock_);
1273};
1274
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001275void AppImageClassLoadersAndDexCachesHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001276 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001277 gc::space::ImageSpace* space,
1278 Handle<mirror::ClassLoader> class_loader,
1279 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001280 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001281 REQUIRES(!Locks::dex_lock_)
1282 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001283 Thread* const self = Thread::Current();
1284 gc::Heap* const heap = Runtime::Current()->GetHeap();
1285 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001286 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001287 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001288 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001289 const size_t num_dex_caches = dex_caches->GetLength();
1290 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001291 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001292 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001293 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001294 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001295 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1296 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001297 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001298 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001299 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001300 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001301 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001302 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001303 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001304 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001305 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001306 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001307 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001308 DCHECK(it != new_class_set->end());
1309 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001310 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001311 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001312 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001313 DCHECK(it2 != new_class_set->end());
1314 DCHECK_EQ(it2->Read(), super_class);
1315 }
1316 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1317 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001318 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1319 if (!class_linker->IsQuickResolutionStub(code) &&
1320 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001321 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001322 !m.IsNative()) {
1323 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001324 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001325 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001326 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1327 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001328 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1329 if (!class_linker->IsQuickResolutionStub(code) &&
1330 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001331 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001332 !m.IsNative()) {
1333 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001334 }
1335 }
1336 }
1337 }
1338 }
1339 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001340 }
Mathieu Chartier743aac32018-03-23 14:25:08 -07001341 if (ClassLinker::kAppImageMayContainStrings) {
Chang Xingba17dbd2017-06-28 21:27:56 +00001342 // Fixup all the literal strings happens at app images which are supposed to be interned.
1343 ScopedTrace timing("Fixup String Intern in image and dex_cache");
1344 const auto& image_header = space->GetImageHeader();
1345 const auto bitmap = space->GetMarkBitmap(); // bitmap of objects
1346 const uint8_t* target_base = space->GetMemMap()->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001347 const ImageSection& objects_section = image_header.GetObjectsSection();
Chang Xingba17dbd2017-06-28 21:27:56 +00001348
1349 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1350 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1351
1352 FixupInternVisitor fixup_intern_visitor;
1353 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_intern_visitor);
1354 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001355 if (kVerifyArtMethodDeclaringClasses) {
1356 ScopedTrace timing("Verify declaring classes");
1357 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1358 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001359 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001360 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001361}
1362
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001363// Update the class loader. Should only be used on classes in the image space.
1364class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001365 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001366 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001367 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001368 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001369
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001370 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001371 // Do not update class loader for boot image classes where the app image
1372 // class loader is only the initiating loader but not the defining loader.
1373 if (klass->GetClassLoader() != nullptr) {
1374 klass->SetClassLoader(class_loader_);
1375 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001376 return true;
1377 }
1378
1379 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001380 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001381};
1382
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001383static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1384 const char* location,
1385 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001386 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001387 DCHECK(error_msg != nullptr);
1388 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001389 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001390 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001391 return std::unique_ptr<const DexFile>();
1392 }
1393 std::string inner_error_msg;
1394 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1395 if (dex_file == nullptr) {
1396 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1397 location,
1398 oat_file->GetLocation().c_str(),
1399 inner_error_msg.c_str());
1400 return std::unique_ptr<const DexFile>();
1401 }
1402
1403 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1404 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1405 location,
1406 dex_file->GetLocationChecksum(),
1407 oat_dex_file->GetDexFileLocationChecksum());
1408 return std::unique_ptr<const DexFile>();
1409 }
1410 return dex_file;
1411}
1412
1413bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1414 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1415 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001416 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001417 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001418 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001419 DCHECK(dex_caches_object != nullptr);
1420 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1421 dex_caches_object->AsObjectArray<mirror::DexCache>();
1422 const OatFile* oat_file = space->GetOatFile();
1423 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001424 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001425 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1426 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1427 dex_file_location.c_str(),
1428 error_msg);
1429 if (dex_file == nullptr) {
1430 return false;
1431 }
1432 dex_cache->SetDexFile(dex_file.get());
1433 out_dex_files->push_back(std::move(dex_file));
1434 }
1435 return true;
1436}
1437
Andreas Gampe0793bec2016-12-01 11:37:33 -08001438// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1439// together and caches some intermediate results.
1440class ImageSanityChecks FINAL {
1441 public:
1442 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1443 REQUIRES_SHARED(Locks::mutator_lock_) {
1444 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001445 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1446 DCHECK(obj != nullptr);
1447 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1448 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1449 if (obj->IsClass()) {
1450 auto klass = obj->AsClass();
1451 for (ArtField& field : klass->GetIFields()) {
1452 CHECK_EQ(field.GetDeclaringClass(), klass);
1453 }
1454 for (ArtField& field : klass->GetSFields()) {
1455 CHECK_EQ(field.GetDeclaringClass(), klass);
1456 }
1457 const auto pointer_size = isc.pointer_size_;
1458 for (auto& m : klass->GetMethods(pointer_size)) {
1459 isc.SanityCheckArtMethod(&m, klass);
1460 }
1461 auto* vtable = klass->GetVTable();
1462 if (vtable != nullptr) {
1463 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1464 }
1465 if (klass->ShouldHaveImt()) {
1466 ImTable* imt = klass->GetImt(pointer_size);
1467 for (size_t i = 0; i < ImTable::kSize; ++i) {
1468 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1469 }
1470 }
1471 if (klass->ShouldHaveEmbeddedVTable()) {
1472 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1473 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1474 }
1475 }
1476 mirror::IfTable* iftable = klass->GetIfTable();
1477 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1478 if (iftable->GetMethodArrayCount(i) > 0) {
1479 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1480 }
1481 }
1482 }
1483 };
1484 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001485 }
1486
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001487 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1488 ClassLinker* class_linker,
1489 mirror::MethodDexCacheType* arr,
1490 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001491 REQUIRES_SHARED(Locks::mutator_lock_) {
1492 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001493 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001494 }
1495
Andreas Gampe0793bec2016-12-01 11:37:33 -08001496 private:
1497 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1498 : spaces_(heap->GetBootImageSpaces()),
1499 pointer_size_(class_linker->GetImagePointerSize()) {
1500 space_begin_.reserve(spaces_.size());
1501 method_sections_.reserve(spaces_.size());
1502 runtime_method_sections_.reserve(spaces_.size());
1503 for (gc::space::ImageSpace* space : spaces_) {
1504 space_begin_.push_back(space->Begin());
1505 auto& header = space->GetImageHeader();
1506 method_sections_.push_back(&header.GetMethodsSection());
1507 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1508 }
1509 }
1510
1511 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1512 REQUIRES_SHARED(Locks::mutator_lock_) {
1513 if (m->IsRuntimeMethod()) {
1514 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1515 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1516 } else if (m->IsCopied()) {
1517 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1518 } else if (expected_class != nullptr) {
1519 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1520 }
1521 if (!spaces_.empty()) {
1522 bool contains = false;
1523 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1524 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1525 contains = method_sections_[i]->Contains(offset) ||
1526 runtime_method_sections_[i]->Contains(offset);
1527 }
1528 CHECK(contains) << m << " not found";
1529 }
1530 }
1531
1532 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1533 ObjPtr<mirror::Class> expected_class)
1534 REQUIRES_SHARED(Locks::mutator_lock_) {
1535 CHECK(arr != nullptr);
1536 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1537 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1538 // expected_class == null means we are a dex cache.
1539 if (expected_class != nullptr) {
1540 CHECK(method != nullptr);
1541 }
1542 if (method != nullptr) {
1543 SanityCheckArtMethod(method, expected_class);
1544 }
1545 }
1546 }
1547
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001548 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001549 REQUIRES_SHARED(Locks::mutator_lock_) {
1550 CHECK_EQ(arr != nullptr, size != 0u);
1551 if (arr != nullptr) {
1552 bool contains = false;
1553 for (auto space : spaces_) {
1554 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001555 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001556 contains = true;
1557 break;
1558 }
1559 }
1560 CHECK(contains);
1561 }
1562 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001563 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1564 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001565 // expected_class == null means we are a dex cache.
1566 if (method != nullptr) {
1567 SanityCheckArtMethod(method, nullptr);
1568 }
1569 }
1570 }
1571
1572 const std::vector<gc::space::ImageSpace*>& spaces_;
1573 const PointerSize pointer_size_;
1574
1575 // Cached sections from the spaces.
1576 std::vector<const uint8_t*> space_begin_;
1577 std::vector<const ImageSection*> method_sections_;
1578 std::vector<const ImageSection*> runtime_method_sections_;
1579};
1580
Andreas Gampebe7af222017-07-25 09:57:28 -07001581static void VerifyAppImage(const ImageHeader& header,
1582 const Handle<mirror::ClassLoader>& class_loader,
1583 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1584 ClassTable* class_table, gc::space::ImageSpace* space)
1585 REQUIRES_SHARED(Locks::mutator_lock_) {
1586 {
1587 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1588 public:
1589 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1590
1591 virtual void Visit(ArtMethod* method)
1592 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1593 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1594 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1595 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1596 }
1597 }
1598
1599 private:
1600 ClassTable* const table_;
1601 };
1602 VerifyClassInTableArtMethodVisitor visitor(class_table);
1603 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1604 }
1605 {
1606 // Verify that all direct interfaces of classes in the class table are also resolved.
1607 std::vector<ObjPtr<mirror::Class>> classes;
1608 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1609 REQUIRES_SHARED(Locks::mutator_lock_) {
1610 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1611 classes.push_back(klass);
1612 }
1613 return true;
1614 };
1615 class_table->Visit(verify_direct_interfaces_in_table);
1616 Thread* self = Thread::Current();
1617 for (ObjPtr<mirror::Class> klass : classes) {
1618 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1619 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1620 << klass->PrettyDescriptor() << " iface #" << i;
1621 }
1622 }
1623 }
1624 // Check that all non-primitive classes in dex caches are also in the class table.
1625 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1626 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1627 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1628 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1629 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1630 if (klass != nullptr && !klass->IsPrimitive()) {
1631 CHECK(class_table->Contains(klass))
1632 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1633 }
1634 }
1635 }
1636}
1637
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001638bool ClassLinker::AddImageSpace(
1639 gc::space::ImageSpace* space,
1640 Handle<mirror::ClassLoader> class_loader,
1641 jobjectArray dex_elements,
1642 const char* dex_location,
1643 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1644 std::string* error_msg) {
1645 DCHECK(out_dex_files != nullptr);
1646 DCHECK(error_msg != nullptr);
1647 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001648 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001649 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001650 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001651 DCHECK(dex_caches_object != nullptr);
1652 Runtime* const runtime = Runtime::Current();
1653 gc::Heap* const heap = runtime->GetHeap();
1654 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001655 // Check that the image is what we are expecting.
1656 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1657 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1658 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1659 image_pointer_size_);
1660 return false;
1661 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001662 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1663 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1664 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1665 expected_image_roots,
1666 header.GetImageRoots()->GetLength());
1667 return false;
1668 }
1669 StackHandleScope<3> hs(self);
1670 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1671 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1672 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1673 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1674 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1675 "Class loader should be the last image root.");
1676 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1677 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001678 DCHECK(class_roots != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001679 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1680 *error_msg = StringPrintf("Expected %d class roots but got %d",
1681 class_roots->GetLength(),
1682 static_cast<int32_t>(kClassRootsMax));
1683 return false;
1684 }
1685 // Check against existing class roots to make sure they match the ones in the boot image.
1686 for (size_t i = 0; i < kClassRootsMax; i++) {
1687 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1688 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1689 return false;
1690 }
1691 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001692 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001693 if (oat_file->GetOatHeader().GetDexFileCount() !=
1694 static_cast<uint32_t>(dex_caches->GetLength())) {
1695 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1696 "image";
1697 return false;
1698 }
1699
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001700 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001701 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1702 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001703 // TODO: Only store qualified paths.
1704 // If non qualified, qualify it.
1705 if (dex_file_location.find('/') == std::string::npos) {
1706 std::string dex_location_path = dex_location;
1707 const size_t pos = dex_location_path.find_last_of('/');
1708 CHECK_NE(pos, std::string::npos);
1709 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1710 dex_file_location = dex_location_path + dex_file_location;
1711 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001712 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1713 dex_file_location.c_str(),
1714 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001715 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001716 return false;
1717 }
1718
1719 if (app_image) {
1720 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1721 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001722 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001723 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001724 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001725 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001726 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001727 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001728 }
1729 }
1730 } else {
1731 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001732 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
1733 this,
1734 dex_cache->GetResolvedMethods(),
1735 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001736 }
1737 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001738 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001739 }
1740 out_dex_files->push_back(std::move(dex_file));
1741 }
1742
1743 if (app_image) {
1744 ScopedObjectAccessUnchecked soa(Thread::Current());
1745 // Check that the class loader resolves the same way as the ones in the image.
1746 // Image class loader [A][B][C][image dex files]
1747 // Class loader = [???][dex_elements][image dex files]
1748 // Need to ensure that [???][dex_elements] == [A][B][C].
1749 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1750 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1751 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1752 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001753 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1754 *error_msg = "Unexpected BootClassLoader in app image";
1755 return false;
1756 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001757 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001758 std::string temp_error_msg;
1759 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1760 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1761 temp_error_msg.c_str());
1762 return false;
1763 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001764 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001765 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1766 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1767 temp_error_msg.c_str());
1768 return false;
1769 }
1770 // Add the temporary dex path list elements at the end.
1771 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1772 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1773 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1774 if (element != nullptr) {
1775 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001776 ObjPtr<mirror::String> name;
1777 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1778 loader_dex_file_names.push_back(name);
1779 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001780 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001781 }
1782 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1783 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1784 static_cast<size_t>(dex_caches->GetLength()));
1785 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1786 // Check that the dex file names match.
1787 bool equal = image_count == loader_dex_file_names.size();
1788 if (equal) {
1789 auto it1 = image_dex_file_names.begin();
1790 auto it2 = loader_dex_file_names.begin();
1791 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1792 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001793 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001794 }
1795 if (!equal) {
1796 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1797 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1798 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001799 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001800 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1801 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1802 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001803 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001804 *error_msg = "Rejecting application image due to class loader mismatch";
1805 // Ignore class loader mismatch for now since these would just use possibly incorrect
1806 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001807 }
1808 }
1809
1810 if (kSanityCheckObjects) {
1811 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1812 auto* dex_cache = dex_caches->Get(i);
1813 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1814 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1815 if (field != nullptr) {
1816 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1817 }
1818 }
1819 }
1820 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001821 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001822 }
1823 }
1824
1825 // Set entry point to interpreter if in InterpretOnly mode.
1826 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001827 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001828 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001829 }
1830
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001831 if (!app_image) {
1832 // Make the string intern table and class table immutable for boot image.
1833 // PIC app oat files may mmap a read-only copy into their own .bss section,
1834 // so enforce that the data in the boot image tables remains unchanged.
1835 //
1836 // We cannot do that for app image even after the fixup as some interned
1837 // String references may actually end up pointing to moveable Strings.
1838 uint8_t* const_section_begin = space->Begin() + header.GetBootImageConstantTablesOffset();
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -07001839 CheckedCall(mprotect,
1840 "protect constant tables",
1841 const_section_begin,
1842 header.GetBootImageConstantTablesSize(),
1843 PROT_READ);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001844 }
1845
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001846 ClassTable* class_table = nullptr;
1847 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001848 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001849 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001850 }
1851 // If we have a class table section, read it and use it for verification in
1852 // UpdateAppImageClassLoadersAndDexCaches.
1853 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001854 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001855 const bool added_class_table = class_table_section.Size() > 0u;
1856 if (added_class_table) {
1857 const uint64_t start_time2 = NanoTime();
1858 size_t read_count = 0;
1859 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1860 /*make copy*/false,
1861 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001862 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001863 }
1864 if (app_image) {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001865 AppImageClassLoadersAndDexCachesHelper::Update(this,
1866 space,
1867 class_loader,
1868 dex_caches,
1869 &temp_set);
Mathieu Chartier69731002016-03-02 16:08:31 -08001870 // Update class loader and resolved strings. If added_class_table is false, the resolved
1871 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001872 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1873 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001874 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001875 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001876
Vladimir Marko305c38b2018-02-14 11:50:07 +00001877 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07001878 // Every class in the app image has initially SubtypeCheckInfo in the
1879 // Uninitialized state.
1880 //
1881 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
1882 // after class initialization is complete. The app image ClassStatus as-is
1883 // are almost all ClassStatus::Initialized, and being in the
1884 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
1885 //
1886 // Force every app image class's SubtypeCheck to be at least kIninitialized.
1887 //
1888 // See also ImageWriter::FixupClass.
1889 ScopedTrace trace("Recalculate app image SubtypeCheck bitstrings");
1890 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
1891 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00001892 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07001893 }
1894 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001895 }
1896 if (!oat_file->GetBssGcRoots().empty()) {
1897 // Insert oat file to class table for visiting .bss GC roots.
1898 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001899 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001900
Mathieu Chartier69731002016-03-02 16:08:31 -08001901 if (added_class_table) {
1902 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1903 class_table->AddClassSet(std::move(temp_set));
1904 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001905
Mathieu Chartier69731002016-03-02 16:08:31 -08001906 if (kIsDebugBuild && app_image) {
1907 // This verification needs to happen after the classes have been added to the class loader.
1908 // Since it ensures classes are in the class table.
Andreas Gampeacbd98b2017-10-12 10:44:11 -07001909 ScopedTrace trace("VerifyAppImage");
Andreas Gampebe7af222017-07-25 09:57:28 -07001910 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08001911 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001912
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001913 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001914 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001915}
1916
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001917bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001918 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1919 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001920}
1921
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001922void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001923 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1924 // enabling tracing requires the mutator lock, there are no race conditions here.
1925 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001926 Thread* const self = Thread::Current();
1927 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001928 if (kUseReadBarrier) {
1929 // We do not track new roots for CC.
1930 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1931 kVisitRootFlagClearRootLog |
1932 kVisitRootFlagStartLoggingNewRoots |
1933 kVisitRootFlagStopLoggingNewRoots));
1934 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001935 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001936 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1937 // There is 3 GC cases to handle:
1938 // Non moving concurrent:
1939 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001940 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001941 //
1942 // Moving non-concurrent:
1943 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1944 // To prevent missing roots, this case needs to ensure that there is no
1945 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1946 // class which is in the class table.
1947 //
1948 // Moving concurrent:
1949 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1950 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001951 //
1952 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1953 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1954 // these objects.
1955 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07001956 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001957 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001958 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001959 for (const ClassLoaderData& data : class_loaders_) {
1960 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1961 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1962 }
1963 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001964 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001965 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001966 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001967 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001968 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001969 // Concurrent moving GC marked new roots through the to-space invariant.
1970 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001971 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001972 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1973 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1974 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1975 if (old_ref != nullptr) {
1976 DCHECK(old_ref->IsClass());
1977 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1978 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1979 // Concurrent moving GC marked new roots through the to-space invariant.
1980 CHECK_EQ(new_ref, old_ref);
1981 }
1982 }
1983 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001984 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001985 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001986 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00001987 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001988 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001989 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001990 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001991 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001992 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001993 }
1994 // We deliberately ignore the class roots in the image since we
1995 // handle image roots by using the MS/CMS rescanning of dirty cards.
1996}
1997
Brian Carlstroma663ea52011-08-19 23:33:41 -07001998// Keep in sync with InitCallback. Anything we visit, we need to
1999// reinit references to when reinitializing a ClassLinker from a
2000// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002001void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002002 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002003 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07002004 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002005 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2006 // unloading if we are marking roots.
2007 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002008}
2009
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002010class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2011 public:
2012 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2013 : visitor_(visitor),
2014 done_(false) {}
2015
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002016 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002017 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002018 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002019 if (!done_ && class_table != nullptr) {
2020 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2021 if (!class_table->Visit(visitor)) {
2022 // If the visitor ClassTable returns false it means that we don't need to continue.
2023 done_ = true;
2024 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002025 }
2026 }
2027
2028 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002029 // Class visitor that limits the class visits from a ClassTable to the classes with
2030 // the provided defining class loader. This filter is used to avoid multiple visits
2031 // of the same class which can be recorded for multiple initiating class loaders.
2032 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2033 public:
2034 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2035 ClassVisitor* visitor)
2036 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2037
2038 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2039 if (klass->GetClassLoader() != defining_class_loader_) {
2040 return true;
2041 }
2042 return (*visitor_)(klass);
2043 }
2044
2045 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2046 ClassVisitor* const visitor_;
2047 };
2048
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002049 ClassVisitor* const visitor_;
2050 // If done is true then we don't need to do any more visiting.
2051 bool done_;
2052};
2053
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002054void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002055 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002056 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2057 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002058 }
2059}
2060
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002061void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002062 Thread* const self = Thread::Current();
2063 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2064 // Not safe to have thread suspension when we are holding a lock.
2065 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002066 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002067 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002068 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002069 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002070 }
2071}
2072
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002073class GetClassesInToVector : public ClassVisitor {
2074 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002075 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002076 classes_.push_back(klass);
2077 return true;
2078 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002079 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002080};
2081
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002082class GetClassInToObjectArray : public ClassVisitor {
2083 public:
2084 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2085 : arr_(arr), index_(0) {}
2086
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002087 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002088 ++index_;
2089 if (index_ <= arr_->GetLength()) {
2090 arr_->Set(index_ - 1, klass);
2091 return true;
2092 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002093 return false;
2094 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002095
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002096 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002097 return index_ <= arr_->GetLength();
2098 }
2099
2100 private:
2101 mirror::ObjectArray<mirror::Class>* const arr_;
2102 int32_t index_;
2103};
2104
2105void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002106 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2107 // is avoiding duplicates.
2108 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002109 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002110 GetClassesInToVector accumulator;
2111 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002112 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002113 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002114 return;
2115 }
2116 }
2117 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002118 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002119 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002120 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002121 // We size the array assuming classes won't be added to the class table during the visit.
2122 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002123 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002124 size_t class_table_size;
2125 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002126 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002127 // Add 100 in case new classes get loaded when we are filling in the object array.
2128 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002129 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002130 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002131 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002132 classes.Assign(
2133 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002134 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002135 GetClassInToObjectArray accumulator(classes.Get());
2136 VisitClasses(&accumulator);
2137 if (accumulator.Succeeded()) {
2138 break;
2139 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002140 }
2141 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2142 // If the class table shrank during creation of the clases array we expect null elements. If
2143 // the class table grew then the loop repeats. If classes are created after the loop has
2144 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002145 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002146 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002147 return;
2148 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002149 }
2150 }
2151}
2152
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002153ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002154 mirror::Class::ResetClass();
2155 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002156 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002157 mirror::Method::ResetClass();
2158 mirror::Reference::ResetClass();
2159 mirror::StackTraceElement::ResetClass();
2160 mirror::String::ResetClass();
2161 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002162 mirror::BooleanArray::ResetArrayClass();
2163 mirror::ByteArray::ResetArrayClass();
2164 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002165 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002166 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002167 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002168 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002169 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002170 mirror::IntArray::ResetArrayClass();
2171 mirror::LongArray::ResetArrayClass();
2172 mirror::ShortArray::ResetArrayClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002173 mirror::CallSite::ResetClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002174 mirror::MethodType::ResetClass();
2175 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002176 mirror::MethodHandlesLookup::ResetClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002177 mirror::VarHandle::ResetClass();
2178 mirror::FieldVarHandle::ResetClass();
2179 mirror::ArrayElementVarHandle::ResetClass();
2180 mirror::ByteArrayViewVarHandle::ResetClass();
2181 mirror::ByteBufferViewVarHandle::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002182 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002183 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002184 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinab2ce842018-02-01 19:09:59 +03002185 // CHA unloading analysis is not needed. No negative consequences are expected because
2186 // all the classloaders are deleted at the same time.
2187 DeleteClassLoader(self, data, false /*cleanup_cha*/);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002188 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002189 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002190}
2191
Alexey Grebenkinab2ce842018-02-01 19:09:59 +03002192void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002193 Runtime* const runtime = Runtime::Current();
2194 JavaVMExt* const vm = runtime->GetJavaVM();
2195 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002196 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002197 if (runtime->GetJit() != nullptr) {
2198 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2199 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002200 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002201 code_cache->RemoveMethodsIn(self, *data.allocator);
2202 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002203 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002204 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002205 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002206 }
Alexey Grebenkinab2ce842018-02-01 19:09:59 +03002207 // Cleanup references to single implementation ArtMethods that will be deleted.
2208 if (cleanup_cha) {
2209 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2210 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2211 }
2212
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002213 delete data.allocator;
2214 delete data.class_table;
2215}
2216
Mathieu Chartiere401d142015-04-22 13:56:20 -07002217mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002218 return down_cast<mirror::PointerArray*>(
2219 image_pointer_size_ == PointerSize::k64
2220 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2221 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002222}
2223
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002224mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002225 Thread* self,
2226 const DexFile& dex_file) {
2227 StackHandleScope<1> hs(self);
2228 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002229 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002230 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002231 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002232 self->AssertPendingOOMException();
2233 return nullptr;
2234 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002235 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002236 if (location == nullptr) {
2237 self->AssertPendingOOMException();
2238 return nullptr;
2239 }
2240 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002241 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002242}
2243
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002244mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2245 const DexFile& dex_file,
2246 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002247 ObjPtr<mirror::String> location = nullptr;
2248 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002249 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002250 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002251 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002252 mirror::DexCache::InitializeDexCache(self,
2253 dex_cache,
2254 location,
2255 &dex_file,
2256 linear_alloc,
2257 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002258 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002259 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002260}
2261
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002262mirror::Class* ClassLinker::AllocClass(Thread* self,
2263 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002264 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002265 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002266 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002267 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002268 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002269 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2270 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002271 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002272 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002273 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002274 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002275 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002276}
2277
Ian Rogers6fac4472014-02-25 17:01:10 -08002278mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002279 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002280}
2281
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002282mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002283 Thread* self,
2284 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002285 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2286 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002287}
2288
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002289mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2290 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002291 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002292 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002293 if (kIsDebugBuild) {
2294 StackHandleScope<1> hs(self);
2295 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2296 Thread::PoisonObjectPointersIfDebug();
2297 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002298
2299 // For temporary classes we must wait for them to be retired.
2300 if (init_done_ && klass->IsTemp()) {
2301 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002302 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002303 ThrowEarlierClassFailure(klass);
2304 return nullptr;
2305 }
2306 StackHandleScope<1> hs(self);
2307 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2308 ObjectLock<mirror::Class> lock(self, h_class);
2309 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002310 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002311 lock.WaitIgnoringInterrupts();
2312 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002313 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002314 ThrowEarlierClassFailure(h_class.Get());
2315 return nullptr;
2316 }
2317 CHECK(h_class->IsRetired());
2318 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002319 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002320 }
2321
Brian Carlstromaded5f72011-10-07 17:15:04 -07002322 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002323 size_t index = 0;
2324 // Maximum number of yield iterations until we start sleeping.
2325 static const size_t kNumYieldIterations = 1000;
2326 // How long each sleep is in us.
2327 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002328 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002329 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002330 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002331 {
2332 ObjectTryLock<mirror::Class> lock(self, h_class);
2333 // Can not use a monitor wait here since it may block when returning and deadlock if another
2334 // thread has locked klass.
2335 if (lock.Acquired()) {
2336 // Check for circular dependencies between classes, the lock is required for SetStatus.
2337 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2338 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002339 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002340 return nullptr;
2341 }
2342 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002344 {
2345 // Handle wrapper deals with klass moving.
2346 ScopedThreadSuspension sts(self, kSuspended);
2347 if (index < kNumYieldIterations) {
2348 sched_yield();
2349 } else {
2350 usleep(kSleepDurationUS);
2351 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002352 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002353 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002354 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002355
Vladimir Marko72ab6842017-01-20 19:32:50 +00002356 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002357 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002358 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359 }
2360 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002361 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002362 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002363 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002364}
2365
Ian Rogers68b56852014-08-29 20:19:11 -07002366typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2367
2368// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002369ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002370 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002371 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002372 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002373 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002374 return ClassPathEntry(dex_file, dex_class_def);
2375 }
2376 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002377 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002378}
2379
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002380bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2381 Thread* self,
2382 const char* descriptor,
2383 size_t hash,
2384 Handle<mirror::ClassLoader> class_loader,
2385 ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002386 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002387 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002388 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002389 return true;
2390 }
2391
Calin Juravlecdd49122017-07-05 20:09:53 -07002392 if (IsPathOrDexClassLoader(soa, class_loader)) {
2393 // For regular path or dex class loader the search order is:
2394 // - parent
2395 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002396
Calin Juravlecdd49122017-07-05 20:09:53 -07002397 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2398 StackHandleScope<1> hs(self);
2399 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2400 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2401 return false; // One of the parents is not supported.
2402 }
2403 if (*result != nullptr) {
2404 return true; // Found the class up the chain.
2405 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002406
Calin Juravlecdd49122017-07-05 20:09:53 -07002407 // Search the current class loader classpath.
2408 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002409 return true;
2410 }
2411
Calin Juravlecdd49122017-07-05 20:09:53 -07002412 if (IsDelegateLastClassLoader(soa, class_loader)) {
2413 // For delegate last, the search order is:
2414 // - boot class path
2415 // - class loader dex files
2416 // - parent
2417 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2418 if (*result != nullptr) {
2419 return true; // The class is part of the boot class path.
2420 }
2421
2422 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2423 if (*result != nullptr) {
2424 return true; // Found the class in the current class loader
2425 }
2426
2427 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2428 StackHandleScope<1> hs(self);
2429 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2430 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2431 }
2432
2433 // Unsupported class loader.
2434 *result = nullptr;
2435 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002436}
2437
2438// Finds the class in the boot class loader.
2439// If the class is found the method returns the resolved class. Otherwise it returns null.
2440ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2441 const char* descriptor,
2442 size_t hash) {
2443 ObjPtr<mirror::Class> result = nullptr;
2444 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2445 if (pair.second != nullptr) {
2446 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2447 if (klass != nullptr) {
2448 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002449 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002450 result = DefineClass(self,
2451 descriptor,
2452 hash,
2453 ScopedNullHandle<mirror::ClassLoader>(),
2454 *pair.first,
2455 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002456 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002457 if (result == nullptr) {
2458 CHECK(self->IsExceptionPending()) << descriptor;
2459 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002460 }
2461 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002462 return result;
2463}
Andreas Gampef865ea92015-04-13 22:14:19 -07002464
Calin Juravle415dc3d2017-06-28 11:03:12 -07002465ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2466 ScopedObjectAccessAlreadyRunnable& soa,
2467 const char* descriptor,
2468 size_t hash,
2469 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampee8320ea2018-02-20 18:24:55 -08002470 DCHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002471 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002472
Andreas Gampee8320ea2018-02-20 18:24:55 -08002473 ObjPtr<mirror::Class> ret;
2474 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2475 const DexFile::ClassDef* dex_class_def =
2476 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2477 if (dex_class_def != nullptr) {
2478 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2479 descriptor,
2480 hash,
2481 class_loader,
2482 *cp_dex_file,
2483 *dex_class_def);
2484 if (klass == nullptr) {
2485 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2486 soa.Self()->ClearException();
2487 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002488 }
Andreas Gampee8320ea2018-02-20 18:24:55 -08002489 ret = klass;
2490 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002491 }
Andreas Gampee8320ea2018-02-20 18:24:55 -08002492 return true; // Continue with the next DexFile.
2493 };
2494
2495 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2496 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002497}
2498
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002499mirror::Class* ClassLinker::FindClass(Thread* self,
2500 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002501 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002502 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002503 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002504 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002505 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002506 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002507 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2508 // for primitive classes that aren't backed by dex files.
2509 return FindPrimitiveClass(descriptor[0]);
2510 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002511 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002512 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002513 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002514 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002515 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002516 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002517 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002518 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002519 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002520 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002521 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002522 return DefineClass(self,
2523 descriptor,
2524 hash,
2525 ScopedNullHandle<mirror::ClassLoader>(),
2526 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002527 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002528 } else {
2529 // The boot class loader is searched ahead of the application class loader, failures are
2530 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2531 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002532 ObjPtr<mirror::Throwable> pre_allocated =
2533 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002534 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002535 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002536 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002537 }
2538 ObjPtr<mirror::Class> result_ptr;
2539 bool descriptor_equals;
2540 if (descriptor[0] == '[') {
2541 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2542 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2543 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2544 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002545 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002546 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002547 bool known_hierarchy =
2548 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2549 if (result_ptr != nullptr) {
2550 // The chain was understood and we found the class. We still need to add the class to
2551 // the class table to protect from racy programs that can try and redefine the path list
2552 // which would change the Class<?> returned for subsequent evaluation of const-class.
2553 DCHECK(known_hierarchy);
2554 DCHECK(result_ptr->DescriptorEquals(descriptor));
2555 descriptor_equals = true;
2556 } else {
2557 // Either the chain wasn't understood or the class wasn't found.
2558 //
2559 // If the chain was understood but we did not find the class, let the Java-side
2560 // rediscover all this and throw the exception with the right stack trace. Note that
2561 // the Java-side could still succeed for racy programs if another thread is actively
2562 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002563
Calin Juravleccd56952016-12-15 17:57:38 +00002564 if (!self->CanCallIntoJava()) {
2565 // Oops, we can't call into java so we can't run actual class-loader code.
2566 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002567 ObjPtr<mirror::Throwable> pre_allocated =
2568 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2569 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002570 return nullptr;
2571 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002572
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002573 // Inlined DescriptorToDot(descriptor) with extra validation.
2574 //
2575 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2576 // the DescriptorEquals() check below and give a confusing error message. For example,
2577 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2578 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2579 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2580 size_t descriptor_length = strlen(descriptor);
2581 if (UNLIKELY(descriptor[0] != 'L') ||
2582 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2583 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2584 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2585 return nullptr;
2586 }
2587 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2588 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2589
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002590 ScopedLocalRef<jobject> class_loader_object(
2591 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002592 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2593 {
2594 ScopedThreadStateChange tsc(self, kNative);
2595 ScopedLocalRef<jobject> class_name_object(
2596 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2597 if (class_name_object.get() == nullptr) {
2598 DCHECK(self->IsExceptionPending()); // OOME.
2599 return nullptr;
2600 }
2601 CHECK(class_loader_object.get() != nullptr);
2602 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2603 WellKnownClasses::java_lang_ClassLoader_loadClass,
2604 class_name_object.get()));
2605 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002606 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002607 // broken loader - throw NPE to be compatible with Dalvik
2608 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2609 class_name_string.c_str()).c_str());
2610 return nullptr;
2611 }
2612 result_ptr = soa.Decode<mirror::Class>(result.get());
2613 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002614 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002615 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002616 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002617
2618 if (self->IsExceptionPending()) {
2619 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2620 // However, to comply with the RI behavior, first check if another thread succeeded.
2621 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2622 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2623 self->ClearException();
2624 return EnsureResolved(self, descriptor, result_ptr);
2625 }
2626 return nullptr;
2627 }
2628
2629 // Try to insert the class to the class table, checking for mismatch.
2630 ObjPtr<mirror::Class> old;
2631 {
2632 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2633 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2634 old = class_table->Lookup(descriptor, hash);
2635 if (old == nullptr) {
2636 old = result_ptr; // For the comparison below, after releasing the lock.
2637 if (descriptor_equals) {
2638 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2639 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2640 } // else throw below, after releasing the lock.
2641 }
2642 }
2643 if (UNLIKELY(old != result_ptr)) {
2644 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2645 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2646 mirror::Class* loader_class = class_loader->GetClass();
2647 const char* loader_class_name =
2648 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2649 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2650 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2651 << DescriptorToDot(descriptor) << "\").";
2652 return EnsureResolved(self, descriptor, old);
2653 }
2654 if (UNLIKELY(!descriptor_equals)) {
2655 std::string result_storage;
2656 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2657 std::string loader_storage;
2658 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2659 ThrowNoClassDefFoundError(
2660 "Initiating class loader of type %s returned class %s instead of %s.",
2661 DescriptorToDot(loader_class_name).c_str(),
2662 DescriptorToDot(result_name).c_str(),
2663 DescriptorToDot(descriptor).c_str());
2664 return nullptr;
2665 }
2666 // success, return mirror::Class*
2667 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002668}
2669
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002670mirror::Class* ClassLinker::DefineClass(Thread* self,
2671 const char* descriptor,
2672 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002673 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002674 const DexFile& dex_file,
2675 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002676 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002677 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002678
Brian Carlstromaded5f72011-10-07 17:15:04 -07002679 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002680 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002681 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002682 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002683 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002684 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002685 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002686 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002687 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002688 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2689 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002690 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002691 klass.Assign(GetClassRoot(kJavaLangDexCache));
Alex Lightd6251582016-10-31 11:12:30 -07002692 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
2693 klass.Assign(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002694 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002695 }
2696
Andreas Gampefa4333d2017-02-14 11:10:34 -08002697 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002698 // Allocate a class with the status of not ready.
2699 // Interface object should get the right size here. Regular class will
2700 // figure out the right size later and be replaced with one of the right
2701 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002702 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002703 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002704 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002705 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002706 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002707 }
Alex Lightb0f11922017-01-23 14:25:17 -08002708 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2709 // nothing.
2710 DexFile const* new_dex_file = nullptr;
2711 DexFile::ClassDef const* new_class_def = nullptr;
2712 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2713 // will only be called once.
2714 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2715 klass,
2716 class_loader,
2717 dex_file,
2718 dex_class_def,
2719 &new_dex_file,
2720 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002721 // Check to see if an exception happened during runtime callbacks. Return if so.
2722 if (self->IsExceptionPending()) {
2723 return nullptr;
2724 }
Alex Lightb0f11922017-01-23 14:25:17 -08002725 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002726 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002727 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002728 return nullptr;
2729 }
2730 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002731 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002732
Jeff Hao848f70a2014-01-15 13:49:50 -08002733 // Mark the string class by setting its access flag.
2734 if (UNLIKELY(!init_done_)) {
2735 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2736 klass->SetStringClass();
2737 }
2738 }
2739
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002740 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002741 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002742 // Make sure we have a valid empty iftable even if there are errors.
2743 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002744
Mathieu Chartier590fee92013-09-13 13:46:47 -07002745 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002746 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002747 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002748 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2749 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002750 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002751 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002752
Mathieu Chartierc7853442015-03-27 14:35:38 -07002753 // Load the fields and other things after we are inserted in the table. This is so that we don't
2754 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2755 // other reason is that the field roots are only visited from the class table. So we need to be
2756 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002757 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002758 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002759 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002760 // An exception occured during load, set status to erroneous while holding klass' lock in case
2761 // notification is necessary.
2762 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002763 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002764 }
2765 return nullptr;
2766 }
2767
Brian Carlstromaded5f72011-10-07 17:15:04 -07002768 // Finish loading (if necessary) by finding parents
2769 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002770 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002771 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002772 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002773 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002774 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002775 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002776 }
2777 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002778
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002779 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002780 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002781 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002782
Brian Carlstromaded5f72011-10-07 17:15:04 -07002783 // Link the class (if necessary)
2784 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002785 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002786 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002787
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002788 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002789 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002790 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002791 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002792 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002793 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002794 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002795 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002796 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002797 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002798 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002799
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002800 // Instrumentation may have updated entrypoints for all methods of all
2801 // classes. However it could not update methods of this class while we
2802 // were loading it. Now the class is resolved, we can update entrypoints
2803 // as required by instrumentation.
2804 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2805 // We must be in the kRunnable state to prevent instrumentation from
2806 // suspending all threads to update entrypoints while we are doing it
2807 // for this class.
2808 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002809 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002810 }
2811
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002812 /*
2813 * We send CLASS_PREPARE events to the debugger from here. The
2814 * definition of "preparation" is creating the static fields for a
2815 * class and initializing them to the standard default values, but not
2816 * executing any code (that comes later, during "initialization").
2817 *
2818 * We did the static preparation in LinkClass.
2819 *
2820 * The class has been prepared and resolved but possibly not yet verified
2821 * at this point.
2822 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002823 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002824
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002825 // Notify native debugger of the new class and its layout.
2826 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2827
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002828 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002829}
2830
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002831uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2832 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002833 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002834 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002835 size_t num_8 = 0;
2836 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002837 size_t num_32 = 0;
2838 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002839 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002840 // We allow duplicate definitions of the same field in a class_data_item
2841 // but ignore the repeated indexes here, b/21868015.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002842 uint32_t last_field_idx = dex::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002843 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002844 uint32_t field_idx = it.GetMemberIndex();
2845 // Ordering enforced by DexFileVerifier.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002846 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
Vladimir Marko879d27b2016-03-15 20:31:50 +00002847 if (UNLIKELY(field_idx == last_field_idx)) {
2848 continue;
2849 }
2850 last_field_idx = field_idx;
2851 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002852 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002853 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002854 switch (c) {
2855 case 'L':
2856 case '[':
2857 num_ref++;
2858 break;
2859 case 'J':
2860 case 'D':
2861 num_64++;
2862 break;
2863 case 'I':
2864 case 'F':
2865 num_32++;
2866 break;
2867 case 'S':
2868 case 'C':
2869 num_16++;
2870 break;
2871 case 'B':
2872 case 'Z':
2873 num_8++;
2874 break;
2875 default:
2876 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002877 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002878 }
2879 }
2880 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002881 return mirror::Class::ComputeClassSize(false,
2882 0,
2883 num_8,
2884 num_16,
2885 num_32,
2886 num_64,
2887 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002888 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002889}
2890
Alex Lightfc49fec2018-01-16 22:28:36 +00002891// Special case to get oat code without overwriting a trampoline.
2892const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002893 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002894 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002895 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002896 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002897 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2898 if (code != nullptr) {
2899 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002900 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002901 if (method->IsNative()) {
2902 // No code and native? Use generic trampoline.
2903 return GetQuickGenericJniStub();
2904 }
2905 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002906}
2907
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002908bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2909 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2910 return false;
2911 }
2912
Elliott Hughes956af0f2014-12-11 14:34:28 -08002913 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002914 return true;
2915 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002916
2917 Runtime* runtime = Runtime::Current();
2918 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2919 if (instr->InterpretOnly()) {
2920 return true;
2921 }
2922
2923 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2924 // Doing this check avoids doing compiled/interpreter transitions.
2925 return true;
2926 }
2927
2928 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2929 // Force the use of interpreter when it is required by the debugger.
2930 return true;
2931 }
2932
Alex Light8f34aba2017-10-09 13:46:32 -07002933 if (Thread::Current()->IsAsyncExceptionPending()) {
2934 // Force use of interpreter to handle async-exceptions
2935 return true;
2936 }
2937
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002938 if (runtime->IsJavaDebuggable()) {
2939 // For simplicity, we ignore precompiled code and go to the interpreter
2940 // assuming we don't already have jitted code.
2941 // We could look at the oat file where `quick_code` is being defined,
2942 // and check whether it's been compiled debuggable, but we decided to
2943 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002944 jit::Jit* jit = Runtime::Current()->GetJit();
2945 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2946 }
2947
David Srbeckyf4480162016-03-16 00:06:24 +00002948 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002949 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002950 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002951 // since we want to JIT it (at first use) with extra stackmaps for native
2952 // debugging. We keep however all AOT code from the boot image,
2953 // since the JIT-at-first-use is blocking and would result in non-negligible
2954 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002955 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002956 }
2957
2958 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002959}
2960
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002961void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002962 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002963 if (klass->NumDirectMethods() == 0) {
2964 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002965 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002966 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002967 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002968 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002969 return; // OAT file unavailable.
2970 }
Ian Rogers19846512012-02-24 11:42:47 -08002971 }
Alex Light64ad14d2014-08-19 14:23:13 -07002972
Mathieu Chartierf8322842014-05-16 10:59:25 -07002973 const DexFile& dex_file = klass->GetDexFile();
2974 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002975 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002976 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002977 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002978 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002979 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002980 it.SkipAllFields();
Ian Rogers97b52f82014-08-14 11:34:07 -07002981 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002982 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2983 klass->GetDexClassDefIndex(),
2984 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002985 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002986 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002987 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002988 if (!method->IsStatic()) {
2989 // Only update static methods.
2990 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002991 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002992 const void* quick_code = nullptr;
2993 if (has_oat_class) {
2994 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002995 quick_code = oat_method.GetQuickCode();
2996 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002997 // Check whether the method is native, in which case it's generic JNI.
2998 if (quick_code == nullptr && method->IsNative()) {
2999 quick_code = GetQuickGenericJniStub();
3000 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003001 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003002 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003003 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003004 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003005 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003006 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003007}
3008
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003009// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3010// method. Should only be called on non-invokable methods.
3011inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003012 DCHECK(method != nullptr);
3013 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003014 method->SetEntryPointFromQuickCompiledCodePtrSize(
3015 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3016 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003017}
3018
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003019static void LinkCode(ClassLinker* class_linker,
3020 ArtMethod* method,
3021 const OatFile::OatClass* oat_class,
3022 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003023 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003024 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003025 // The following code only applies to a non-compiler runtime.
3026 return;
3027 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003028 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003029 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003030 if (oat_class != nullptr) {
3031 // Every kind of method should at least get an invoke stub from the oat_method.
3032 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003033 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003034 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003035 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003036
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003037 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003038 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003039 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003040
Alex Light9139e002015-10-09 15:59:48 -07003041 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003042 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003043 return;
3044 }
Ian Rogers19846512012-02-24 11:42:47 -08003045
3046 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003047 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003048 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3049 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003050 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003051 } else if (quick_code == nullptr && method->IsNative()) {
3052 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003053 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003054 // Set entry point from compiled code if there's no code or in interpreter only mode.
3055 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003056 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003057
Ian Rogers62d6c772013-02-27 08:32:07 -08003058 if (method->IsNative()) {
3059 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003060 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003061
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003062 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003063 // We have a native method here without code. Then it should have either the generic JNI
3064 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3065 // TODO: this doesn't handle all the cases where trampolines may be installed.
3066 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003067 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3068 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003069 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003070 }
3071}
3072
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003073void ClassLinker::SetupClass(const DexFile& dex_file,
3074 const DexFile::ClassDef& dex_class_def,
3075 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003076 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003077 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003078 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003079 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003080 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003081 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003082
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003083 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07003084 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003085 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003086 klass->SetAccessFlags(access_flags);
3087 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003088 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003089 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003090
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003091 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003092 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003093}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003094
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003095void ClassLinker::LoadClass(Thread* self,
3096 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003097 const DexFile::ClassDef& dex_class_def,
3098 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003099 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003100 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003101 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003102 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003103 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003104}
3105
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003106LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3107 LinearAlloc* allocator,
3108 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003109 if (length == 0) {
3110 return nullptr;
3111 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003112 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3113 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3114 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003115 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003116 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003117 CHECK(ret != nullptr);
3118 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3119 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003120}
3121
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003122LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3123 LinearAlloc* allocator,
3124 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003125 if (length == 0) {
3126 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003127 }
Vladimir Marko14632852015-08-17 12:07:23 +01003128 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3129 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003130 const size_t storage_size =
3131 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003132 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003133 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003134 CHECK(ret != nullptr);
3135 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003136 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003137 }
3138 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003139}
3140
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003141LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003142 if (class_loader == nullptr) {
3143 return Runtime::Current()->GetLinearAlloc();
3144 }
3145 LinearAlloc* allocator = class_loader->GetAllocator();
3146 DCHECK(allocator != nullptr);
3147 return allocator;
3148}
3149
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003150LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003151 if (class_loader == nullptr) {
3152 return Runtime::Current()->GetLinearAlloc();
3153 }
3154 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3155 LinearAlloc* allocator = class_loader->GetAllocator();
3156 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003157 RegisterClassLoader(class_loader);
3158 allocator = class_loader->GetAllocator();
3159 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003160 }
3161 return allocator;
3162}
3163
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003164void ClassLinker::LoadClassMembers(Thread* self,
3165 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003166 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003167 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003168 {
3169 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3170 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003171 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003172 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003173 // We allow duplicate definitions of the same field in a class_data_item
3174 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003175 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003176 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003177 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3178 allocator,
3179 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003180 size_t num_sfields = 0;
3181 uint32_t last_field_idx = 0u;
3182 for (; it.HasNextStaticField(); it.Next()) {
3183 uint32_t field_idx = it.GetMemberIndex();
3184 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3185 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3186 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003187 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003188 ++num_sfields;
3189 last_field_idx = field_idx;
3190 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003191 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003192
Mathieu Chartiere401d142015-04-22 13:56:20 -07003193 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003194 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3195 allocator,
3196 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003197 size_t num_ifields = 0u;
3198 last_field_idx = 0u;
3199 for (; it.HasNextInstanceField(); it.Next()) {
3200 uint32_t field_idx = it.GetMemberIndex();
3201 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3202 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3203 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003204 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003205 ++num_ifields;
3206 last_field_idx = field_idx;
3207 }
3208 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003209
Vladimir Marko23682bf2015-06-24 14:28:03 +01003210 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3211 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003212 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003213 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3214 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003215 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3216 if (sfields != nullptr) {
3217 sfields->SetSize(num_sfields);
3218 }
3219 if (ifields != nullptr) {
3220 ifields->SetSize(num_ifields);
3221 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003222 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003223 // Set the field arrays.
3224 klass->SetSFieldsPtr(sfields);
3225 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003226 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003227 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3228 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003229 bool has_oat_class = false;
3230 const OatFile::OatClass oat_class =
3231 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3232 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3233 : OatFile::OatClass::Invalid();
3234 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003235 klass->SetMethodsPtr(
3236 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3237 it.NumDirectMethods(),
3238 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003239 size_t class_def_method_index = 0;
Andreas Gampee2abbc62017-09-15 11:59:26 -07003240 uint32_t last_dex_method_index = dex::kDexNoIndex;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003241 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003242 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003243 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3244 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003245 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003246 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003247 uint32_t it_method_index = it.GetMemberIndex();
3248 if (last_dex_method_index == it_method_index) {
3249 // duplicate case
3250 method->SetMethodIndex(last_class_def_method_index);
3251 } else {
3252 method->SetMethodIndex(class_def_method_index);
3253 last_dex_method_index = it_method_index;
3254 last_class_def_method_index = class_def_method_index;
3255 }
3256 class_def_method_index++;
3257 }
3258 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3259 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003260 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003261 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003262 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003263 class_def_method_index++;
3264 }
3265 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003266 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003267 // Ensure that the card is marked so that remembered sets pick up native roots.
3268 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003269 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003270}
3271
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003272void ClassLinker::LoadField(const ClassDataItemIterator& it,
3273 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003274 ArtField* dst) {
3275 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003276 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003277 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003278
3279 // Get access flags from the DexFile. If this is a boot class path class,
3280 // also set its runtime hidden API access flags.
3281 uint32_t access_flags = it.GetFieldAccessFlags();
3282 if (klass->IsBootStrapClassLoaded()) {
3283 access_flags =
3284 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3285 }
3286 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003287}
3288
Mathieu Chartier268764d2016-09-13 12:09:38 -07003289void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003290 const ClassDataItemIterator& it,
3291 Handle<mirror::Class> klass,
3292 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003293 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003294 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003295 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003296
Mathieu Chartier268764d2016-09-13 12:09:38 -07003297 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003298 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003299 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003300 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003301
David Brazdilf6a8a552018-01-15 18:10:50 +00003302 // Get access flags from the DexFile. If this is a boot class path class,
3303 // also set its runtime hidden API access flags.
Andreas Gampe51829322014-08-25 15:05:04 -07003304 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003305
David Brazdilf6a8a552018-01-15 18:10:50 +00003306 if (klass->IsBootStrapClassLoaded()) {
3307 access_flags =
3308 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3309 }
3310
Ian Rogersdfb325e2013-10-30 01:00:44 -07003311 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003312 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003313 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3314 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003315 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003316 klass->SetFinalizable();
3317 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003318 std::string temp;
3319 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003320 // The Enum class declares a "final" finalize() method to prevent subclasses from
3321 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3322 // subclasses, so we exclude it here.
3323 // We also want to avoid setting the flag on Object, where we know that finalize() is
3324 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003325 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3326 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003327 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003328 }
3329 }
3330 }
3331 } else if (method_name[0] == '<') {
3332 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003333 bool is_init = (strcmp("<init>", method_name) == 0);
3334 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003335 if (UNLIKELY(!is_init && !is_clinit)) {
3336 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3337 } else {
3338 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3339 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003340 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003341 access_flags |= kAccConstructor;
3342 }
3343 }
3344 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003345 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3346 // Check if the native method is annotated with @FastNative or @CriticalNative.
3347 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3348 dex_file, dst->GetClassDef(), dex_method_idx);
3349 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003350 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003351}
3352
Ian Rogers7b078e82014-09-10 14:44:24 -07003353void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003354 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003355 self,
3356 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003357 Runtime::Current()->GetLinearAlloc());
3358 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003359 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003360}
3361
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003362void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003363 ObjPtr<mirror::DexCache> dex_cache) {
3364 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003365 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003366 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
3367 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003368}
3369
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003370void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003371 ObjPtr<mirror::DexCache> dex_cache,
3372 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003373 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003374 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003375 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003376 // For app images, the dex cache location may be a suffix of the dex file location since the
3377 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003378 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3379 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003380 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3381 std::string dex_file_location = dex_file.GetLocation();
3382 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003383 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003384 // Take suffix.
3385 const std::string dex_file_suffix = dex_file_location.substr(
3386 dex_file_location.length() - dex_cache_length,
3387 dex_cache_length);
3388 // Example dex_cache location is SettingsProvider.apk and
3389 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003390 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003391 const OatFile* oat_file =
3392 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
3393 // Clean up pass to remove null dex caches. Also check if we need to initialize OatFile .bss.
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003394 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003395 bool initialize_oat_file_bss = (oat_file != nullptr);
Ian Rogers55256cb2017-12-21 17:07:11 -08003396 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003397 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3398 DexCacheData data = *it;
3399 if (self->IsJWeakCleared(data.weak_root)) {
3400 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003401 it = dex_caches_.erase(it);
3402 } else {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003403 if (initialize_oat_file_bss &&
3404 it->dex_file->GetOatDexFile() != nullptr &&
3405 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
3406 initialize_oat_file_bss = false; // Already initialized.
3407 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003408 ++it;
3409 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003410 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003411 if (initialize_oat_file_bss) {
3412 // TODO: Pre-initialize from boot/app image?
3413 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3414 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3415 entry = resolution_method;
3416 }
3417 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003418 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003419 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003420 DexCacheData data;
3421 data.weak_root = dex_cache_jweak;
3422 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003423 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky440a9b32018-02-15 17:47:29 +00003424 AddNativeDebugInfoForDex(self, ArrayRef<const uint8_t>(data.dex_file->Begin(),
3425 data.dex_file->Size()));
Vladimir Markocd556b02017-02-03 11:47:34 +00003426 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003427 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3428 // path dex caches without an image.
3429 data.class_table->InsertStrongRoot(dex_cache);
3430 if (class_loader != nullptr) {
3431 // Since we added a strong root to the class table, do the write barrier as required for
3432 // remembered sets and generational GCs.
3433 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3434 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003435 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003436}
3437
Vladimir Markocd556b02017-02-03 11:47:34 +00003438ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3439 return data.IsValid()
3440 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3441 : nullptr;
3442}
3443
3444ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3445 Thread* self,
3446 ObjPtr<mirror::DexCache> dex_cache,
3447 const DexCacheData& data,
3448 ObjPtr<mirror::ClassLoader> class_loader) {
3449 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3450 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3451 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3452 "Attempt to register dex file %s with multiple class loaders",
3453 data.dex_file->GetLocation().c_str());
3454 return nullptr;
3455 }
3456 return dex_cache;
3457}
3458
Alex Light07f06212017-06-01 14:01:43 -07003459void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3460 ObjPtr<mirror::ClassLoader> class_loader) {
3461 Thread* self = Thread::Current();
3462 StackHandleScope<2> hs(self);
3463 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3464 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3465 const DexFile* dex_file = dex_cache->GetDexFile();
3466 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3467 if (kIsDebugBuild) {
3468 DexCacheData old_data;
3469 {
3470 ReaderMutexLock mu(self, *Locks::dex_lock_);
3471 old_data = FindDexCacheDataLocked(*dex_file);
3472 }
3473 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3474 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3475 << "been registered on dex file " << dex_file->GetLocation();
3476 }
3477 ClassTable* table;
3478 {
3479 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3480 table = InsertClassTableForClassLoader(h_class_loader.Get());
3481 }
3482 WriterMutexLock mu(self, *Locks::dex_lock_);
3483 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3484 table->InsertStrongRoot(h_dex_cache.Get());
3485 if (h_class_loader.Get() != nullptr) {
3486 // Since we added a strong root to the class table, do the write barrier as required for
3487 // remembered sets and generational GCs.
3488 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3489 }
3490}
3491
Vladimir Markocd556b02017-02-03 11:47:34 +00003492ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3493 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003494 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003495 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003496 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003497 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003498 old_data = FindDexCacheDataLocked(dex_file);
3499 }
3500 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3501 if (old_dex_cache != nullptr) {
3502 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003503 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003504 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3505 DCHECK(linear_alloc != nullptr);
3506 ClassTable* table;
3507 {
3508 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3509 table = InsertClassTableForClassLoader(class_loader);
3510 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003511 // Don't alloc while holding the lock, since allocation may need to
3512 // suspend all threads and another thread may need the dex_lock_ to
3513 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003514 StackHandleScope<3> hs(self);
3515 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003516 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003517 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3518 self,
3519 dex_file)));
3520 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003521 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003522 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003523 old_data = FindDexCacheDataLocked(dex_file);
3524 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003525 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003526 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3527 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3528 // that the arrays are null.
3529 mirror::DexCache::InitializeDexCache(self,
3530 h_dex_cache.Get(),
3531 h_location.Get(),
3532 &dex_file,
3533 linear_alloc,
3534 image_pointer_size_);
3535 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003536 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003537 }
3538 if (old_dex_cache != nullptr) {
3539 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3540 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003541 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003542 self->ClearException();
3543 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3544 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3545 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003546 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003547 self->AssertPendingOOMException();
3548 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003549 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003550 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003551 if (h_class_loader.Get() != nullptr) {
3552 // Since we added a strong root to the class table, do the write barrier as required for
3553 // remembered sets and generational GCs.
3554 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3555 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003556 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003557}
3558
Vladimir Markocd556b02017-02-03 11:47:34 +00003559bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003560 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003561 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003562}
3563
Vladimir Markocd556b02017-02-03 11:47:34 +00003564ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3565 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003566 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3567 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003568 if (dex_cache != nullptr) {
3569 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003570 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003571 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003572 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003573 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003574 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003575 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003576 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003577 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3578 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003579 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003580}
3581
Vladimir Markocd556b02017-02-03 11:47:34 +00003582ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3583 const DexFile* dex_file = dex_cache->GetDexFile();
3584 DCHECK(dex_file != nullptr);
3585 ReaderMutexLock mu(self, *Locks::dex_lock_);
3586 // Search assuming unique-ness of dex file.
3587 for (const DexCacheData& data : dex_caches_) {
3588 // Avoid decoding (and read barriers) other unrelated dex caches.
3589 if (data.dex_file == dex_file) {
3590 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3591 if (registered_dex_cache != nullptr) {
3592 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3593 return data.class_table;
3594 }
3595 }
3596 }
3597 return nullptr;
3598}
3599
3600ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3601 // Search assuming unique-ness of dex file.
3602 for (const DexCacheData& data : dex_caches_) {
3603 // Avoid decoding (and read barriers) other unrelated dex caches.
3604 if (data.dex_file == &dex_file) {
3605 return data;
3606 }
3607 }
3608 return DexCacheData();
3609}
3610
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003611mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003612 ObjPtr<mirror::Class> klass =
3613 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003614 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003615 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003616 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003617 }
3618 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003619}
3620
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003621mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003622 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003623 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003624 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003625 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003626 StackHandleScope<1> hs(self);
3627 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003628 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003629 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3630 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003631 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00003632 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003633 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003634 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3635 h_class.Get(),
3636 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003637 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003638 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003639}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003640
Brian Carlstrombe977852011-07-19 14:54:54 -07003641// Create an array class (i.e. the class object for the array, not the
3642// array itself). "descriptor" looks like "[C" or "[[[[B" or
3643// "[Ljava/lang/String;".
3644//
3645// If "descriptor" refers to an array of primitives, look up the
3646// primitive type's internally-generated class object.
3647//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003648// "class_loader" is the class loader of the class that's referring to
3649// us. It's used to ensure that we're looking for the element type in
3650// the right context. It does NOT become the class loader for the
3651// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003652//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003653// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003654mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003655 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003656 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003657 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003658 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003659 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3660 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003661 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003662 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003663 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003664 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3665 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003666 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003667 DCHECK(self->IsExceptionPending());
3668 return nullptr;
3669 } else {
3670 self->ClearException();
3671 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003672 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003673 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3674 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3675 return nullptr;
3676 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003677 // See if the component type is already loaded. Array classes are
3678 // always associated with the class loader of their underlying
3679 // element type -- an array of Strings goes with the loader for
3680 // java/lang/String -- so we need to look for it there. (The
3681 // caller should have checked for the existence of the class
3682 // before calling here, but they did so with *their* class loader,
3683 // not the component type's loader.)
3684 //
3685 // If we find it, the caller adds "loader" to the class' initiating
3686 // loader list, which should prevent us from going through this again.
3687 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003688 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003689 // are the same, because our caller (FindClass) just did the
3690 // lookup. (Even if we get this wrong we still have correct behavior,
3691 // because we effectively do this lookup again when we add the new
3692 // class to the hash table --- necessary because of possible races with
3693 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003694 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003695 ObjPtr<mirror::Class> new_class =
3696 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003697 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003698 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003699 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003700 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003701
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003702 // Fill out the fields in the Class.
3703 //
3704 // It is possible to execute some methods against arrays, because
3705 // all arrays are subclasses of java_lang_Object_, so we need to set
3706 // up a vtable. We can just point at the one in java_lang_Object_.
3707 //
3708 // Array classes are simple enough that we don't need to do a full
3709 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003710 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003711 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003712 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003713 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003714 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003715 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003716 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003717 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003718 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003719 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003720 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003721 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003722 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003723 } else if (strcmp(descriptor, "[J") == 0) {
3724 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003725 }
3726 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003727 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003728 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003729 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003730 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003731 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003732 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003733 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003734 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003735 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003736 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003737 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003738 new_class->SetSuperClass(java_lang_Object);
3739 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003740 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003741 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003742 if (component_type->IsPrimitive()) {
3743 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3744 } else {
3745 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3746 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00003747 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003748 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3749 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3750 new_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003751 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003752 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003753 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003754
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003755 // All arrays have java/lang/Cloneable and java/io/Serializable as
3756 // interfaces. We need to set that up here, so that stuff like
3757 // "instanceof" works right.
3758 //
3759 // Note: The GC could run during the call to FindSystemClass,
3760 // so we need to make sure the class object is GC-valid while we're in
3761 // there. Do this by clearing the interface list so the GC will just
3762 // think that the entries are null.
3763
3764
3765 // Use the single, global copies of "interfaces" and "iftable"
3766 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003767 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003768 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003769 CHECK(array_iftable != nullptr);
3770 new_class->SetIfTable(array_iftable);
3771 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003772
Elliott Hughes00626c22013-06-14 15:04:14 -07003773 // Inherit access flags from the component type.
3774 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3775 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3776 access_flags &= kAccJavaFlagsMask;
3777 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003778 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003779 access_flags |= kAccAbstract | kAccFinal;
3780 access_flags &= ~kAccInterface;
3781
3782 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003783
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003784 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003785 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003786 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3787 // duplicate events in case of races. Array classes don't really follow dedicated
3788 // load and prepare, anyways.
3789 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3790 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3791
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003792 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003793 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003794 }
3795 // Another thread must have loaded the class after we
3796 // started but before we finished. Abandon what we've
3797 // done.
3798 //
3799 // (Yes, this happens.)
3800
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003801 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003802}
3803
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003804mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003805 switch (type) {
3806 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003807 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003808 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003809 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003810 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003811 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003812 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003813 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003814 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003815 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003816 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003817 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003818 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003819 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003820 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003821 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003822 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003823 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003824 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003825 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003826 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003827 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003828 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003829 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003830}
3831
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003832mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003833 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003834 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003835 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003836 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003837 source += " from ";
3838 source += dex_cache->GetLocation()->ToModifiedUtf8();
3839 }
3840 LOG(INFO) << "Loaded class " << descriptor << source;
3841 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003842 {
3843 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003844 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003845 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003846 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003847 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003848 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003849 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003850 VerifyObject(klass);
3851 class_table->InsertWithHash(klass, hash);
3852 if (class_loader != nullptr) {
3853 // This is necessary because we need to have the card dirtied for remembered sets.
3854 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3855 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003856 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003857 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003858 }
3859 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003860 if (kIsDebugBuild) {
3861 // Test that copied methods correctly can find their holder.
3862 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3863 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3864 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003865 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003866 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003867}
3868
Vladimir Marko1998cd02017-01-13 13:02:58 +00003869void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003870 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3871 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3872 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3873 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003874 }
3875}
3876
Alex Lighte64300b2015-12-15 15:02:47 -08003877// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003878void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003879 LengthPrefixedArray<ArtMethod>* new_methods) {
3880 klass->SetMethodsPtrUnchecked(new_methods,
3881 klass->NumDirectMethods(),
3882 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003883 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003884 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003885}
3886
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003887mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003888 const char* descriptor,
3889 ObjPtr<mirror::ClassLoader> class_loader) {
3890 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3891}
3892
3893mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003894 const char* descriptor,
3895 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003896 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003897 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3898 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3899 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003900 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003901 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003902 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003903 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003904 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003905 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003906}
3907
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003908class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3909 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08003910 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003911
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003912 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003913 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003914 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003915 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003916 if (class_table != nullptr) {
3917 class_table->FreezeSnapshot();
3918 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003919 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003920};
3921
3922void ClassLinker::MoveClassTableToPreZygote() {
3923 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003924 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003925 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003926 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003927}
3928
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003929// Look up classes by hash and descriptor and put all matching ones in the result array.
3930class LookupClassesVisitor : public ClassLoaderVisitor {
3931 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003932 LookupClassesVisitor(const char* descriptor,
3933 size_t hash,
3934 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003935 : descriptor_(descriptor),
3936 hash_(hash),
3937 result_(result) {}
3938
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003939 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003940 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003941 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003942 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003943 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3944 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003945 result_->push_back(klass);
3946 }
3947 }
3948
3949 private:
3950 const char* const descriptor_;
3951 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003952 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003953};
3954
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003955void ClassLinker::LookupClasses(const char* descriptor,
3956 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003957 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003958 Thread* const self = Thread::Current();
3959 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003960 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003961 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003962 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003963 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003964 result.push_back(klass);
3965 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003966 LookupClassesVisitor visitor(descriptor, hash, &result);
3967 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003968}
3969
Alex Lightf1f10492015-10-07 16:08:36 -07003970bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3971 Handle<mirror::Class> klass,
3972 Handle<mirror::Class> supertype) {
3973 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003974 DCHECK(klass != nullptr);
3975 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003976
Alex Lightf1f10492015-10-07 16:08:36 -07003977 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3978 VerifyClass(self, supertype);
3979 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003980
3981 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3982 // The supertype is either verified, or we soft failed at AOT time.
3983 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003984 return true;
3985 }
3986 // If we got this far then we have a hard failure.
3987 std::string error_msg =
3988 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003989 klass->PrettyDescriptor().c_str(),
3990 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003991 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003992 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003993 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003994 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003995 // Set during VerifyClass call (if at all).
3996 self->ClearException();
3997 }
3998 // Change into a verify error.
3999 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004000 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004001 self->GetException()->SetCause(cause.Get());
4002 }
4003 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4004 if (Runtime::Current()->IsAotCompiler()) {
4005 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4006 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004007 // Need to grab the lock to change status.
4008 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004009 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004010 return false;
4011}
4012
Andreas Gampecc1b5352016-12-01 16:58:38 -08004013// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
4014// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
4015// before.
4016static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
4017 REQUIRES_SHARED(Locks::mutator_lock_) {
4018 if (!klass->WasVerificationAttempted()) {
4019 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
4020 klass->SetVerificationAttempted();
4021 }
4022}
4023
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004024verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004025 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004026 {
4027 // TODO: assert that the monitor on the Class is held
4028 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004029
Andreas Gampe884f3b82016-03-30 19:52:58 -07004030 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004031 ClassStatus old_status = klass->GetStatus();
4032 while (old_status == ClassStatus::kVerifying ||
4033 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004034 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004035 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4036 // case we may see the same status again. b/62912904. This is why the check is
4037 // greater or equal.
4038 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004039 << "Class '" << klass->PrettyClass()
4040 << "' performed an illegal verification state transition from " << old_status
4041 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004042 old_status = klass->GetStatus();
4043 }
jeffhao98eacac2011-09-14 16:11:53 -07004044
Andreas Gampe884f3b82016-03-30 19:52:58 -07004045 // The class might already be erroneous, for example at compile time if we attempted to verify
4046 // this class as a parent to another.
4047 if (klass->IsErroneous()) {
4048 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004049 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004050 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004051
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004052 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004053 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004054 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004055 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004056 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004057
4058 // For AOT, don't attempt to re-verify if we have already found we should
4059 // verify at runtime.
4060 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004061 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004062 }
jeffhao98eacac2011-09-14 16:11:53 -07004063
Vladimir Marko2c64a832018-01-04 11:31:56 +00004064 if (klass->GetStatus() == ClassStatus::kResolved) {
4065 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004066 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004067 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004068 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004069 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004070 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004071 }
4072
4073 // Skip verification if disabled.
4074 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004075 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004076 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004077 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004078 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004079 }
4080
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004081 VLOG(class_linker) << "Beginning verification for class: "
4082 << klass->PrettyDescriptor()
4083 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4084
Ian Rogers9ffb0392012-09-10 11:56:50 -07004085 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004086 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004087 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4088 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004089 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004090 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004091 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004092 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004093
Alex Lightf1f10492015-10-07 16:08:36 -07004094 // Verify all default super-interfaces.
4095 //
4096 // (1) Don't bother if the superclass has already had a soft verification failure.
4097 //
4098 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4099 // recursive initialization by themselves. This is because when an interface is initialized
4100 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4101 // but choose not to for an optimization. If the interfaces is being verified due to a class
4102 // initialization (which would need all the default interfaces to be verified) the class code
4103 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004104 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004105 && !klass->IsInterface()) { // See (2)
4106 int32_t iftable_count = klass->GetIfTableCount();
4107 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4108 // Loop through all interfaces this class has defined. It doesn't matter the order.
4109 for (int32_t i = 0; i < iftable_count; i++) {
4110 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004111 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004112 // We only care if we have default interfaces and can skip if we are already verified...
4113 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4114 continue;
4115 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4116 // We had a hard failure while verifying this interface. Just return immediately.
4117 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004118 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004119 } else if (UNLIKELY(!iface->IsVerified())) {
4120 // We softly failed to verify the iface. Stop checking and clean up.
4121 // Put the iface into the supertype handle so we know what caused us to fail.
4122 supertype.Assign(iface.Get());
4123 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004124 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004125 }
4126 }
4127
Alex Lightf1f10492015-10-07 16:08:36 -07004128 // At this point if verification failed, then supertype is the "first" supertype that failed
4129 // verification (without a specific order). If verification succeeded, then supertype is either
4130 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004131 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004132 supertype.Get() == klass->GetSuperClass() ||
4133 !supertype->IsVerified());
4134
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004135 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004136 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004137 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004138 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004139
4140 VLOG(class_linker) << "Class preverified status for class "
4141 << klass->PrettyDescriptor()
4142 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4143 << ": "
4144 << preverified;
4145
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004146 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4147 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004148 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4149 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004150
Ian Rogers62d6c772013-02-27 08:32:07 -08004151 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004152 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004153 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004154 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004155 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004156
4157 // Verification is done, grab the lock again.
4158 ObjectLock<mirror::Class> lock(self, klass);
4159
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004160 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4161 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004162 VLOG(class_linker) << "Soft verification failure in class "
4163 << klass->PrettyDescriptor()
4164 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4165 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004166 }
Ian Rogers1f539342012-10-03 21:09:42 -07004167 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004168 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004169 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004170 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004171 // Even though there were no verifier failures we need to respect whether the super-class and
4172 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004173 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004174 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004175 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004176 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4177 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004178 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004179 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004180 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004181 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004182 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004183 // Soft failures at compile time should be retried at runtime. Soft
4184 // failures at runtime will be handled by slow paths in the generated
4185 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004186 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004187 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004188 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004189 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004190 // As this is a fake verified status, make sure the methods are _not_ marked
4191 // kAccSkipAccessChecks later.
4192 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004193 }
4194 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004195 } else {
David Sehr709b0702016-10-13 09:12:37 -07004196 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004197 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4198 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004199 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004200 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004201 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004202 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004203 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004204 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004205 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004206 // method.
4207 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004208 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004209 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004210
4211 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4212 // Never skip access checks if the verification soft fail is forced.
4213 // Mark the class as having a verification attempt to avoid re-running the verifier.
4214 klass->SetVerificationAttempted();
4215 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004216 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004217 }
Andreas Gampe48498592014-09-10 19:48:05 -07004218 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004219 // Done verifying. Notify the compiler about the verification status, in case the class
4220 // was verified implicitly (eg super class of a compiled class).
4221 if (Runtime::Current()->IsAotCompiler()) {
4222 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4223 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4224 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004225 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004226}
4227
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004228verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4229 Handle<mirror::Class> klass,
4230 verifier::HardFailLogMode log_level,
4231 std::string* error_msg) {
4232 Runtime* const runtime = Runtime::Current();
4233 return verifier::MethodVerifier::VerifyClass(self,
4234 klass.Get(),
4235 runtime->GetCompilerCallbacks(),
4236 runtime->IsAotCompiler(),
4237 log_level,
4238 error_msg);
4239}
4240
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004241bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004242 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004243 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004244 // If we're compiling, we can only verify the class using the oat file if
4245 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004246 // the compilation unit (app - dependencies). We will let the compiler callback
4247 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004248 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004249 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004250 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004251 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004252 return false;
4253 }
4254 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004255 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004256 return false;
4257 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004258 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004259
Richard Uhler07b3c232015-03-31 15:57:54 -07004260 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004261 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004262 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004263 return false;
4264 }
4265
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004266 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004267 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004268 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004269 return true;
4270 }
4271 // If we only verified a subset of the classes at compile time, we can end up with classes that
4272 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004273 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004274 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004275 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004276 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004277 // Compile time verification failed with a soft error. Compile time verification can fail
4278 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004279 // class ... {
4280 // Foo x;
4281 // .... () {
4282 // if (...) {
4283 // v1 gets assigned a type of resolved class Foo
4284 // } else {
4285 // v1 gets assigned a type of unresolved class Bar
4286 // }
4287 // iput x = v1
4288 // } }
4289 // when we merge v1 following the if-the-else it results in Conflict
4290 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4291 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4292 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4293 // at compile time).
4294 return false;
4295 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004296 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004297 // Compile time verification failed with a hard error. This is caused by invalid instructions
4298 // in the class. These errors are unrecoverable.
4299 return false;
4300 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004301 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004302 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4303 // not loading the class.
4304 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4305 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004306 return false;
4307 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004308 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004309 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004310 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004311 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004312 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004313}
4314
Alex Light5a559862016-01-29 12:24:48 -08004315void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004316 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004317 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004318 }
4319}
4320
Alex Light5a559862016-01-29 12:24:48 -08004321void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004322 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004323 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004324 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004325 return; // native or abstract method
4326 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004327 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004328 return; // nothing to process
4329 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004330 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004331 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004332 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4333 CatchHandlerIterator iterator(handlers_ptr);
4334 for (; iterator.HasNext(); iterator.Next()) {
4335 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4336 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004337 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004338 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004339 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004340 DCHECK(Thread::Current()->IsExceptionPending());
4341 Thread::Current()->ClearException();
4342 }
4343 }
4344 }
4345 handlers_ptr = iterator.EndDataPointer();
4346 }
4347}
4348
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004349mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4350 jstring name,
4351 jobjectArray interfaces,
4352 jobject loader,
4353 jobjectArray methods,
4354 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004355 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004356 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004357 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004358 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004359 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004360 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004361 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004362 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004363 DCHECK(temp_klass->GetClass() != nullptr);
4364 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004365 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4366 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004367 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4368 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4369 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4370 temp_klass->SetName(soa.Decode<mirror::String>(name));
4371 temp_klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004372 // Object has an empty iftable, copy it for that reason.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004373 temp_klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004374 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004375 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004376 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004377
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004378 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004379 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004380
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004381 // Insert the class before loading the fields as the field roots
4382 // (ArtField::declaring_class_) are only visited from the class
4383 // table. There can't be any suspend points between inserting the
4384 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004385 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004386 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004387
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004388 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004389 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004390 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004391 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004392
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004393 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4394 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004395 ArtField& interfaces_sfield = sfields->At(0);
4396 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004397 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004398 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004399
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004400 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004401 ArtField& throws_sfield = sfields->At(1);
4402 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004403 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004404 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004405
Ian Rogers466bb252011-10-14 03:29:56 -07004406 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004407 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004408
Alex Lighte64300b2015-12-15 15:02:47 -08004409 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004410 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004411 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004412 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004413 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004414
4415 // Create the methods array.
4416 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4417 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004418 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4419 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004420 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004421 self->AssertPendingOOMException();
4422 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004423 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004424 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004425
4426 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004427 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004428
4429 // Create virtual method using specified prototypes.
4430 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004431 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004432 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004433 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004434 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004435 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4436 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004437 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004438
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004439 // The super class is java.lang.reflect.Proxy
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004440 temp_klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004441 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004442 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004443 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004444
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004445 // At this point the class is loaded. Publish a ClassLoad event.
4446 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4447 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4448
4449 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004450 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004451 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004452 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004453 // Link the fields and virtual methods, creating vtable and iftables.
4454 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004455 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004456 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004457 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004458 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004459 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004460 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004461 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004462 CHECK(temp_klass->IsRetired());
4463 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004464
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004465 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004466 interfaces_sfield.SetObject<false>(
4467 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004468 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004469 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4470 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004471 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004472 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004473
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004474 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4475
Vladimir Marko305c38b2018-02-14 11:50:07 +00004476 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4477 // See also ClassLinker::EnsureInitialized().
4478 if (kBitstringSubtypeCheckEnabled) {
4479 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4480 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4481 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4482 }
4483
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004484 {
4485 // Lock on klass is released. Lock new class object.
4486 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004487 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004488 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004489
4490 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004491 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004492 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004493 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4494
Ian Rogersc2b44472011-12-14 21:17:17 -08004495 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004496 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4497 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004498 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004499 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004500
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004501 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004502 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004503 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004504 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004505 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004506
4507 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004508 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004509 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004510
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004511 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004512 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004513 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004514 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004515 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004516 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004517}
4518
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004519std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004520 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004521 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004522 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004523 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4524}
4525
Mathieu Chartiere401d142015-04-22 13:56:20 -07004526void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4527 // Create constructor for Proxy that must initialize the method.
Neil Fullerd12c3b02017-11-30 18:03:15 +00004528 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004529
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004530 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4531 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markoba118822017-06-12 15:41:56 +01004532 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->FindConstructor(
4533 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004534 DCHECK(proxy_constructor != nullptr)
4535 << "Could not find <init> method in java.lang.reflect.Proxy";
4536
Jeff Haodb8a6642014-08-14 17:18:52 -07004537 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4538 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004539 DCHECK(out != nullptr);
4540 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004541 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004542 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004543 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004544 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4545 kAccPublic |
4546 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004547 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004548
4549 // Set the original constructor method.
4550 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004551}
4552
Mathieu Chartiere401d142015-04-22 13:56:20 -07004553void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004554 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004555 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4556 CHECK_STREQ(np->GetName(), "<init>");
4557 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004558 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004559}
4560
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004561void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004562 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004563 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004564 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004565 DCHECK(out != nullptr);
4566 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004567
Alex Lighte9dd04f2016-03-16 16:09:45 -07004568 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004569 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004570 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4571 // preference to the invocation handler.
4572 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4573 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004574 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4575 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004576 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4577
4578 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4579 // method they copy might (if it's a default method).
4580 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004581
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004582 // Set the original interface method.
4583 out->SetDataPtrSize(prototype, image_pointer_size_);
4584
Ian Rogers466bb252011-10-14 03:29:56 -07004585 // At runtime the method looks like a reference and argument saving method, clone the code
4586 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004587 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004588}
Jesse Wilson95caa792011-10-12 18:14:17 -04004589
Mathieu Chartiere401d142015-04-22 13:56:20 -07004590void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004591 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004592 CHECK(!prototype->IsFinal());
4593 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004594 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004595
4596 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4597 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004598 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004599 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004600}
4601
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004602bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004603 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004604 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004605 return true;
4606 }
4607 if (!can_init_statics) {
4608 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004609 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004610 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004611 return false;
4612 }
4613 // Check if there are encoded static values needing initialization.
4614 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004615 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004616 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004617 if (dex_class_def->static_values_off_ != 0) {
4618 return false;
4619 }
4620 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004621 // If we are a class we need to initialize all interfaces with default methods when we are
4622 // initialized. Check all of them.
4623 if (!klass->IsInterface()) {
4624 size_t num_interfaces = klass->GetIfTableCount();
4625 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004626 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004627 if (iface->HasDefaultMethods() &&
4628 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4629 return false;
4630 }
4631 }
4632 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004633 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004634 if (klass->IsInterface() || !klass->HasSuperClass()) {
4635 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004636 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004637 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004638 if (!can_init_parents && !super_class->IsInitialized()) {
4639 return false;
4640 }
4641 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004642}
4643
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004644bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4645 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004646 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4647
4648 // Are we already initialized and therefore done?
4649 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4650 // an initialized class will never change its state.
4651 if (klass->IsInitialized()) {
4652 return true;
4653 }
4654
4655 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004656 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004657 return false;
4658 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004659
Ian Rogers7b078e82014-09-10 14:44:24 -07004660 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004661 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004662 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004663 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004664
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004665 // Re-check under the lock in case another thread initialized ahead of us.
4666 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004667 return true;
4668 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004669
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004670 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004671 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004672 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004673 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004674 return false;
4675 }
4676
Vladimir Marko72ab6842017-01-20 19:32:50 +00004677 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4678 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004679
4680 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004681 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004682 if (!klass->IsVerified()) {
4683 // We failed to verify, expect either the klass to be erroneous or verification failed at
4684 // compile time.
4685 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004686 // The class is erroneous. This may be a verifier error, or another thread attempted
4687 // verification and/or initialization and failed. We can distinguish those cases by
4688 // whether an exception is already pending.
4689 if (self->IsExceptionPending()) {
4690 // Check that it's a VerifyError.
4691 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004692 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004693 } else {
4694 // Check that another thread attempted initialization.
4695 DCHECK_NE(0, klass->GetClinitThreadId());
4696 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4697 // Need to rethrow the previous failure now.
4698 ThrowEarlierClassFailure(klass.Get(), true);
4699 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004700 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004701 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004702 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004703 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004704 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004705 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004706 } else {
4707 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004709
4710 // A separate thread could have moved us all the way to initialized. A "simple" example
4711 // involves a subclass of the current class being initialized at the same time (which
4712 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004713 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004714 if (klass->IsInitialized()) {
4715 return true;
4716 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004717 }
4718
Vladimir Marko2c64a832018-01-04 11:31:56 +00004719 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07004720 // initializing higher up the stack or another thread has beat us
4721 // to initializing and we need to wait. Either way, this
4722 // invocation of InitializeClass will not be responsible for
4723 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004724 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004725 // Could have got an exception during verification.
4726 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004727 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004728 return false;
4729 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004730 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004731 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004732 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004733 return true;
4734 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004735 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004736 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 }
4738
Jeff Haoe2e40342017-07-19 10:45:18 -07004739 // Try to get the oat class's status for this class if the oat file is present. The compiler
4740 // tries to validate superclass descriptors, and writes the result into the oat file.
4741 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4742 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4743 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004744 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004745 const Runtime* runtime = Runtime::Current();
4746 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4747 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4748 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004749 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07004750 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004751 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004752 return false;
4753 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004754 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004755
Vladimir Marko2c64a832018-01-04 11:31:56 +00004756 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004757 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004758
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004759 // From here out other threads may observe that we're initializing and so changes of state
4760 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004761 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004762 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004763
4764 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004765 }
4766
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004767 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004768 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004769 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004770 if (!super_class->IsInitialized()) {
4771 CHECK(!super_class->IsInterface());
4772 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004773 StackHandleScope<1> hs(self);
4774 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004775 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004776 if (!super_initialized) {
4777 // The super class was verified ahead of entering initializing, we should only be here if
4778 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004779 // For the case of aot compiler, the super class might also be initializing but we don't
4780 // want to process circular dependencies in pre-compile.
4781 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004782 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004783 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004784 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004785 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004786 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004787 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004788 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004789 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004790 return false;
4791 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004792 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004793 }
4794
Alex Lighteb7c1442015-08-31 13:17:42 -07004795 if (!klass->IsInterface()) {
4796 // Initialize interfaces with default methods for the JLS.
4797 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004798 // Only setup the (expensive) handle scope if we actually need to.
4799 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004800 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004801 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4802 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004803 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004804 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004805 CHECK(handle_scope_iface->IsInterface());
4806 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4807 // We have already done this for this interface. Skip it.
4808 continue;
4809 }
4810 // We cannot just call initialize class directly because we need to ensure that ALL
4811 // interfaces with default methods are initialized. Non-default interface initialization
4812 // will not affect other non-default super-interfaces.
4813 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4814 handle_scope_iface,
4815 can_init_statics,
4816 can_init_parents);
4817 if (!iface_initialized) {
4818 ObjectLock<mirror::Class> lock(self, klass);
4819 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004820 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004821 return false;
4822 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004823 }
4824 }
4825 }
4826
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004827 const size_t num_static_fields = klass->NumStaticFields();
4828 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004829 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004830 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004831 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004832 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004833 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004834
4835 // Eagerly fill in static fields so that the we don't have to do as many expensive
4836 // Class::FindStaticField in ResolveField.
4837 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004838 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004839 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004840 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004841 if (resolved_field == nullptr) {
David Brazdild5274382018-05-04 11:28:03 +01004842 // Populating cache of a dex file which defines `klass` should always be allowed.
4843 DCHECK_EQ(hiddenapi::GetMemberAction(
4844 field, class_loader.Get(), dex_cache.Get(), hiddenapi::kNone), hiddenapi::kAllow);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004845 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004846 } else {
4847 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004848 }
4849 }
4850
Vladimir Markoe11dd502017-12-08 14:09:45 +00004851 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
4852 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07004853 this,
4854 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00004855 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers13735952014-10-08 12:43:28 -07004856 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004857 ClassDataItemIterator field_it(dex_file, class_data);
4858 if (value_it.HasNext()) {
4859 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004860 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004861 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004862 ArtField* field = ResolveField(
Vladimir Markoe11dd502017-12-08 14:09:45 +00004863 field_it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004864 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004865 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004866 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004867 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004868 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004869 if (self->IsExceptionPending()) {
4870 break;
4871 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004872 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004873 }
4874 }
4875 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004876
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004877
Mathieu Chartierda595be2016-08-10 13:57:39 -07004878 if (!self->IsExceptionPending()) {
4879 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4880 if (clinit != nullptr) {
4881 CHECK(can_init_statics);
4882 JValue result;
4883 clinit->Invoke(self, nullptr, 0, &result, "V");
4884 }
4885 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004886 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004887 uint64_t t1 = NanoTime();
4888
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004889 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004890 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004891 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004892
4893 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004894 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004895 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004896 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004897 } else if (Runtime::Current()->IsTransactionAborted()) {
4898 // The exception thrown when the transaction aborted has been caught and cleared
4899 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004900 VLOG(compiler) << "Return from class initializer of "
4901 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004902 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004903 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004904 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004905 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004906 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004907 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4908 RuntimeStats* thread_stats = self->GetStats();
4909 ++global_stats->class_init_count;
4910 ++thread_stats->class_init_count;
4911 global_stats->class_init_time_ns += (t1 - t0);
4912 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004913 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004914 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004915 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004916 std::string temp;
4917 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004918 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004919 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004920 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004921 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004922 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004923 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004924 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004925}
4926
Alex Lighteb7c1442015-08-31 13:17:42 -07004927// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4928// and perform the initialization only on those interfaces that contain default methods.
4929bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4930 Handle<mirror::Class> iface,
4931 bool can_init_statics,
4932 bool can_init_parents) {
4933 CHECK(iface->IsInterface());
4934 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004935 // Only create the (expensive) handle scope if we need it.
4936 if (UNLIKELY(num_direct_ifaces > 0)) {
4937 StackHandleScope<1> hs(self);
4938 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4939 // First we initialize all of iface's super-interfaces recursively.
4940 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004941 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004942 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004943 if (!super_iface->HasBeenRecursivelyInitialized()) {
4944 // Recursive step
4945 handle_super_iface.Assign(super_iface);
4946 if (!InitializeDefaultInterfaceRecursive(self,
4947 handle_super_iface,
4948 can_init_statics,
4949 can_init_parents)) {
4950 return false;
4951 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004952 }
4953 }
4954 }
4955
4956 bool result = true;
4957 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4958 // initialize if we don't have default methods.
4959 if (iface->HasDefaultMethods()) {
4960 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4961 }
4962
4963 // Mark that this interface has undergone recursive default interface initialization so we know we
4964 // can skip it on any later class initializations. We do this even if we are not a default
4965 // interface since we can still avoid the traversal. This is purely a performance optimization.
4966 if (result) {
4967 // TODO This should be done in a better way
Andreas Gampec4af33f2018-03-02 17:54:22 -08004968 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
4969 // interface. It is bad (Java) style, but not impossible. Marking the recursive
4970 // initialization is a performance optimization (to avoid another idempotent visit
4971 // for other implementing classes/interfaces), and can be revisited later.
4972 ObjectTryLock<mirror::Class> lock(self, iface);
4973 if (lock.Acquired()) {
4974 iface->SetRecursivelyInitialized();
4975 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004976 }
4977 return result;
4978}
4979
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004980bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4981 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004982 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004983 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004984 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004985 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004986 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004987 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004988
4989 // When we wake up, repeat the test for init-in-progress. If
4990 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004991 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004992 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004993 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004994 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004995 return false;
4996 }
4997 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004998 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004999 continue;
5000 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005001 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005002 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005003 // Compile time initialization failed.
5004 return false;
5005 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005006 if (klass->IsErroneous()) {
5007 // The caller wants an exception, but it was thrown in a
5008 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005009 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005010 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005011 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005012 return false;
5013 }
5014 if (klass->IsInitialized()) {
5015 return true;
5016 }
David Sehr709b0702016-10-13 09:12:37 -07005017 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005018 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005019 }
Ian Rogers07140832014-09-30 15:43:59 -07005020 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005021}
5022
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005023static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5024 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025 ArtMethod* method,
5026 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005027 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005028 DCHECK(Thread::Current()->IsExceptionPending());
5029 DCHECK(!m->IsProxyMethod());
5030 const DexFile* dex_file = m->GetDexFile();
5031 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5032 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005033 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005034 std::string return_type = dex_file->PrettyType(return_type_idx);
5035 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005036 ThrowWrappedLinkageError(klass.Get(),
5037 "While checking class %s method %s signature against %s %s: "
5038 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005039 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5040 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005041 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005042 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005043 return_type.c_str(), class_loader.c_str());
5044}
5045
5046static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5047 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005048 ArtMethod* method,
5049 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005050 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005051 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005052 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005053 DCHECK(Thread::Current()->IsExceptionPending());
5054 DCHECK(!m->IsProxyMethod());
5055 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005056 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5057 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005058 ThrowWrappedLinkageError(klass.Get(),
5059 "While checking class %s method %s signature against %s %s: "
5060 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005061 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5062 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005063 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005064 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005065 index, arg_type.c_str(), class_loader.c_str());
5066}
5067
5068static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5069 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005070 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005071 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005072 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005073 ThrowLinkageError(klass.Get(),
5074 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005075 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5076 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005077 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005078 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005079 error_msg.c_str());
5080}
5081
Ian Rogersb5fb2072014-12-02 17:22:02 -08005082static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005083 Handle<mirror::Class> klass,
5084 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005085 ArtMethod* method1,
5086 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005087 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005088 {
5089 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005090 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005091 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005092 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005093 return false;
5094 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005095 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005096 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005097 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005098 return false;
5099 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005100 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005101 ThrowSignatureMismatch(klass, super_klass, method1,
5102 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005103 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005104 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005105 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005106 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005107 return false;
5108 }
5109 }
5110 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5111 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5112 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005113 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005114 ThrowSignatureMismatch(klass, super_klass, method1,
5115 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005116 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005117 return false;
5118 }
5119 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005120 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005121 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005122 ThrowSignatureMismatch(klass, super_klass, method1,
5123 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005124 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005125 return false;
5126 }
5127 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005128 }
5129 uint32_t num_types = types1->Size();
5130 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005131 ThrowSignatureMismatch(klass, super_klass, method1,
5132 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005133 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005134 return false;
5135 }
5136 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005137 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005138 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005139 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005140 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005141 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005142 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005143 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005144 return false;
5145 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005146 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005147 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005148 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005149 if (UNLIKELY(other_param_type == nullptr)) {
5150 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005151 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005152 return false;
5153 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005154 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005155 ThrowSignatureMismatch(klass, super_klass, method1,
5156 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5157 i,
David Sehr709b0702016-10-13 09:12:37 -07005158 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005159 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005160 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005161 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005162 return false;
5163 }
5164 }
5165 return true;
5166}
5167
5168
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005169bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005170 if (klass->IsInterface()) {
5171 return true;
5172 }
Ian Rogers151f2212014-05-06 11:27:27 -07005173 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005174 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005175 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005176 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005177 if (klass->HasSuperClass() &&
5178 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005179 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005180 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005181 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5182 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5183 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005184 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5185 klass,
5186 super_klass,
5187 m,
5188 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005189 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005190 return false;
5191 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005192 }
5193 }
5194 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005195 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005196 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5197 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5198 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005199 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005200 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5201 j, image_pointer_size_);
5202 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5203 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005204 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5205 klass,
5206 super_klass,
5207 m,
5208 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005209 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005210 return false;
5211 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005212 }
5213 }
5214 }
5215 }
5216 return true;
5217}
5218
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005219bool ClassLinker::EnsureInitialized(Thread* self,
5220 Handle<mirror::Class> c,
5221 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005222 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005223 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005224
Mathieu Chartier524507a2014-08-27 15:28:28 -07005225 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005226 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005227 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005228 return true;
5229 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005230 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5231 //
5232 // Ensure the bitstring is initialized before any of the class initialization
5233 // logic occurs. Once a class initializer starts running, objects can
5234 // escape into the heap and use the subtype checking code.
5235 //
5236 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5237 // can be used as a source for the IsSubClass check, and that all ancestors
5238 // of the class are Assigned (can be used as a target for IsSubClass check)
5239 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005240 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005241 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005242 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005243 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5244 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005245 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005246 if (!success) {
5247 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005248 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005249 }
5250 } else {
5251 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005252 }
5253 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005254}
5255
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005256void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5257 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005258 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005259 for (ArtField& field : new_class->GetIFields()) {
5260 if (field.GetDeclaringClass() == temp_class) {
5261 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005262 }
5263 }
5264
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005265 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005266 for (ArtField& field : new_class->GetSFields()) {
5267 if (field.GetDeclaringClass() == temp_class) {
5268 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005269 }
5270 }
5271
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005272 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005273 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005274 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005275 if (method.GetDeclaringClass() == temp_class) {
5276 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005277 }
5278 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005279
5280 // Make sure the remembered set and mod-union tables know that we updated some of the native
5281 // roots.
5282 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005283}
5284
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005285void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005286 CHECK(class_loader->GetAllocator() == nullptr);
5287 CHECK(class_loader->GetClassTable() == nullptr);
5288 Thread* const self = Thread::Current();
5289 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005290 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005291 // Create and set the class table.
5292 data.class_table = new ClassTable;
5293 class_loader->SetClassTable(data.class_table);
5294 // Create and set the linear allocator.
5295 data.allocator = Runtime::Current()->CreateLinearAlloc();
5296 class_loader->SetAllocator(data.allocator);
5297 // Add to the list so that we know to free the data later.
5298 class_loaders_.push_back(data);
5299}
5300
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005301ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005302 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005303 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005304 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005305 ClassTable* class_table = class_loader->GetClassTable();
5306 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005307 RegisterClassLoader(class_loader);
5308 class_table = class_loader->GetClassTable();
5309 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005310 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005311 return class_table;
5312}
5313
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005314ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005315 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005316}
5317
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005318static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005319 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005320 while (klass->HasSuperClass()) {
5321 klass = klass->GetSuperClass();
5322 if (klass->ShouldHaveImt()) {
5323 return klass->GetImt(pointer_size);
5324 }
5325 }
5326 return nullptr;
5327}
5328
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005329bool ClassLinker::LinkClass(Thread* self,
5330 const char* descriptor,
5331 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005332 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005333 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005334 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005335
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005336 if (!LinkSuperClass(klass)) {
5337 return false;
5338 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005339 ArtMethod* imt_data[ImTable::kSize];
5340 // If there are any new conflicts compared to super class.
5341 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005342 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005343 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005344 return false;
5345 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005346 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005347 return false;
5348 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005349 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005350 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005351 return false;
5352 }
5353 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005354 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005355
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005356 ImTable* imt = nullptr;
5357 if (klass->ShouldHaveImt()) {
5358 // If there are any new conflicts compared to the super class we can not make a copy. There
5359 // can be cases where both will have a conflict method at the same slot without having the same
5360 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5361 // will possibly create a table that is incorrect for either of the classes.
5362 // Same IMT with new_conflict does not happen very often.
5363 if (!new_conflict) {
5364 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5365 if (super_imt != nullptr) {
5366 bool imt_equals = true;
5367 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5368 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5369 }
5370 if (imt_equals) {
5371 imt = super_imt;
5372 }
5373 }
5374 }
5375 if (imt == nullptr) {
5376 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5377 imt = reinterpret_cast<ImTable*>(
5378 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5379 if (imt == nullptr) {
5380 return false;
5381 }
5382 imt->Populate(imt_data, image_pointer_size_);
5383 }
5384 }
5385
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005386 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5387 // We don't need to retire this class as it has no embedded tables or it was created the
5388 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005389 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005390
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005391 if (klass->ShouldHaveEmbeddedVTable()) {
5392 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005393 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005394 if (klass->ShouldHaveImt()) {
5395 klass->SetImt(imt, image_pointer_size_);
5396 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005397
5398 // Update CHA info based on whether we override methods.
5399 // Have to do this before setting the class as resolved which allows
5400 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005401 if (cha_ != nullptr) {
5402 cha_->UpdateAfterLoadingOf(klass);
5403 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005404
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005405 // This will notify waiters on klass that saw the not yet resolved
5406 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005407 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005408 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005409 } else {
5410 CHECK(!klass->IsResolved());
5411 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005412 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005413 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005414 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5415 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5416 // may not see any references to the target space and clean the card for a class if another
5417 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005418 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005419 klass->SetSFieldsPtrUnchecked(nullptr);
5420 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005421 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005422 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005423 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005424 return false;
5425 }
5426
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005427 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5428 ObjectLock<mirror::Class> lock(self, h_new_class);
5429 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005430
5431 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005432 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005433 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005434 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005435 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005436 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005437 if (class_loader != nullptr) {
5438 // We updated the class in the class table, perform the write barrier so that the GC knows
5439 // about the change.
5440 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5441 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005442 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005443 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005444 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5445 }
5446 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005447
Mingyao Yang063fc772016-08-02 11:02:54 -07005448 // Update CHA info based on whether we override methods.
5449 // Have to do this before setting the class as resolved which allows
5450 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005451 if (cha_ != nullptr) {
5452 cha_->UpdateAfterLoadingOf(h_new_class);
5453 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005454
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005455 // This will notify waiters on temp class that saw the not yet resolved class in the
5456 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005457 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005458
Vladimir Marko2c64a832018-01-04 11:31:56 +00005459 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005460 // This will notify waiters on new_class that saw the not yet resolved
5461 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005462 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005463 // Return the new class.
5464 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005465 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005466 return true;
5467}
5468
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005469bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005470 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005471 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005472 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5473 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005474 // Check that a class does not inherit from itself directly.
5475 //
5476 // TODO: This is a cheap check to detect the straightforward case
5477 // of a class extending itself (b/28685551), but we should do a
5478 // proper cycle detection on loaded classes, to detect all cases
5479 // of class circularity errors (b/28830038).
5480 if (super_class_idx == class_def.class_idx_) {
5481 ThrowClassCircularityError(klass.Get(),
5482 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005483 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005484 return false;
5485 }
5486
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005487 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005488 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005489 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005490 return false;
5491 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005492 // Verify
5493 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005494 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005495 super_class->PrettyDescriptor().c_str(),
5496 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005497 return false;
5498 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005499 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005500 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005501 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005502 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005503 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005504 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005505 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005506 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005507 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005508 DCHECK(Thread::Current()->IsExceptionPending());
5509 return false;
5510 }
5511 // Verify
5512 if (!klass->CanAccess(interface)) {
5513 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005514 ThrowIllegalAccessError(klass.Get(),
5515 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005516 interface->PrettyDescriptor().c_str(),
5517 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005518 return false;
5519 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005520 }
5521 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005522 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005523 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005524 return true;
5525}
5526
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005527bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005528 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005529 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005530 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005531 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005532 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005533 return false;
5534 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005535 return true;
5536 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005537 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005538 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005539 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005540 return false;
5541 }
5542 // Verify
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005543 if (klass->IsInterface() && super != GetClassRoot(kJavaLangObject)) {
5544 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5545 return false;
5546 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005547 if (super->IsFinal()) {
5548 ThrowVerifyError(klass.Get(),
5549 "Superclass %s of %s is declared final",
5550 super->PrettyDescriptor().c_str(),
5551 klass->PrettyDescriptor().c_str());
5552 return false;
5553 }
5554 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005555 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005556 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005557 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005558 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005559 return false;
5560 }
5561 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005562 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005563 super->PrettyDescriptor().c_str(),
5564 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005565 return false;
5566 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005567
Brian Carlstromf3632832014-05-20 15:36:53 -07005568 // Inherit kAccClassIsFinalizable from the superclass in case this
5569 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005570 if (super->IsFinalizable()) {
5571 klass->SetFinalizable();
5572 }
5573
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005574 // Inherit class loader flag form super class.
5575 if (super->IsClassLoaderClass()) {
5576 klass->SetClassLoaderClass();
5577 }
5578
Elliott Hughes2da50362011-10-10 16:57:08 -07005579 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005580 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005581 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005582 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005583 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005584 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005585 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005586 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005587 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005588 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005589 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005590 return false;
5591 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005592
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005593 if (kIsDebugBuild) {
5594 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005595 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005596 CHECK(super->IsResolved());
5597 super = super->GetSuperClass();
5598 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005599 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005600 return true;
5601}
5602
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005603// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005604bool ClassLinker::LinkMethods(Thread* self,
5605 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005606 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005607 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005608 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005609 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005610 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5611 // need to have default methods be in the virtuals array of each class but we don't set that up
5612 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005613 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005614 // Link virtual methods then interface methods.
5615 // We set up the interface lookup table first because we need it to determine if we need to update
5616 // any vtable entries with new default method implementations.
5617 return SetupInterfaceLookupTable(self, klass, interfaces)
5618 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005619 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005620}
5621
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005622// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5623// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5624// caches in the implementation below.
5625class MethodNameAndSignatureComparator FINAL : public ValueObject {
5626 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005627 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005628 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005629 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5630 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005631 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005632 }
5633
5634 const char* GetName() {
5635 if (name_ == nullptr) {
5636 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5637 }
5638 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005639 }
5640
Mathieu Chartiere401d142015-04-22 13:56:20 -07005641 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005642 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005643 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005644 const DexFile* other_dex_file = other->GetDexFile();
5645 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5646 if (dex_file_ == other_dex_file) {
5647 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5648 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005649 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005650 uint32_t other_name_len;
5651 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5652 &other_name_len);
5653 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5654 return false;
5655 }
5656 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5657 }
5658
5659 private:
5660 // Dex file for the method to compare against.
5661 const DexFile* const dex_file_;
5662 // MethodId for the method to compare against.
5663 const DexFile::MethodId* const mid_;
5664 // Lazily computed name from the dex file's strings.
5665 const char* name_;
5666 // Lazily computed name length.
5667 uint32_t name_len_;
5668};
5669
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005670class LinkVirtualHashTable {
5671 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005672 LinkVirtualHashTable(Handle<mirror::Class> klass,
5673 size_t hash_size,
5674 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005675 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005676 : klass_(klass),
5677 hash_size_(hash_size),
5678 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005679 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005680 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5681 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005682
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005683 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005684 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5685 virtual_method_index, image_pointer_size_);
5686 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005687 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005688 uint32_t index = hash % hash_size_;
5689 // Linear probe until we have an empty slot.
5690 while (hash_table_[index] != invalid_index_) {
5691 if (++index == hash_size_) {
5692 index = 0;
5693 }
5694 }
5695 hash_table_[index] = virtual_method_index;
5696 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005697
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005698 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005699 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005700 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005701 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005702 size_t index = hash % hash_size_;
5703 while (true) {
5704 const uint32_t value = hash_table_[index];
5705 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5706 // the block and can safely assume not found.
5707 if (value == invalid_index_) {
5708 break;
5709 }
5710 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005711 ArtMethod* virtual_method =
5712 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5713 if (comparator->HasSameNameAndSignature(
5714 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005715 hash_table_[index] = removed_index_;
5716 return value;
5717 }
5718 }
5719 if (++index == hash_size_) {
5720 index = 0;
5721 }
5722 }
5723 return GetNotFoundIndex();
5724 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005725
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005726 static uint32_t GetNotFoundIndex() {
5727 return invalid_index_;
5728 }
5729
5730 private:
5731 static const uint32_t invalid_index_;
5732 static const uint32_t removed_index_;
5733
5734 Handle<mirror::Class> klass_;
5735 const size_t hash_size_;
5736 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005737 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005738};
5739
5740const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5741const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5742
Stephen Hines1ddd9132017-02-08 01:51:18 -08005743bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005744 Thread* self,
5745 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005746 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005747 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005748 if (klass->IsInterface()) {
5749 // No vtable.
5750 if (!IsUint<16>(num_virtual_methods)) {
5751 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5752 return false;
5753 }
5754 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005755 // Assign each method an IMT index and set the default flag.
5756 for (size_t i = 0; i < num_virtual_methods; ++i) {
5757 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5758 m->SetMethodIndex(i);
5759 if (!m->IsAbstract()) {
5760 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5761 has_defaults = true;
5762 }
5763 }
5764 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5765 // during initialization. This is a performance optimization. We could simply traverse the
5766 // virtual_methods_ array again during initialization.
5767 if (has_defaults) {
5768 klass->SetHasDefaultMethods();
5769 }
5770 return true;
5771 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005772 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5773 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005774 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005775 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005776 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005777 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005778 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005779 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005780 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005781 return false;
5782 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005783 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005784 vtable->SetElementPtrSize(
5785 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005786 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005787 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5788 // might give us new default methods). If no new interfaces then we can skip the rest since
5789 // the class cannot override any of the super-class's methods. This is required for
5790 // correctness since without it we might not update overridden default method vtable entries
5791 // correctly.
5792 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005793 klass->SetVTable(vtable.Get());
5794 return true;
5795 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005796 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005797 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005798 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005799 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005800 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5801 // might give us new default methods). See comment above.
5802 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005803 klass->SetVTable(super_vtable);
5804 return true;
5805 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005806 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5807 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005808 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005809 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005810 return false;
5811 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005812 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005813 // How the algorithm works:
5814 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5815 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5816 // method which has not been matched to a vtable method, and j if the virtual method at the
5817 // index overrode the super virtual method at index j.
5818 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5819 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5820 // the need for the initial vtable which we later shrink back down).
5821 // 3. Add non overridden methods to the end of the vtable.
5822 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005823 // + 1 so that even if we only have new default methods we will still be able to use this hash
5824 // table (i.e. it will never have 0 size).
5825 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005826 uint32_t* hash_table_ptr;
5827 std::unique_ptr<uint32_t[]> hash_heap_storage;
5828 if (hash_table_size <= kMaxStackHash) {
5829 hash_table_ptr = reinterpret_cast<uint32_t*>(
5830 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5831 } else {
5832 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5833 hash_table_ptr = hash_heap_storage.get();
5834 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005835 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005836 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005837 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005838 DCHECK(klass->GetVirtualMethodDuringLinking(
5839 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005840 hash_table.Add(i);
5841 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005842 // 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 -07005843 // the hash table.
5844 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005845 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005846 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005847 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5848 super_method->GetAccessFlags())) {
5849 // Continue on to the next method since this one is package private and canot be overridden.
5850 // Before Android 4.1, the package-private method super_method might have been incorrectly
5851 // overridden.
5852 continue;
5853 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005854 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005855 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005856 // We remove the method so that subsequent lookups will be faster by making the hash-map
5857 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005858 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5859 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005860 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5861 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005862 if (super_method->IsFinal()) {
5863 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5864 virtual_method->PrettyMethod().c_str(),
5865 super_method->GetDeclaringClassDescriptor());
5866 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005867 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005868 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5869 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005870 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005871 // We didn't directly override this method but we might through default methods...
5872 // Check for default method update.
5873 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005874 switch (FindDefaultMethodImplementation(self,
5875 super_method,
5876 klass,
5877 /*out*/&default_method)) {
5878 case DefaultMethodSearchResult::kDefaultConflict: {
5879 // A conflict was found looking for default methods. Note this (assuming it wasn't
5880 // pre-existing) in the translations map.
5881 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5882 // Don't generate another conflict method to reduce memory use as an optimization.
5883 default_translations->insert(
5884 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5885 }
5886 break;
5887 }
5888 case DefaultMethodSearchResult::kAbstractFound: {
5889 // No conflict but method is abstract.
5890 // We note that this vtable entry must be made abstract.
5891 if (UNLIKELY(!super_method->IsAbstract())) {
5892 default_translations->insert(
5893 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5894 }
5895 break;
5896 }
5897 case DefaultMethodSearchResult::kDefaultFound: {
5898 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5899 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5900 // Found a default method implementation that is new.
5901 // TODO Refactor this add default methods to virtuals here and not in
5902 // LinkInterfaceMethods maybe.
5903 // The problem is default methods might override previously present
5904 // default-method or miranda-method vtable entries from the superclass.
5905 // Unfortunately we need these to be entries in this class's virtuals. We do not
5906 // give these entries there until LinkInterfaceMethods so we pass this map around
5907 // to let it know which vtable entries need to be updated.
5908 // Make a note that vtable entry j must be updated, store what it needs to be updated
5909 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5910 // then.
5911 default_translations->insert(
5912 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005913 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5914 << " overridden by default "
5915 << default_method->PrettyMethod()
5916 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005917 }
5918 break;
5919 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005920 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005921 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005922 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005923 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005924 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005925 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005926 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005927 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5928 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005929 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005930 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005931 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005932 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005933 local_method->SetMethodIndex(actual_count);
5934 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005935 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005936 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005937 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005938 return false;
5939 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005940 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005941 CHECK_LE(actual_count, max_count);
5942 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005943 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005944 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005945 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005946 return false;
5947 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005948 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005949 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005950 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005951 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005952 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005953 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5954 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005955 return false;
5956 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005957 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005958 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005959 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005960 return false;
5961 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005962 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005963 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5964 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005965 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005966 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005967 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005968 }
5969 return true;
5970}
5971
Alex Light9139e002015-10-09 15:59:48 -07005972// Determine if the given iface has any subinterface in the given list that declares the method
5973// specified by 'target'.
5974//
5975// Arguments
5976// - self: The thread we are running on
5977// - target: A comparator that will match any method that overrides the method we are checking for
5978// - iftable: The iftable we are searching for an overriding method on.
5979// - ifstart: The index of the interface we are checking to see if anything overrides
5980// - iface: The interface we are checking to see if anything overrides.
5981// - image_pointer_size:
5982// The image pointer size.
5983//
5984// Returns
5985// - True: There is some method that matches the target comparator defined in an interface that
5986// is a subtype of iface.
5987// - False: There is no method that matches the target comparator in any interface that is a subtype
5988// of iface.
5989static bool ContainsOverridingMethodOf(Thread* self,
5990 MethodNameAndSignatureComparator& target,
5991 Handle<mirror::IfTable> iftable,
5992 size_t ifstart,
5993 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005994 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005995 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005996 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005997 DCHECK(iface != nullptr);
5998 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07005999 DCHECK_GE(ifstart, 0u);
6000 DCHECK_LT(ifstart, iftable->Count());
6001 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6002 DCHECK(iface->IsInterface());
6003
6004 size_t iftable_count = iftable->Count();
6005 StackHandleScope<1> hs(self);
6006 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6007 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6008 // Skip ifstart since our current interface obviously cannot override itself.
6009 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006010 // Iterate through every method on this interface. The order does not matter.
6011 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006012 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006013 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006014 // Check if the i'th interface is a subtype of this one.
6015 if (iface->IsAssignableFrom(current_iface.Get())) {
6016 return true;
6017 }
6018 break;
6019 }
6020 }
6021 }
6022 return false;
6023}
6024
Alex Lighteb7c1442015-08-31 13:17:42 -07006025// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006026// out_default_method and returns kDefaultFound on success. If no default method was found return
6027// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6028// default_method conflict) it will return kDefaultConflict.
6029ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6030 Thread* self,
6031 ArtMethod* target_method,
6032 Handle<mirror::Class> klass,
6033 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006034 DCHECK(self != nullptr);
6035 DCHECK(target_method != nullptr);
6036 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006037
6038 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006039
6040 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6041 // table. This lets us walk the table backwards when searching for default methods. The first one
6042 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6043 // track of it and then continue checking all other interfaces, since we need to throw an error if
6044 // we encounter conflicting default method implementations (one is not a subtype of the other).
6045 //
6046 // The order of unrelated interfaces does not matter and is not defined.
6047 size_t iftable_count = klass->GetIfTableCount();
6048 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006049 // No interfaces. We have already reset out to null so just return kAbstractFound.
6050 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006051 }
6052
Alex Light9139e002015-10-09 15:59:48 -07006053 StackHandleScope<3> hs(self);
6054 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006055 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006056 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006057 MethodNameAndSignatureComparator target_name_comparator(
6058 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6059 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006060 for (size_t k = iftable_count; k != 0; ) {
6061 --k;
6062
Alex Lighteb7c1442015-08-31 13:17:42 -07006063 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006064
6065 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006066 // Iterate through every declared method on this interface. The order does not matter.
6067 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6068 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006069 // Skip abstract methods and methods with different names.
6070 if (current_method->IsAbstract() ||
6071 !target_name_comparator.HasSameNameAndSignature(
6072 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6073 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006074 } else if (!current_method->IsPublic()) {
6075 // The verifier should have caught the non-public method for dex version 37. Just warn and
6076 // skip it since this is from before default-methods so we don't really need to care that it
6077 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006078 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6079 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006080 << "This will be a fatal error in subsequent versions of android. "
6081 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006082 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006083 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006084 // We have multiple default impls of the same method. This is a potential default conflict.
6085 // We need to check if this possibly conflicting method is either a superclass of the chosen
6086 // default implementation or is overridden by a non-default interface method. In either case
6087 // there is no conflict.
6088 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6089 !ContainsOverridingMethodOf(self,
6090 target_name_comparator,
6091 iftable,
6092 k,
6093 iface,
6094 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006095 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006096 << current_method->PrettyMethod() << " and "
6097 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6098 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006099 *out_default_method = nullptr;
6100 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006101 } else {
6102 break; // Continue checking at the next interface.
6103 }
6104 } else {
Alex Light9139e002015-10-09 15:59:48 -07006105 // chosen_iface == null
6106 if (!ContainsOverridingMethodOf(self,
6107 target_name_comparator,
6108 iftable,
6109 k,
6110 iface,
6111 image_pointer_size_)) {
6112 // Don't set this as the chosen interface if something else is overriding it (because that
6113 // other interface would be potentially chosen instead if it was default). If the other
6114 // interface was abstract then we wouldn't select this interface as chosen anyway since
6115 // the abstract method masks it.
6116 *out_default_method = current_method;
6117 chosen_iface.Assign(iface.Get());
6118 // We should now finish traversing the graph to find if we have default methods that
6119 // conflict.
6120 } else {
David Sehr709b0702016-10-13 09:12:37 -07006121 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6122 << "' was "
6123 << "skipped because it was overridden by an abstract method in a "
6124 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006125 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006126 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006127 break;
6128 }
6129 }
Alex Light9139e002015-10-09 15:59:48 -07006130 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006131 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6132 << "' selected "
6133 << "as the implementation for '" << target_method->PrettyMethod()
6134 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006135 return DefaultMethodSearchResult::kDefaultFound;
6136 } else {
6137 return DefaultMethodSearchResult::kAbstractFound;
6138 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006139}
6140
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006141ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006142 ArtMethod* conflict_method,
6143 ArtMethod* interface_method,
6144 ArtMethod* method,
6145 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006146 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006147 Runtime* const runtime = Runtime::Current();
6148 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6149 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6150
6151 // Create a new entry if the existing one is the shared conflict method.
6152 ArtMethod* new_conflict_method = new_entry
6153 ? runtime->CreateImtConflictMethod(linear_alloc)
6154 : conflict_method;
6155
6156 // Allocate a new table. Note that we will leak this table at the next conflict,
6157 // but that's a tradeoff compared to making the table fixed size.
6158 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006159 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6160 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006161 if (data == nullptr) {
6162 LOG(ERROR) << "Failed to allocate conflict table";
6163 return conflict_method;
6164 }
6165 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6166 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006167 method,
6168 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006169
6170 // Do a fence to ensure threads see the data in the table before it is assigned
6171 // to the conflict method.
6172 // Note that there is a race in the presence of multiple threads and we may leak
6173 // memory from the LinearAlloc, but that's a tradeoff compared to using
6174 // atomic operations.
6175 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006176 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006177 return new_conflict_method;
6178}
6179
Vladimir Marko921094a2017-01-12 18:37:06 +00006180bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6181 Handle<mirror::Class> klass,
6182 Handle<mirror::IfTable> iftable) {
6183 DCHECK(!klass->IsInterface());
6184 const bool has_superclass = klass->HasSuperClass();
6185 const bool extend_super_iftable = has_superclass;
6186 const size_t ifcount = klass->GetIfTableCount();
6187 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6188 for (size_t i = 0; i < ifcount; ++i) {
6189 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6190 if (num_methods > 0) {
6191 const bool is_super = i < super_ifcount;
6192 // This is an interface implemented by a super-class. Therefore we can just copy the method
6193 // array from the superclass.
6194 const bool super_interface = is_super && extend_super_iftable;
6195 ObjPtr<mirror::PointerArray> method_array;
6196 if (super_interface) {
6197 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6198 DCHECK(if_table != nullptr);
6199 DCHECK(if_table->GetMethodArray(i) != nullptr);
6200 // If we are working on a super interface, try extending the existing method array.
6201 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6202 } else {
6203 method_array = AllocPointerArray(self, num_methods);
6204 }
6205 if (UNLIKELY(method_array == nullptr)) {
6206 self->AssertPendingOOMException();
6207 return false;
6208 }
6209 iftable->SetMethodArray(i, method_array);
6210 }
6211 }
6212 return true;
6213}
6214
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006215void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6216 ArtMethod* imt_conflict_method,
6217 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006218 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006219 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006220 // Place method in imt if entry is empty, place conflict otherwise.
6221 if (*imt_ref == unimplemented_method) {
6222 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006223 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006224 // If we are not a conflict and we have the same signature and name as the imt
6225 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006226 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6227 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006228 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006229 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006230 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006231 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006232 *imt_ref = current_method;
6233 } else {
Alex Light9139e002015-10-09 15:59:48 -07006234 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006235 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006236 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006237 } else {
6238 // Place the default conflict method. Note that there may be an existing conflict
6239 // method in the IMT, but it could be one tailored to the super class, with a
6240 // specific ImtConflictTable.
6241 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006242 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006243 }
6244}
6245
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006246void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006247 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6248 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006249 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006250 Runtime* const runtime = Runtime::Current();
6251 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6252 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006253 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006254 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006255 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006256 FillIMTFromIfTable(klass->GetIfTable(),
6257 unimplemented_method,
6258 conflict_method,
6259 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006260 /*create_conflict_tables*/true,
6261 /*ignore_copied_methods*/false,
6262 &new_conflict,
6263 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006264 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006265 if (!klass->ShouldHaveImt()) {
6266 return;
6267 }
6268 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6269 // we can just use the same pointer.
6270 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006271 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006272 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6273 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6274 bool same = true;
6275 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6276 ArtMethod* method = imt_data[i];
6277 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6278 if (method != super_method) {
6279 bool is_conflict_table = method->IsRuntimeMethod() &&
6280 method != unimplemented_method &&
6281 method != conflict_method;
6282 // Verify conflict contents.
6283 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6284 super_method != unimplemented_method &&
6285 super_method != conflict_method;
6286 if (!is_conflict_table || !super_conflict_table) {
6287 same = false;
6288 } else {
6289 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6290 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6291 same = same && table1->Equals(table2, image_pointer_size_);
6292 }
6293 }
6294 }
6295 if (same) {
6296 imt = super_imt;
6297 }
6298 }
6299 if (imt == nullptr) {
6300 imt = klass->GetImt(image_pointer_size_);
6301 DCHECK(imt != nullptr);
6302 imt->Populate(imt_data, image_pointer_size_);
6303 } else {
6304 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006305 }
6306}
6307
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006308ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6309 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006310 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006311 void* data = linear_alloc->Alloc(Thread::Current(),
6312 ImtConflictTable::ComputeSize(count,
6313 image_pointer_size));
6314 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6315}
6316
6317ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6318 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6319}
6320
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006321void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006322 ArtMethod* unimplemented_method,
6323 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006324 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006325 bool create_conflict_tables,
6326 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006327 /*out*/bool* new_conflict,
6328 /*out*/ArtMethod** imt) {
6329 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006330 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006331 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006332 const size_t num_virtuals = interface->NumVirtualMethods();
6333 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6334 // Virtual methods can be larger than the if table methods if there are default methods.
6335 DCHECK_GE(num_virtuals, method_array_count);
6336 if (kIsDebugBuild) {
6337 if (klass->IsInterface()) {
6338 DCHECK_EQ(method_array_count, 0u);
6339 } else {
6340 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6341 }
6342 }
6343 if (method_array_count == 0) {
6344 continue;
6345 }
6346 auto* method_array = if_table->GetMethodArray(i);
6347 for (size_t j = 0; j < method_array_count; ++j) {
6348 ArtMethod* implementation_method =
6349 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6350 if (ignore_copied_methods && implementation_method->IsCopied()) {
6351 continue;
6352 }
6353 DCHECK(implementation_method != nullptr);
6354 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6355 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6356 // or interface methods in the IMT here they will not create extra conflicts since we compare
6357 // names and signatures in SetIMTRef.
6358 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006359 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006360
6361 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6362 // the same implementation method, keep track of this to avoid creating a conflict table in
6363 // this case.
6364
6365 // Conflict table size for each IMT slot.
6366 ++conflict_counts[imt_index];
6367
6368 SetIMTRef(unimplemented_method,
6369 imt_conflict_method,
6370 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006371 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006372 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006373 }
6374 }
6375
6376 if (create_conflict_tables) {
6377 // Create the conflict tables.
6378 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006379 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006380 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006381 if (imt[i] == imt_conflict_method) {
6382 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6383 if (new_table != nullptr) {
6384 ArtMethod* new_conflict_method =
6385 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6386 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6387 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006388 } else {
6389 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006390 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006391 }
6392 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006393 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006394 }
6395 }
6396
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006397 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006398 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006399 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6400 // Virtual methods can be larger than the if table methods if there are default methods.
6401 if (method_array_count == 0) {
6402 continue;
6403 }
6404 auto* method_array = if_table->GetMethodArray(i);
6405 for (size_t j = 0; j < method_array_count; ++j) {
6406 ArtMethod* implementation_method =
6407 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6408 if (ignore_copied_methods && implementation_method->IsCopied()) {
6409 continue;
6410 }
6411 DCHECK(implementation_method != nullptr);
6412 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006413 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006414 if (!imt[imt_index]->IsRuntimeMethod() ||
6415 imt[imt_index] == unimplemented_method ||
6416 imt[imt_index] == imt_conflict_method) {
6417 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006418 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006419 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6420 const size_t num_entries = table->NumEntries(image_pointer_size_);
6421 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6422 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006423 }
6424 }
6425 }
6426}
6427
Alex Lighteb7c1442015-08-31 13:17:42 -07006428// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6429// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006430static bool NotSubinterfaceOfAny(
6431 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6432 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006433 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006434 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006435 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006436 for (ObjPtr<mirror::Class> c : classes) {
6437 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006438 return false;
6439 }
6440 }
6441 return true;
6442}
6443
6444// Fills in and flattens the interface inheritance hierarchy.
6445//
6446// By the end of this function all interfaces in the transitive closure of to_process are added to
6447// the iftable and every interface precedes all of its sub-interfaces in this list.
6448//
6449// all I, J: Interface | I <: J implies J precedes I
6450//
6451// (note A <: B means that A is a subtype of B)
6452//
6453// This returns the total number of items in the iftable. The iftable might be resized down after
6454// this call.
6455//
6456// We order this backwards so that we do not need to reorder superclass interfaces when new
6457// interfaces are added in subclass's interface tables.
6458//
6459// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6460// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6461// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6462// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006463static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006464 size_t super_ifcount,
6465 std::vector<mirror::Class*> to_process)
6466 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006467 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006468 // This is the set of all class's already in the iftable. Used to make checking if a class has
6469 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006470 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006471 // The first super_ifcount elements are from the superclass. We note that they are already added.
6472 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006473 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006474 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6475 classes_in_iftable.insert(iface);
6476 }
6477 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006478 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006479 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6480 // At this point in the loop current-iface-list has the invariant that:
6481 // for every pair of interfaces I,J within it:
6482 // if index_of(I) < index_of(J) then I is not a subtype of J
6483
6484 // If we have already seen this element then all of its super-interfaces must already be in the
6485 // current-iface-list so we can skip adding it.
6486 if (!ContainsElement(classes_in_iftable, interface)) {
6487 // We haven't seen this interface so add all of its super-interfaces onto the
6488 // current-iface-list, skipping those already on it.
6489 int32_t ifcount = interface->GetIfTableCount();
6490 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006491 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006492 if (!ContainsElement(classes_in_iftable, super_interface)) {
6493 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6494 classes_in_iftable.insert(super_interface);
6495 iftable->SetInterface(filled_ifcount, super_interface);
6496 filled_ifcount++;
6497 }
6498 }
6499 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6500 // Place this interface onto the current-iface-list after all of its super-interfaces.
6501 classes_in_iftable.insert(interface);
6502 iftable->SetInterface(filled_ifcount, interface);
6503 filled_ifcount++;
6504 } else if (kIsDebugBuild) {
6505 // Check all super-interfaces are already in the list.
6506 int32_t ifcount = interface->GetIfTableCount();
6507 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006508 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006509 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006510 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6511 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006512 }
6513 }
6514 }
6515 if (kIsDebugBuild) {
6516 // Check that the iftable is ordered correctly.
6517 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006518 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006519 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006520 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006521 // !(if_a <: if_b)
6522 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006523 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6524 << ") extends "
6525 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006526 << "interface list.";
6527 }
6528 }
6529 }
6530 return filled_ifcount;
6531}
6532
6533bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6534 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6535 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006536 const bool has_superclass = klass->HasSuperClass();
6537 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006538 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006539 const size_t num_interfaces =
6540 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006541 if (num_interfaces == 0) {
6542 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006543 if (LIKELY(has_superclass)) {
6544 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6545 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006546 // Class implements no interfaces.
6547 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006548 return true;
6549 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006550 // Class implements same interfaces as parent, are any of these not marker interfaces?
6551 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006552 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006553 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006554 if (super_iftable->GetMethodArrayCount(i) > 0) {
6555 has_non_marker_interface = true;
6556 break;
6557 }
6558 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006559 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006560 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006561 klass->SetIfTable(super_iftable);
6562 return true;
6563 }
6564 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006565 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006566 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006567 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006568 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006569 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006570 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006571 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006572 if (UNLIKELY(!interface->IsInterface())) {
6573 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006574 ThrowIncompatibleClassChangeError(klass.Get(),
6575 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006576 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006577 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6578 return false;
6579 }
6580 ifcount += interface->GetIfTableCount();
6581 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006582 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006583 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006584 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006585 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006586 return false;
6587 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006588 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006589 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006590 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006591 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006592 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006593 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006594 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006595 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006596
6597 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6598 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6599 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006600 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006601
6602 size_t new_ifcount;
6603 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006604 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006605 std::vector<mirror::Class*> to_add;
6606 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006607 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006608 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006609 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006610 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006611
6612 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006613 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006614
Ian Rogers7b078e82014-09-10 14:44:24 -07006615 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006616
Ian Rogersb52b01a2012-01-12 17:01:38 -08006617 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006618 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006619 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006620 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006621 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006622 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006623 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006624 return false;
6625 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006626 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006627 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006628 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006629 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006630 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006631 return true;
6632}
6633
Alex Light1f3925d2016-09-07 12:04:20 -07006634// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6635// of methods must be unique.
6636static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6637 return nullptr;
6638}
6639
6640template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006641static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006642 const ScopedArenaVector<ArtMethod*>& list,
6643 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006644 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006645 for (ArtMethod* method : list) {
6646 if (cmp.HasSameNameAndSignature(method)) {
6647 return method;
6648 }
6649 }
Alex Light1f3925d2016-09-07 12:04:20 -07006650 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006651}
6652
Alex Light1f3925d2016-09-07 12:04:20 -07006653// Check that all vtable entries are present in this class's virtuals or are the same as a
6654// superclasses vtable entry.
6655static void CheckClassOwnsVTableEntries(Thread* self,
6656 Handle<mirror::Class> klass,
6657 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006658 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006659 StackHandleScope<2> hs(self);
6660 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006661 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006662 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006663 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006664 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6665 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6666 CHECK(m != nullptr);
6667
Alex Lighta41a30782017-03-29 11:33:19 -07006668 if (m->GetMethodIndexDuringLinking() != i) {
6669 LOG(WARNING) << m->PrettyMethod()
6670 << " has an unexpected method index for its spot in the vtable for class"
6671 << klass->PrettyClass();
6672 }
Alex Lighte64300b2015-12-15 15:02:47 -08006673 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6674 auto is_same_method = [m] (const ArtMethod& meth) {
6675 return &meth == m;
6676 };
Alex Light3f980532017-03-17 15:10:32 -07006677 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6678 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6679 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6680 << klass->PrettyClass() << " or any of its superclasses!";
6681 }
Alex Lighte64300b2015-12-15 15:02:47 -08006682 }
6683}
6684
Alex Light1f3925d2016-09-07 12:04:20 -07006685// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6686// method is overridden in a subclass.
6687static void CheckVTableHasNoDuplicates(Thread* self,
6688 Handle<mirror::Class> klass,
6689 PointerSize pointer_size)
6690 REQUIRES_SHARED(Locks::mutator_lock_) {
6691 StackHandleScope<1> hs(self);
6692 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6693 int32_t num_entries = vtable->GetLength();
6694 for (int32_t i = 0; i < num_entries; i++) {
6695 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6696 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6697 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6698 vtable_entry->GetAccessFlags())) {
6699 continue;
6700 }
6701 MethodNameAndSignatureComparator name_comparator(
6702 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006703 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006704 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006705 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6706 other_entry->GetAccessFlags())) {
6707 continue;
6708 }
Alex Light3f980532017-03-17 15:10:32 -07006709 if (vtable_entry == other_entry ||
6710 name_comparator.HasSameNameAndSignature(
6711 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6712 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6713 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6714 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6715 << other_entry->PrettyMethod() << " (0x" << std::hex
6716 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6717 }
Alex Light1f3925d2016-09-07 12:04:20 -07006718 }
6719 }
6720}
6721
6722static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6723 REQUIRES_SHARED(Locks::mutator_lock_) {
6724 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6725 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6726}
6727
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006728void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6729 ArtMethod* unimplemented_method,
6730 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006731 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006732 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006733 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006734 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006735 if (super_class->ShouldHaveImt()) {
6736 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6737 for (size_t i = 0; i < ImTable::kSize; ++i) {
6738 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006739 }
6740 } else {
6741 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006742 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006743 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006744 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006745 FillIMTFromIfTable(if_table,
6746 unimplemented_method,
6747 imt_conflict_method,
6748 klass.Get(),
6749 /*create_conflict_table*/false,
6750 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006751 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006752 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006753 }
6754 }
6755}
6756
Vladimir Marko921094a2017-01-12 18:37:06 +00006757class ClassLinker::LinkInterfaceMethodsHelper {
6758 public:
6759 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6760 Handle<mirror::Class> klass,
6761 Thread* self,
6762 Runtime* runtime)
6763 : class_linker_(class_linker),
6764 klass_(klass),
6765 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6766 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6767 self_(self),
6768 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6769 allocator_(&stack_),
6770 default_conflict_methods_(allocator_.Adapter()),
6771 overriding_default_conflict_methods_(allocator_.Adapter()),
6772 miranda_methods_(allocator_.Adapter()),
6773 default_methods_(allocator_.Adapter()),
6774 overriding_default_methods_(allocator_.Adapter()),
6775 move_table_(allocator_.Adapter()) {
6776 }
6777
6778 ArtMethod* FindMethod(ArtMethod* interface_method,
6779 MethodNameAndSignatureComparator& interface_name_comparator,
6780 ArtMethod* vtable_impl)
6781 REQUIRES_SHARED(Locks::mutator_lock_);
6782
6783 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6784 MethodNameAndSignatureComparator& interface_name_comparator)
6785 REQUIRES_SHARED(Locks::mutator_lock_);
6786
6787 bool HasNewVirtuals() const {
6788 return !(miranda_methods_.empty() &&
6789 default_methods_.empty() &&
6790 overriding_default_methods_.empty() &&
6791 overriding_default_conflict_methods_.empty() &&
6792 default_conflict_methods_.empty());
6793 }
6794
6795 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6796
6797 ObjPtr<mirror::PointerArray> UpdateVtable(
6798 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6799 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6800
6801 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6802
6803 void UpdateIMT(ArtMethod** out_imt);
6804
6805 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6806 if (kIsDebugBuild) {
6807 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6808 // Check that there are no stale methods are in the dex cache array.
6809 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6810 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006811 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6812 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006813 CHECK(move_table_.find(m) == move_table_.end() ||
6814 // The original versions of copied methods will still be present so allow those too.
6815 // Note that if the first check passes this might fail to GetDeclaringClass().
6816 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6817 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6818 [m] (ArtMethod& meth) {
6819 return &meth == m;
6820 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6821 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6822 }
6823 }
6824 }
6825
6826 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6827 LengthPrefixedArray<ArtMethod>* methods) {
6828 if (kIsDebugBuild) {
6829 CHECK(methods != nullptr);
6830 // Put some random garbage in old methods to help find stale pointers.
6831 if (methods != old_methods && old_methods != nullptr) {
6832 // Need to make sure the GC is not running since it could be scanning the methods we are
6833 // about to overwrite.
6834 ScopedThreadStateChange tsc(self_, kSuspended);
6835 gc::ScopedGCCriticalSection gcs(self_,
6836 gc::kGcCauseClassLinker,
6837 gc::kCollectorTypeClassLinker);
6838 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6839 method_size_,
6840 method_alignment_);
6841 memset(old_methods, 0xFEu, old_size);
6842 }
6843 }
6844 }
6845
6846 private:
6847 size_t NumberOfNewVirtuals() const {
6848 return miranda_methods_.size() +
6849 default_methods_.size() +
6850 overriding_default_conflict_methods_.size() +
6851 overriding_default_methods_.size() +
6852 default_conflict_methods_.size();
6853 }
6854
6855 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6856 return !klass_->IsInterface();
6857 }
6858
6859 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6860 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6861 << "Interfaces should only have default-conflict methods appended to them.";
6862 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6863 << miranda_methods_.size()
6864 << " default_methods=" << default_methods_.size()
6865 << " overriding_default_methods=" << overriding_default_methods_.size()
6866 << " default_conflict_methods=" << default_conflict_methods_.size()
6867 << " overriding_default_conflict_methods="
6868 << overriding_default_conflict_methods_.size();
6869 }
6870
6871 ClassLinker* class_linker_;
6872 Handle<mirror::Class> klass_;
6873 size_t method_alignment_;
6874 size_t method_size_;
6875 Thread* const self_;
6876
6877 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6878 // the virtual methods array.
6879 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6880 // during cross compilation.
6881 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6882 ArenaStack stack_;
6883 ScopedArenaAllocator allocator_;
6884
6885 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6886 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6887 ScopedArenaVector<ArtMethod*> miranda_methods_;
6888 ScopedArenaVector<ArtMethod*> default_methods_;
6889 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6890
6891 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6892};
6893
6894ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6895 ArtMethod* interface_method,
6896 MethodNameAndSignatureComparator& interface_name_comparator,
6897 ArtMethod* vtable_impl) {
6898 ArtMethod* current_method = nullptr;
6899 switch (class_linker_->FindDefaultMethodImplementation(self_,
6900 interface_method,
6901 klass_,
6902 /*out*/&current_method)) {
6903 case DefaultMethodSearchResult::kDefaultConflict: {
6904 // Default method conflict.
6905 DCHECK(current_method == nullptr);
6906 ArtMethod* default_conflict_method = nullptr;
6907 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6908 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6909 default_conflict_method = vtable_impl;
6910 } else {
6911 // See if we already have a conflict method for this method.
6912 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6913 interface_name_comparator,
6914 default_conflict_methods_,
6915 overriding_default_conflict_methods_);
6916 if (LIKELY(preexisting_conflict != nullptr)) {
6917 // We already have another conflict we can reuse.
6918 default_conflict_method = preexisting_conflict;
6919 } else {
6920 // Note that we do this even if we are an interface since we need to create this and
6921 // cannot reuse another classes.
6922 // Create a new conflict method for this to use.
6923 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6924 new(default_conflict_method) ArtMethod(interface_method,
6925 class_linker_->GetImagePointerSize());
6926 if (vtable_impl == nullptr) {
6927 // Save the conflict method. We need to add it to the vtable.
6928 default_conflict_methods_.push_back(default_conflict_method);
6929 } else {
6930 // Save the conflict method but it is already in the vtable.
6931 overriding_default_conflict_methods_.push_back(default_conflict_method);
6932 }
6933 }
6934 }
6935 current_method = default_conflict_method;
6936 break;
6937 } // case kDefaultConflict
6938 case DefaultMethodSearchResult::kDefaultFound: {
6939 DCHECK(current_method != nullptr);
6940 // Found a default method.
6941 if (vtable_impl != nullptr &&
6942 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6943 // We found a default method but it was the same one we already have from our
6944 // superclass. Don't bother adding it to our vtable again.
6945 current_method = vtable_impl;
6946 } else if (LIKELY(FillTables())) {
6947 // Interfaces don't need to copy default methods since they don't have vtables.
6948 // Only record this default method if it is new to save space.
6949 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6950 // would make lookup for interface super much faster. (We would only need to scan
6951 // the iftable to find if there is a NSME or AME.)
6952 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6953 default_methods_,
6954 overriding_default_methods_);
6955 if (old == nullptr) {
6956 // We found a default method implementation and there were no conflicts.
6957 if (vtable_impl == nullptr) {
6958 // Save the default method. We need to add it to the vtable.
6959 default_methods_.push_back(current_method);
6960 } else {
6961 // Save the default method but it is already in the vtable.
6962 overriding_default_methods_.push_back(current_method);
6963 }
6964 } else {
6965 CHECK(old == current_method) << "Multiple default implementations selected!";
6966 }
6967 }
6968 break;
6969 } // case kDefaultFound
6970 case DefaultMethodSearchResult::kAbstractFound: {
6971 DCHECK(current_method == nullptr);
6972 // Abstract method masks all defaults.
6973 if (vtable_impl != nullptr &&
6974 vtable_impl->IsAbstract() &&
6975 !vtable_impl->IsDefaultConflicting()) {
6976 // We need to make this an abstract method but the version in the vtable already is so
6977 // don't do anything.
6978 current_method = vtable_impl;
6979 }
6980 break;
6981 } // case kAbstractFound
6982 }
6983 return current_method;
6984}
6985
6986ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
6987 ArtMethod* interface_method,
6988 MethodNameAndSignatureComparator& interface_name_comparator) {
6989 // Find out if there is already a miranda method we can use.
6990 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6991 miranda_methods_);
6992 if (miranda_method == nullptr) {
6993 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
6994 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6995 CHECK(miranda_method != nullptr);
6996 // Point the interface table at a phantom slot.
6997 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
6998 miranda_methods_.push_back(miranda_method);
6999 }
7000 return miranda_method;
7001}
7002
7003void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7004 LogNewVirtuals();
7005
7006 const size_t old_method_count = klass_->NumMethods();
7007 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7008 DCHECK_NE(old_method_count, new_method_count);
7009
7010 // Attempt to realloc to save RAM if possible.
7011 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7012 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7013 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7014 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7015 // CopyFrom has internal read barriers.
7016 //
7017 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7018 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7019 method_size_,
7020 method_alignment_);
7021 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7022 method_size_,
7023 method_alignment_);
7024 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7025 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007026 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007027 self_, old_methods, old_methods_ptr_size, new_size));
7028 CHECK(methods != nullptr); // Native allocation failure aborts.
7029
7030 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7031 if (methods != old_methods) {
7032 // Maps from heap allocated miranda method to linear alloc miranda method.
7033 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7034 // Copy over the old methods.
7035 for (auto& m : klass_->GetMethods(pointer_size)) {
7036 move_table_.emplace(&m, &*out);
7037 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7038 // barriers when it copies.
7039 out->CopyFrom(&m, pointer_size);
7040 ++out;
7041 }
7042 }
7043 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7044 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7045 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007046 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7047 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007048 ArtMethod& new_method = *out;
7049 new_method.CopyFrom(mir_method, pointer_size);
7050 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7051 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7052 << "Miranda method should be abstract!";
7053 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007054 // Update the entry in the method array, as the array will be used for future lookups,
7055 // where thread suspension is allowed.
7056 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7057 // would not see them.
7058 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007059 ++out;
7060 }
7061 // We need to copy the default methods into our own method table since the runtime requires that
7062 // every method on a class's vtable be in that respective class's virtual method table.
7063 // NOTE This means that two classes might have the same implementation of a method from the same
7064 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7065 // default method found on a class with one found on the declaring interface directly and must
7066 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007067 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7068 &overriding_default_methods_}) {
7069 for (size_t i = 0; i < methods_vec->size(); ++i) {
7070 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007071 ArtMethod& new_method = *out;
7072 new_method.CopyFrom(def_method, pointer_size);
7073 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7074 // verified yet it shouldn't have methods that are skipping access checks.
7075 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7076 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007077 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007078 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7079 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7080 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7081 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007082 // Update the entry in the method array, as the array will be used for future lookups,
7083 // where thread suspension is allowed.
7084 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7085 // would not see them.
7086 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007087 ++out;
7088 }
7089 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007090 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7091 &overriding_default_conflict_methods_}) {
7092 for (size_t i = 0; i < methods_vec->size(); ++i) {
7093 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007094 ArtMethod& new_method = *out;
7095 new_method.CopyFrom(conf_method, pointer_size);
7096 // This is a type of default method (there are default method impls, just a conflict) so
7097 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7098 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7099 // methods that are skipping access checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007100 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007101 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7102 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7103 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7104 DCHECK(new_method.IsDefaultConflicting());
7105 // The actual method might or might not be marked abstract since we just copied it from a
7106 // (possibly default) interface method. We need to set it entry point to be the bridge so
7107 // that the compiler will not invoke the implementation of whatever method we copied from.
7108 EnsureThrowsInvocationError(class_linker_, &new_method);
7109 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007110 // Update the entry in the method array, as the array will be used for future lookups,
7111 // where thread suspension is allowed.
7112 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7113 // would not see them.
7114 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007115 ++out;
7116 }
7117 }
7118 methods->SetSize(new_method_count);
7119 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7120}
7121
7122ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7123 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7124 ObjPtr<mirror::PointerArray> old_vtable) {
7125 // Update the vtable to the new method structures. We can skip this for interfaces since they
7126 // do not have vtables.
7127 const size_t old_vtable_count = old_vtable->GetLength();
7128 const size_t new_vtable_count = old_vtable_count +
7129 miranda_methods_.size() +
7130 default_methods_.size() +
7131 default_conflict_methods_.size();
7132
7133 ObjPtr<mirror::PointerArray> vtable =
7134 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7135 if (UNLIKELY(vtable == nullptr)) {
7136 self_->AssertPendingOOMException();
7137 return nullptr;
7138 }
7139
7140 size_t vtable_pos = old_vtable_count;
7141 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7142 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7143 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7144 default_conflict_methods_,
7145 miranda_methods_}) {
7146 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007147 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007148 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7149 // fields are references into the dex file the method was defined in. Since the ArtMethod
7150 // does not store that information it uses declaring_class_->dex_cache_.
7151 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7152 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7153 ++vtable_pos;
7154 }
7155 }
7156 DCHECK_EQ(vtable_pos, new_vtable_count);
7157
7158 // Update old vtable methods. We use the default_translations map to figure out what each
7159 // vtable entry should be updated to, if they need to be at all.
7160 for (size_t i = 0; i < old_vtable_count; ++i) {
7161 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7162 // Try and find what we need to change this method to.
7163 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007164 if (translation_it != default_translations.end()) {
7165 if (translation_it->second.IsInConflict()) {
7166 // Find which conflict method we are to use for this method.
7167 MethodNameAndSignatureComparator old_method_comparator(
7168 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7169 // We only need to look through overriding_default_conflict_methods since this is an
7170 // overridden method we are fixing up here.
7171 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7172 old_method_comparator, overriding_default_conflict_methods_);
7173 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7174 translated_method = new_conflict_method;
7175 } else if (translation_it->second.IsAbstract()) {
7176 // Find which miranda method we are to use for this method.
7177 MethodNameAndSignatureComparator old_method_comparator(
7178 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7179 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7180 miranda_methods_);
7181 DCHECK(miranda_method != nullptr);
7182 translated_method = miranda_method;
7183 } else {
7184 // Normal default method (changed from an older default or abstract interface method).
7185 DCHECK(translation_it->second.IsTranslation());
7186 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007187 auto it = move_table_.find(translated_method);
7188 DCHECK(it != move_table_.end());
7189 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007190 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007191 } else {
7192 auto it = move_table_.find(translated_method);
7193 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007194 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007195
7196 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007197 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007198 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007199 if (kIsDebugBuild) {
7200 auto* methods = klass_->GetMethodsPtr();
7201 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007202 reinterpret_cast<uintptr_t>(translated_method));
7203 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007204 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7205 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007206 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007207 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007208 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007209 }
7210 }
7211 klass_->SetVTable(vtable.Ptr());
7212 return vtable;
7213}
7214
7215void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7216 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7217 const size_t ifcount = klass_->GetIfTableCount();
7218 // Go fix up all the stale iftable pointers.
7219 for (size_t i = 0; i < ifcount; ++i) {
7220 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7221 auto* method_array = iftable->GetMethodArray(i);
7222 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7223 DCHECK(m != nullptr) << klass_->PrettyClass();
7224 auto it = move_table_.find(m);
7225 if (it != move_table_.end()) {
7226 auto* new_m = it->second;
7227 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7228 method_array->SetElementPtrSize(j, new_m, pointer_size);
7229 }
7230 }
7231 }
7232}
7233
7234void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7235 // Fix up IMT next.
7236 for (size_t i = 0; i < ImTable::kSize; ++i) {
7237 auto it = move_table_.find(out_imt[i]);
7238 if (it != move_table_.end()) {
7239 out_imt[i] = it->second;
7240 }
7241 }
7242}
7243
Alex Light705ad492015-09-21 11:36:30 -07007244// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007245bool ClassLinker::LinkInterfaceMethods(
7246 Thread* self,
7247 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007248 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007249 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007250 ArtMethod** out_imt) {
7251 StackHandleScope<3> hs(self);
7252 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007253
7254 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007255 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007256 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007257 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007258 const size_t ifcount = klass->GetIfTableCount();
7259
Vladimir Marko921094a2017-01-12 18:37:06 +00007260 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007261
7262 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7263 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007264 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007265 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007266 const bool extend_super_iftable = has_superclass;
7267 if (has_superclass && fill_tables) {
7268 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007269 unimplemented_method,
7270 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007271 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007272 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007273 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007274 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7275 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007276 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007277 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7278 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007279 }
7280 }
7281
Vladimir Marko921094a2017-01-12 18:37:06 +00007282 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7283
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007284 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007285 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007286 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7287 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7288 // they will already be null. This has the additional benefit that the declarer of a miranda
7289 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007290 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007291 --i;
Alex Light9139e002015-10-09 15:59:48 -07007292 DCHECK_LT(i, ifcount);
7293
Alex Light705ad492015-09-21 11:36:30 -07007294 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007295 if (num_methods > 0) {
7296 StackHandleScope<2> hs2(self);
7297 const bool is_super = i < super_ifcount;
7298 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007299 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7300 // conflict methods. Just set this as nullptr in those cases.
7301 Handle<mirror::PointerArray> method_array(fill_tables
7302 ? hs2.NewHandle(iftable->GetMethodArray(i))
7303 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007304
Alex Lighte64300b2015-12-15 15:02:47 -08007305 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007306 ScopedNullHandle<mirror::PointerArray> null_handle;
7307 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007308 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007309
Alex Light9139e002015-10-09 15:59:48 -07007310 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7311 // and confusing. Default methods should always look through all the superclasses
7312 // because they are the last choice of an implementation. We get around this by looking
7313 // at the super-classes iftable methods (copied into method_array previously) when we are
7314 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007315 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007316 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007317 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007318 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007319 using_virtuals = true;
7320 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7321 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007322 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007323 // For a new interface, however, we need the whole vtable in case a new
7324 // interface method is implemented in the whole superclass.
7325 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007326 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007327 input_vtable_array = vtable;
7328 input_array_length = input_vtable_array->GetLength();
7329 }
Alex Lighte64300b2015-12-15 15:02:47 -08007330
Alex Lighteb7c1442015-08-31 13:17:42 -07007331 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007332 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007333 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007334 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007335 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007336 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007337 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007338 // For each method listed in the interface's method list, find the
7339 // matching method in our class's method list. We want to favor the
7340 // subclass over the superclass, which just requires walking
7341 // back from the end of the vtable. (This only matters if the
7342 // superclass defines a private method and this class redefines
7343 // it -- otherwise it would use the same vtable slot. In .dex files
7344 // those don't end up in the virtual method table, so it shouldn't
7345 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007346 //
7347 // To find defaults we need to do the same but also go over interfaces.
7348 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007349 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007350 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007351 ArtMethod* vtable_method = using_virtuals ?
7352 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007353 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7354 ArtMethod* vtable_method_for_name_comparison =
7355 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007356 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007357 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007358 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007359 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7360 // allocations.
7361 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007362 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007363 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007364 vtable_method->PrettyMethod().c_str(),
7365 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007366 return false;
Alex Light9139e002015-10-09 15:59:48 -07007367 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007368 // We might have a newer, better, default method for this, so we just skip it. If we
7369 // are still using this we will select it again when scanning for default methods. To
7370 // obviate the need to copy the method again we will make a note that we already found
7371 // a default here.
7372 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007373 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007374 break;
7375 } else {
7376 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007377 if (LIKELY(fill_tables)) {
7378 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7379 // Place method in imt if entry is empty, place conflict otherwise.
7380 SetIMTRef(unimplemented_method,
7381 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007382 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007383 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007384 /*out*/imt_ptr);
7385 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007386 break;
7387 }
7388 }
Alex Light9139e002015-10-09 15:59:48 -07007389 }
7390 // Continue on to the next method if we are done.
7391 if (LIKELY(found_impl)) {
7392 continue;
7393 } else if (LIKELY(super_interface)) {
7394 // Don't look for a default implementation when the super-method is implemented directly
7395 // by the class.
7396 //
7397 // See if we can use the superclasses method and skip searching everything else.
7398 // Note: !found_impl && super_interface
7399 CHECK(extend_super_iftable);
7400 // If this is a super_interface method it is possible we shouldn't override it because a
7401 // superclass could have implemented it directly. We get the method the superclass used
7402 // to implement this to know if we can override it with a default method. Doing this is
7403 // safe since we know that the super_iftable is filled in so we can simply pull it from
7404 // there. We don't bother if this is not a super-classes interface since in that case we
7405 // have scanned the entire vtable anyway and would have found it.
7406 // TODO This is rather dirty but it is faster than searching through the entire vtable
7407 // every time.
7408 ArtMethod* supers_method =
7409 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7410 DCHECK(supers_method != nullptr);
7411 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007412 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007413 // The method is not overridable by a default method (i.e. it is directly implemented
7414 // in some class). Therefore move onto the next interface method.
7415 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007416 } else {
7417 // If the super-classes method is override-able by a default method we need to keep
7418 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7419 // 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 -07007420 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7421 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7422 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007423 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007424 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7425 << " and not 'nullptr' or "
7426 << supers_method->PrettyMethod()
7427 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007428 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007429 }
7430 }
7431 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007432 ArtMethod* current_method = helper.FindMethod(interface_method,
7433 interface_name_comparator,
7434 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007435 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007436 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007437 // We could not find an implementation for this method and since it is a brand new
7438 // interface we searched the entire vtable (and all default methods) for an
7439 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007440 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7441 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007442 }
7443
7444 if (current_method != nullptr) {
7445 // We found a default method implementation. Record it in the iftable and IMT.
7446 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7447 SetIMTRef(unimplemented_method,
7448 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007449 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007450 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007451 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007452 }
7453 }
Alex Light705ad492015-09-21 11:36:30 -07007454 } // For each method in interface end.
7455 } // if (num_methods > 0)
7456 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007457 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007458 if (helper.HasNewVirtuals()) {
7459 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7460 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7461 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7462
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007463 // 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 -07007464 // suspension assert.
7465 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007466
Alex Light705ad492015-09-21 11:36:30 -07007467 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007468 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007469 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007470 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007471 return false;
7472 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007473 helper.UpdateIfTable(iftable);
7474 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007475 }
Alex Light705ad492015-09-21 11:36:30 -07007476
Vladimir Marko921094a2017-01-12 18:37:06 +00007477 helper.CheckNoStaleMethodsInDexCache();
7478 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007479 } else {
7480 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007481 }
Alex Light705ad492015-09-21 11:36:30 -07007482 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007483 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007484 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007485 return true;
7486}
7487
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007488bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007489 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007490 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007491}
7492
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007493bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007494 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007495 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007496}
7497
Brian Carlstromdbc05252011-09-09 01:59:59 -07007498struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007499 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007500 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007501 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007502 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007503 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007504 // 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 -07007505 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7506 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007507 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007508 if (type1 == Primitive::kPrimNot) {
7509 // Reference always goes first.
7510 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007511 }
Vladimir Markod5777482014-11-12 17:02:02 +00007512 if (type2 == Primitive::kPrimNot) {
7513 // Reference always goes first.
7514 return false;
7515 }
7516 size_t size1 = Primitive::ComponentSize(type1);
7517 size_t size2 = Primitive::ComponentSize(type2);
7518 if (size1 != size2) {
7519 // Larger primitive types go first.
7520 return size1 > size2;
7521 }
7522 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7523 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007524 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007525 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7526 // by name and for equal names by type id index.
7527 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7528 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007529 }
7530};
7531
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007532bool ClassLinker::LinkFields(Thread* self,
7533 Handle<mirror::Class> klass,
7534 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007535 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007536 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007537 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007538 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7539 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007540
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007541 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007542 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007543 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007544 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007545 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007546 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007547 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007548 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007549 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007550 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007551 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007552 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007553
David Sehr709b0702016-10-13 09:12:37 -07007554 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007555
Brian Carlstromdbc05252011-09-09 01:59:59 -07007556 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007557 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007558 //
7559 // The overall sort order order is:
7560 // 1) All object reference fields, sorted alphabetically.
7561 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7562 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7563 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7564 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7565 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7566 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7567 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7568 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7569 //
7570 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7571 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007572 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007573 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007574 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007575 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007576 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007577 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007578 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7579 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007580
Fred Shih381e4ca2014-08-25 17:24:27 -07007581 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007582 size_t current_field = 0;
7583 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007584 FieldGaps gaps;
7585
Brian Carlstromdbc05252011-09-09 01:59:59 -07007586 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007587 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007588 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007589 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007590 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007591 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007592 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007593 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7594 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007595 MemberOffset old_offset = field_offset;
7596 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7597 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7598 }
Roland Levillain14d90572015-07-16 10:52:26 +01007599 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007600 grouped_and_sorted_fields.pop_front();
7601 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007602 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007603 field_offset = MemberOffset(field_offset.Uint32Value() +
7604 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007605 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007606 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7607 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007608 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7609 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7610 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7611 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007612 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7613 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007614 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007615
Elliott Hughesadb460d2011-10-05 17:02:34 -07007616 // 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 -07007617 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007618 // We know there are no non-reference fields in the Reference classes, and we know
7619 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007620 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007621 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007622 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007623 --num_reference_fields;
7624 }
7625
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007626 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007627 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007628 if (is_static) {
7629 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007630 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007631 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007632 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007633 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007634 if (num_reference_fields == 0 || super_class == nullptr) {
7635 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007636 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007637 if (super_class == nullptr ||
7638 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7639 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007640 }
7641 }
7642 if (kIsDebugBuild) {
7643 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7644 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007645 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007646 while (cur_super != nullptr) {
7647 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7648 cur_super = cur_super->GetSuperClass();
7649 }
7650 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007651 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007652 } else {
7653 // Check that there is at least num_reference_fields other than Object.class.
7654 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007655 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007656 }
7657 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007658 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007659 std::string temp;
7660 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7661 size_t previous_size = klass->GetObjectSize();
7662 if (previous_size != 0) {
7663 // Make sure that we didn't originally have an incorrect size.
7664 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007665 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007666 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007667 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007668 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007669
7670 if (kIsDebugBuild) {
7671 // Make sure that the fields array is ordered by name but all reference
7672 // offsets are at the beginning as far as alignment allows.
7673 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007674 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007675 : klass->GetFirstReferenceInstanceFieldOffset();
7676 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7677 num_reference_fields *
7678 sizeof(mirror::HeapReference<mirror::Object>));
7679 MemberOffset current_ref_offset = start_ref_offset;
7680 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007681 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007682 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007683 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7684 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007685 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007686 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007687 // NOTE: The field names can be the same. This is not possible in the Java language
7688 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007689 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007690 }
7691 Primitive::Type type = field->GetTypeAsPrimitiveType();
7692 bool is_primitive = type != Primitive::kPrimNot;
7693 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7694 strcmp("referent", field->GetName()) == 0) {
7695 is_primitive = true; // We lied above, so we have to expect a lie here.
7696 }
7697 MemberOffset offset = field->GetOffsetDuringLinking();
7698 if (is_primitive) {
7699 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7700 // Shuffled before references.
7701 size_t type_size = Primitive::ComponentSize(type);
7702 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7703 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7704 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7705 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7706 }
7707 } else {
7708 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7709 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7710 sizeof(mirror::HeapReference<mirror::Object>));
7711 }
7712 }
7713 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7714 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007715 return true;
7716}
7717
Vladimir Marko76649e82014-11-10 18:32:59 +00007718// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007719void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007720 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007721 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007722 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007723 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007724 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007725 // Compute reference offsets unless our superclass overflowed.
7726 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7727 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007728 if (num_reference_fields != 0u) {
7729 // All of the fields that contain object references are guaranteed be grouped in memory
7730 // starting at an appropriately aligned address after super class object data.
7731 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7732 sizeof(mirror::HeapReference<mirror::Object>));
7733 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007734 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007735 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007736 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007737 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007738 reference_offsets |= (0xffffffffu << start_bit) &
7739 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007740 }
7741 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007742 }
7743 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007744 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007745}
7746
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007747ObjPtr<mirror::String> ClassLinker::ResolveString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007748 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007749 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007750 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007751 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007752 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007753 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007754 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007755 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07007756 uint32_t utf16_length;
7757 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007758 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007759 if (string != nullptr) {
7760 dex_cache->SetResolvedString(string_idx, string);
7761 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007762 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007763}
7764
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007765ObjPtr<mirror::String> ClassLinker::LookupString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007766 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007767 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007768 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007769 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007770 return resolved;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007771 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007772 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007773 uint32_t utf16_length;
7774 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007775 ObjPtr<mirror::String> string =
7776 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007777 if (string != nullptr) {
7778 dex_cache->SetResolvedString(string_idx, string);
7779 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007780 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007781}
7782
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007783ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
7784 ObjPtr<mirror::DexCache> dex_cache,
7785 ObjPtr<mirror::ClassLoader> class_loader) {
7786 const DexFile& dex_file = *dex_cache->GetDexFile();
7787 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7788 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7789 ObjPtr<mirror::Class> type = nullptr;
7790 if (descriptor[1] == '\0') {
7791 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7792 // for primitive classes that aren't backed by dex files.
7793 type = FindPrimitiveClass(descriptor[0]);
7794 } else {
7795 Thread* const self = Thread::Current();
7796 DCHECK(self != nullptr);
7797 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7798 // Find the class in the loaded classes table.
7799 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
7800 }
7801 if (type != nullptr) {
7802 if (type->IsResolved()) {
7803 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07007804 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007805 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007806 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007807 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007808 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007809}
7810
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007811ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
7812 Handle<mirror::DexCache> dex_cache,
7813 Handle<mirror::ClassLoader> class_loader) {
7814 Thread* self = Thread::Current();
7815 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
7816 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
7817 if (resolved != nullptr) {
7818 // TODO: we used to throw here if resolved's class loader was not the
7819 // boot class loader. This was to permit different classes with the
7820 // same name to be loaded simultaneously by different loaders
7821 dex_cache->SetResolvedType(type_idx, resolved);
7822 } else {
7823 CHECK(self->IsExceptionPending())
7824 << "Expected pending exception for failed resolution of: " << descriptor;
7825 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7826 StackHandleScope<1> hs(self);
7827 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
7828 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
7829 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7830 self->ClearException();
7831 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7832 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007833 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007834 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007835 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007836 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00007837 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007838}
7839
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007840ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
7841 ObjPtr<mirror::DexCache> dex_cache,
7842 ObjPtr<mirror::ClassLoader> class_loader,
7843 uint32_t method_idx) {
7844 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7845 // functions can optimize the search if the dex_cache is the same as the DexCache
7846 // of the class, with fall-back to name and signature search otherwise.
7847 ArtMethod* resolved = nullptr;
7848 if (klass->IsInterface()) {
7849 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7850 } else {
7851 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7852 }
7853 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil6ca80d22018-03-12 18:01:18 +00007854 if (resolved != nullptr &&
Narayan Kamathe453a8d2018-04-03 15:23:46 +01007855 hiddenapi::GetMemberAction(
7856 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
David Brazdil6ca80d22018-03-12 18:01:18 +00007857 resolved = nullptr;
7858 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007859 if (resolved != nullptr) {
7860 // In case of jmvti, the dex file gets verified before being registered, so first
7861 // check if it's registered before checking class tables.
7862 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007863 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
7864 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007865 << "DexFile referrer: " << dex_file.GetLocation()
7866 << " ClassLoader: " << DescribeLoaders(class_loader, "");
7867 // Be a good citizen and update the dex cache to speed subsequent calls.
7868 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007869 // Disable the following invariant check as the verifier breaks it. b/73760543
7870 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7871 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
7872 // << "Method: " << resolved->PrettyMethod() << ", "
7873 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
7874 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007875 }
7876 return resolved;
7877}
7878
David Brazdil54a99cf2018-04-05 16:57:32 +01007879// Returns true if `method` is either null or hidden.
7880// Does not print any warnings if it is hidden.
7881static bool CheckNoSuchMethod(ArtMethod* method,
7882 ObjPtr<mirror::DexCache> dex_cache,
7883 ObjPtr<mirror::ClassLoader> class_loader)
7884 REQUIRES_SHARED(Locks::mutator_lock_) {
7885 return method == nullptr ||
7886 hiddenapi::GetMemberAction(method,
7887 class_loader,
7888 dex_cache,
7889 hiddenapi::kNone) // do not print warnings
7890 == hiddenapi::kDeny;
7891}
7892
7893ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
7894 ObjPtr<mirror::DexCache> dex_cache,
7895 ObjPtr<mirror::ClassLoader> class_loader,
7896 uint32_t method_idx) {
7897 if (klass->IsInterface()) {
7898 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7899 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
7900 } else {
7901 // If there was an interface method with the same signature, we would have
7902 // found it in the "copied" methods. Only DCHECK that the interface method
7903 // really does not exist.
7904 if (kIsDebugBuild) {
7905 ArtMethod* method =
7906 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7907 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
7908 }
7909 return nullptr;
7910 }
7911}
7912
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007913template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00007914ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007915 Handle<mirror::DexCache> dex_cache,
7916 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007917 ArtMethod* referrer,
7918 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007919 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007920 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007921 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007922 PointerSize pointer_size = image_pointer_size_;
7923 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007924 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007925 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7926 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007927 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7928 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007929 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007930 return resolved;
7931 }
Vladimir Marko89011192017-12-11 13:45:05 +00007932 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007933 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007934 ObjPtr<mirror::Class> klass = nullptr;
7935 if (valid_dex_cache_method) {
7936 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7937 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007938 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007939 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007940 // We normaly should not end up here. However the verifier currently doesn't guarantee
7941 // the invariant of having the klass in the class table. b/73760543
7942 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007943 }
Vladimir Markoba118822017-06-12 15:41:56 +01007944 } else {
7945 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007946 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01007947 if (klass == nullptr) {
7948 DCHECK(Thread::Current()->IsExceptionPending());
7949 return nullptr;
7950 }
7951 }
7952
7953 // Check if the invoke type matches the class type.
7954 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
7955 CheckInvokeClassMismatch</* kThrow */ true>(
7956 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007957 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007958 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007959 }
Vladimir Markoba118822017-06-12 15:41:56 +01007960
7961 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007962 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007963 }
Vladimir Markoba118822017-06-12 15:41:56 +01007964
7965 // Note: We can check for IllegalAccessError only if we have a referrer.
7966 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
7967 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
7968 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
7969 if (!referring_class->CheckResolvedMethodAccess(methods_class,
7970 resolved,
7971 dex_cache.Get(),
7972 method_idx,
7973 type)) {
7974 DCHECK(Thread::Current()->IsExceptionPending());
7975 return nullptr;
7976 }
7977 }
7978
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007979 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01007980 if (LIKELY(resolved != nullptr) &&
7981 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
7982 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007983 return resolved;
7984 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007985 // If we had a method, or if we can find one with another lookup type,
7986 // it's an incompatible-class-change error.
7987 if (resolved == nullptr) {
David Brazdil54a99cf2018-04-05 16:57:32 +01007988 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007989 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007990 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007991 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007992 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007993 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007994 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7995 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01007996 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07007997 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007998 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007999 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008000 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008001}
8002
Vladimir Marko89011192017-12-11 13:45:05 +00008003ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008004 Handle<mirror::DexCache> dex_cache,
8005 Handle<mirror::ClassLoader> class_loader) {
8006 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008007 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008008 if (resolved != nullptr) {
8009 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008010 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8011 return resolved;
8012 }
8013 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008014 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
8015 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008016 if (klass == nullptr) {
8017 Thread::Current()->AssertPendingException();
8018 return nullptr;
8019 }
8020 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008021 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8022 } else {
8023 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008024 }
David Brazdil6ca80d22018-03-12 18:01:18 +00008025 if (resolved != nullptr &&
Narayan Kamathe453a8d2018-04-03 15:23:46 +01008026 hiddenapi::GetMemberAction(
8027 resolved, class_loader.Get(), dex_cache.Get(), hiddenapi::kLinking) == hiddenapi::kDeny) {
David Brazdil6ca80d22018-03-12 18:01:18 +00008028 resolved = nullptr;
8029 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008030 return resolved;
8031}
8032
Vladimir Markof44d36c2017-03-14 14:18:46 +00008033ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8034 ObjPtr<mirror::DexCache> dex_cache,
8035 ObjPtr<mirror::ClassLoader> class_loader,
8036 bool is_static) {
8037 const DexFile& dex_file = *dex_cache->GetDexFile();
8038 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8039 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8040 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008041 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008042 }
8043 if (klass == nullptr) {
8044 // The class has not been resolved yet, so the field is also unresolved.
8045 return nullptr;
8046 }
8047 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008048
David Brazdild5274382018-05-04 11:28:03 +01008049 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008050}
8051
Vladimir Markoe11dd502017-12-08 14:09:45 +00008052ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008053 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008054 Handle<mirror::ClassLoader> class_loader,
8055 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008056 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008057 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008058 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008059 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008060 return resolved;
8061 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008062 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008063 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008064 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008065 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008066 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008067 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008068 }
8069
David Brazdild5274382018-05-04 11:28:03 +01008070 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008071 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008072 const char* name = dex_file.GetFieldName(field_id);
8073 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil6ca80d22018-03-12 18:01:18 +00008074 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil6ca80d22018-03-12 18:01:18 +00008075 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008076 return resolved;
8077}
8078
Vladimir Markoe11dd502017-12-08 14:09:45 +00008079ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008080 Handle<mirror::DexCache> dex_cache,
8081 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008082 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008083 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008084 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008085 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008086 return resolved;
8087 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008088 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008089 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008090 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008091 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008092 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008093 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008094 }
8095
David Brazdild5274382018-05-04 11:28:03 +01008096 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8097 if (resolved == nullptr) {
8098 const char* name = dex_file.GetFieldName(field_id);
8099 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008100 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008101 }
8102 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008103}
8104
David Brazdild5274382018-05-04 11:28:03 +01008105ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8106 ObjPtr<mirror::DexCache> dex_cache,
8107 ObjPtr<mirror::ClassLoader> class_loader,
8108 uint32_t field_idx,
8109 bool is_static) {
8110 ArtField* resolved = nullptr;
8111 Thread* self = is_static ? Thread::Current() : nullptr;
8112 const DexFile& dex_file = *dex_cache->GetDexFile();
8113
8114 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8115 : klass->FindInstanceField(dex_cache, field_idx);
8116
8117 if (resolved == nullptr) {
8118 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8119 const char* name = dex_file.GetFieldName(field_id);
8120 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8121 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8122 : klass->FindInstanceField(name, type);
8123 }
8124
8125 if (resolved != nullptr &&
8126 hiddenapi::GetMemberAction(
8127 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
8128 resolved = nullptr;
8129 }
8130
8131 if (resolved != nullptr) {
8132 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8133 }
8134
8135 return resolved;
8136}
8137
8138ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8139 ObjPtr<mirror::DexCache> dex_cache,
8140 ObjPtr<mirror::ClassLoader> class_loader,
8141 uint32_t field_idx) {
8142 ArtField* resolved = nullptr;
8143 Thread* self = Thread::Current();
8144 const DexFile& dex_file = *dex_cache->GetDexFile();
8145 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8146
8147 const char* name = dex_file.GetFieldName(field_id);
8148 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8149 resolved = mirror::Class::FindField(self, klass, name, type);
8150
8151 if (resolved != nullptr &&
8152 hiddenapi::GetMemberAction(
8153 resolved, class_loader, dex_cache, hiddenapi::kLinking) == hiddenapi::kDeny) {
8154 resolved = nullptr;
8155 }
8156
8157 if (resolved != nullptr) {
8158 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8159 }
8160
8161 return resolved;
8162}
8163
Vladimir Markoaf940202017-12-08 15:01:18 +00008164ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8165 Thread* self,
8166 uint32_t proto_idx,
8167 Handle<mirror::DexCache> dex_cache,
8168 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008169 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008170 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008171
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008172 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008173 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008174 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008175 }
8176
Narayan Kamath25352fc2016-08-03 12:46:58 +01008177 StackHandleScope<4> hs(self);
8178
8179 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008180 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008181 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8182 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008183 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008184 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008185 DCHECK(self->IsExceptionPending());
8186 return nullptr;
8187 }
8188
8189 // Then resolve the argument types.
8190 //
8191 // TODO: Is there a better way to figure out the number of method arguments
8192 // other than by looking at the shorty ?
8193 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8194
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008195 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008196 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008197 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8198 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008199 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008200 DCHECK(self->IsExceptionPending());
8201 return nullptr;
8202 }
8203
8204 DexFileParameterIterator it(dex_file, proto_id);
8205 int32_t i = 0;
8206 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8207 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008208 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008209 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008210 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008211 DCHECK(self->IsExceptionPending());
8212 return nullptr;
8213 }
8214
8215 method_params->Set(i++, param_class.Get());
8216 }
8217
8218 DCHECK(!it.HasNext());
8219
8220 Handle<mirror::MethodType> type = hs.NewHandle(
8221 mirror::MethodType::Create(self, return_type, method_params));
8222 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8223
8224 return type.Get();
8225}
8226
Vladimir Markoaf940202017-12-08 15:01:18 +00008227ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
8228 uint32_t proto_idx,
8229 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008230 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008231 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8232 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008233 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008234}
8235
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008236mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8237 Thread* self,
8238 const DexFile::MethodHandleItem& method_handle,
8239 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008240 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008241 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8242 mirror::MethodHandle::Kind kind;
8243 bool is_static;
8244 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008245 switch (handle_type) {
8246 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008247 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008248 is_static = true;
8249 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008250 break;
8251 }
8252 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008253 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008254 is_static = true;
8255 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008256 break;
8257 }
8258 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008259 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008260 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008261 num_params = 2;
8262 break;
8263 }
8264 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008265 kind = mirror::MethodHandle::Kind::kInstanceGet;
8266 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008267 num_params = 1;
8268 break;
8269 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008270 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008271 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008272 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008273 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008274 case DexFile::MethodHandleType::kInvokeInterface:
8275 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008276 }
8277
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008278 ArtField* target_field =
8279 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8280 if (LIKELY(target_field != nullptr)) {
8281 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8282 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8283 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8284 ThrowIllegalAccessErrorField(referring_class, target_field);
8285 return nullptr;
8286 }
8287 } else {
8288 DCHECK(Thread::Current()->IsExceptionPending());
8289 return nullptr;
8290 }
8291
8292 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008293 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8294 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8295 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8296 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008297 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008298 DCHECK(self->IsExceptionPending());
8299 return nullptr;
8300 }
8301
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008302 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008303 Handle<mirror::Class> return_type;
8304 switch (handle_type) {
8305 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008306 method_params->Set(0, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008307 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8308 break;
8309 }
8310 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008311 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008312 break;
8313 }
8314 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008315 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008316 method_params->Set(1, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008317 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8318 break;
8319 }
8320 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008321 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008322 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008323 break;
8324 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008325 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008326 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008327 case DexFile::MethodHandleType::kInvokeConstructor:
8328 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008329 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008330 UNREACHABLE();
8331 }
8332
8333 for (int32_t i = 0; i < num_params; ++i) {
8334 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8335 DCHECK(self->IsExceptionPending());
8336 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008337 }
8338 }
8339
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008340 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008341 DCHECK(self->IsExceptionPending());
8342 return nullptr;
8343 }
8344
8345 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008346 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8347 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008348 DCHECK(self->IsExceptionPending());
8349 return nullptr;
8350 }
Orion Hodson631827d2017-04-10 14:53:47 +01008351
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008352 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8353 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8354}
8355
8356mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8357 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008358 const DexFile::MethodHandleItem& method_handle,
8359 ArtMethod* referrer) {
8360 DexFile::MethodHandleType handle_type =
8361 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8362 mirror::MethodHandle::Kind kind;
8363 uint32_t receiver_count = 0;
8364 ArtMethod* target_method = nullptr;
8365 switch (handle_type) {
8366 case DexFile::MethodHandleType::kStaticPut:
8367 case DexFile::MethodHandleType::kStaticGet:
8368 case DexFile::MethodHandleType::kInstancePut:
8369 case DexFile::MethodHandleType::kInstanceGet:
8370 UNREACHABLE();
8371 case DexFile::MethodHandleType::kInvokeStatic: {
8372 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8373 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008374 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8375 method_handle.field_or_method_idx_,
8376 referrer,
8377 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008378 break;
8379 }
8380 case DexFile::MethodHandleType::kInvokeInstance: {
8381 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8382 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008383 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8384 method_handle.field_or_method_idx_,
8385 referrer,
8386 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008387 break;
8388 }
8389 case DexFile::MethodHandleType::kInvokeConstructor: {
8390 // Constructors are currently implemented as a transform. They
8391 // are special cased later in this method.
8392 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8393 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008394 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8395 method_handle.field_or_method_idx_,
8396 referrer,
8397 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008398 break;
8399 }
8400 case DexFile::MethodHandleType::kInvokeDirect: {
8401 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8402 receiver_count = 1;
8403 StackHandleScope<2> hs(self);
8404 // A constant method handle with type kInvokeDirect can refer to
8405 // a method that is private or to a method in a super class. To
8406 // disambiguate the two options, we resolve the method ignoring
8407 // the invocation type to determine if the method is private. We
8408 // then resolve again specifying the intended invocation type to
8409 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008410 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008411 hs.NewHandle(referrer->GetDexCache()),
8412 hs.NewHandle(referrer->GetClassLoader()));
8413 if (UNLIKELY(target_method == nullptr)) {
8414 break;
8415 }
8416
8417 if (target_method->IsPrivate()) {
8418 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008419 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8420 method_handle.field_or_method_idx_,
8421 referrer,
8422 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008423 } else {
8424 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008425 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8426 method_handle.field_or_method_idx_,
8427 referrer,
8428 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008429 if (UNLIKELY(target_method == nullptr)) {
8430 break;
8431 }
8432 // Find the method specified in the parent in referring class
8433 // so invoke-super invokes the method in the parent of the
8434 // referrer.
8435 target_method =
8436 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8437 kRuntimePointerSize);
8438 }
8439 break;
8440 }
8441 case DexFile::MethodHandleType::kInvokeInterface: {
8442 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8443 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008444 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8445 method_handle.field_or_method_idx_,
8446 referrer,
8447 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008448 break;
8449 }
Orion Hodson631827d2017-04-10 14:53:47 +01008450 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008451
8452 if (UNLIKELY(target_method == nullptr)) {
8453 DCHECK(Thread::Current()->IsExceptionPending());
8454 return nullptr;
8455 }
8456
8457 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8458 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8459 uint32_t access_flags = target_method->GetAccessFlags();
8460 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8461 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8462 return nullptr;
8463 }
8464
8465 // Calculate the number of parameters from the method shorty. We add the
8466 // receiver count (0 or 1) and deduct one for the return value.
8467 uint32_t shorty_length;
8468 target_method->GetShorty(&shorty_length);
8469 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8470
8471 StackHandleScope<7> hs(self);
8472 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8473 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8474 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8475 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8476 if (method_params.Get() == nullptr) {
8477 DCHECK(self->IsExceptionPending());
8478 return nullptr;
8479 }
8480
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008481 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008482 if (receiver_count != 0) {
8483 // Insert receiver
8484 method_params->Set(index++, target_method->GetDeclaringClass());
8485 }
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008486 DexFileParameterIterator it(*target_method->GetDexFile(), target_method->GetPrototype());
8487 Handle<mirror::DexCache> target_method_dex_cache(hs.NewHandle(target_method->GetDexCache()));
8488 Handle<mirror::ClassLoader> target_method_class_loader(hs.NewHandle(target_method->GetClassLoader()));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008489 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008490 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008491 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008492 ObjPtr<mirror::Class> klass = ResolveType(type_idx,
8493 target_method_dex_cache,
8494 target_method_class_loader);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008495 if (nullptr == klass) {
8496 DCHECK(self->IsExceptionPending());
8497 return nullptr;
8498 }
8499 method_params->Set(index++, klass);
8500 it.Next();
8501 }
8502
Vladimir Markob45528c2017-07-27 14:14:28 +01008503 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008504 if (UNLIKELY(return_type.IsNull())) {
8505 DCHECK(self->IsExceptionPending());
8506 return nullptr;
8507 }
8508
8509 Handle<mirror::MethodType>
8510 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8511 if (UNLIKELY(method_type.IsNull())) {
8512 DCHECK(self->IsExceptionPending());
8513 return nullptr;
8514 }
8515
8516 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8517 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8518 Handle<mirror::MethodHandlesLookup> lookup =
8519 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8520 return lookup->FindConstructor(self, constructor_class, method_type);
8521 }
8522
8523 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8524 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8525}
8526
Vladimir Markoaf940202017-12-08 15:01:18 +00008527ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8528 uint32_t method_handle_idx,
8529 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008530 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008531 const DexFile* const dex_file = referrer->GetDexFile();
8532 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8533 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8534 case DexFile::MethodHandleType::kStaticPut:
8535 case DexFile::MethodHandleType::kStaticGet:
8536 case DexFile::MethodHandleType::kInstancePut:
8537 case DexFile::MethodHandleType::kInstanceGet:
8538 return ResolveMethodHandleForField(self, method_handle, referrer);
8539 case DexFile::MethodHandleType::kInvokeStatic:
8540 case DexFile::MethodHandleType::kInvokeInstance:
8541 case DexFile::MethodHandleType::kInvokeConstructor:
8542 case DexFile::MethodHandleType::kInvokeDirect:
8543 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008544 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008545 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008546}
8547
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008548bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8549 return (entry_point == GetQuickResolutionStub()) ||
8550 (quick_resolution_trampoline_ == entry_point);
8551}
8552
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008553bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8554 return (entry_point == GetQuickToInterpreterBridge()) ||
8555 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8556}
8557
8558bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8559 return (entry_point == GetQuickGenericJniStub()) ||
8560 (quick_generic_jni_trampoline_ == entry_point);
8561}
8562
David Sehra49e0532017-08-25 08:05:29 -07008563bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8564 return entry_point == GetJniDlsymLookupStub();
8565}
8566
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008567const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8568 return GetQuickGenericJniStub();
8569}
8570
Mathieu Chartiere401d142015-04-22 13:56:20 -07008571void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008572 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008573 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8574 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008575 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008576 }
8577}
8578
Alex Lightdb01a092017-04-03 15:39:55 -07008579void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8580 DCHECK(method->IsObsolete());
8581 // We cannot mess with the entrypoints of native methods because they are used to determine how
8582 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8583 if (!method->IsNative()) {
8584 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8585 }
8586}
8587
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008588void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008589 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008590 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008591 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8592 << NumNonZygoteClasses() << "\n";
8593}
8594
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008595class CountClassesVisitor : public ClassLoaderVisitor {
8596 public:
8597 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8598
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008599 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008600 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008601 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008602 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008603 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8604 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008605 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008606 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008607
8608 size_t num_zygote_classes;
8609 size_t num_non_zygote_classes;
8610};
8611
8612size_t ClassLinker::NumZygoteClasses() const {
8613 CountClassesVisitor visitor;
8614 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008615 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008616}
8617
8618size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008619 CountClassesVisitor visitor;
8620 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008621 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008622}
8623
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008624size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008625 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008626 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008627 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008628}
8629
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008630pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008631 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008632}
8633
8634pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008635 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008636}
8637
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008638void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008639 DCHECK(!init_done_);
8640
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008641 DCHECK(klass != nullptr);
8642 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008643
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008644 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008645 DCHECK(class_roots != nullptr);
8646 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008647 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008648}
8649
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008650const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8651 static const char* class_roots_descriptors[] = {
8652 "Ljava/lang/Class;",
8653 "Ljava/lang/Object;",
8654 "[Ljava/lang/Class;",
8655 "[Ljava/lang/Object;",
8656 "Ljava/lang/String;",
8657 "Ljava/lang/DexCache;",
8658 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008659 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008660 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008661 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008662 "Ljava/lang/reflect/Proxy;",
8663 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008664 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008665 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008666 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008667 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008668 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008669 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008670 "Ljava/lang/invoke/MethodType;",
Orion Hodson005ac512017-10-24 15:43:43 +01008671 "Ljava/lang/invoke/VarHandle;",
8672 "Ljava/lang/invoke/FieldVarHandle;",
8673 "Ljava/lang/invoke/ArrayElementVarHandle;",
8674 "Ljava/lang/invoke/ByteArrayViewVarHandle;",
8675 "Ljava/lang/invoke/ByteBufferViewVarHandle;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008676 "Ljava/lang/ClassLoader;",
8677 "Ljava/lang/Throwable;",
8678 "Ljava/lang/ClassNotFoundException;",
8679 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008680 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008681 "Z",
8682 "B",
8683 "C",
8684 "D",
8685 "F",
8686 "I",
8687 "J",
8688 "S",
8689 "V",
8690 "[Z",
8691 "[B",
8692 "[C",
8693 "[D",
8694 "[F",
8695 "[I",
8696 "[J",
8697 "[S",
8698 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008699 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008700 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008701 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8702 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008703
8704 const char* descriptor = class_roots_descriptors[class_root];
8705 CHECK(descriptor != nullptr);
8706 return descriptor;
8707}
8708
Calin Juravle7865ac72017-06-28 11:03:12 -07008709jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
Andreas Gampe473191c2017-12-28 16:55:31 -08008710 const std::vector<const DexFile*>& dex_files,
8711 jclass loader_class,
8712 jobject parent_loader) {
Calin Juravle7865ac72017-06-28 11:03:12 -07008713 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8714 WellKnownClasses::dalvik_system_PathClassLoader) ||
8715 self->GetJniEnv()->IsSameObject(loader_class,
8716 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8717
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008718 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8719 // We could move the jobject to the callers, but all call-sites do this...
8720 ScopedObjectAccessUnchecked soa(self);
8721
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008722 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008723 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008724
Mathieu Chartierc7853442015-03-27 14:35:38 -07008725 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008726 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008727
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008728 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008729 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008730 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008731 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008732 mirror::ObjectArray<mirror::Object>::Alloc(self,
8733 dex_elements_class.Get(),
8734 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008735 Handle<mirror::Class> h_dex_element_class =
8736 hs.NewHandle(dex_elements_class->GetComponentType());
8737
Mathieu Chartierc7853442015-03-27 14:35:38 -07008738 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008739 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008740 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008741
Andreas Gampe08883de2016-11-08 13:20:52 -08008742 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00008743 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008744
Andreas Gampe08883de2016-11-08 13:20:52 -08008745 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00008746 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008747
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008748 // Fill the elements array.
8749 int32_t index = 0;
8750 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008751 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008752
Calin Juravle7865ac72017-06-28 11:03:12 -07008753 // CreateWellKnownClassLoader is only used by gtests and compiler.
8754 // 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 -07008755 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8756 self,
8757 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008758 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008759 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008760
Mathieu Chartier3738e982017-05-12 16:07:28 -07008761 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8762 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008763 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008764 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008765 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008766 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008767
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008768 Handle<mirror::String> h_file_name = hs2.NewHandle(
8769 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008770 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008771 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8772
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008773 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008774 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008775 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008776
8777 h_dex_elements->Set(index, h_element.Get());
8778 index++;
8779 }
8780 DCHECK_EQ(index, h_dex_elements->GetLength());
8781
8782 // Create DexPathList.
8783 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008784 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008785 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008786 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008787 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08008788 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
8789 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
8790 // elements.
8791 {
8792 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
8793 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
8794 DCHECK(native_lib_dirs != nullptr);
8795 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
8796 DCHECK(list_class != nullptr);
8797 {
8798 StackHandleScope<1> h_list_scope(self);
8799 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
8800 bool list_init = EnsureInitialized(self, h_list_class, true, true);
8801 DCHECK(list_init);
8802 list_class = h_list_class.Get();
8803 }
8804 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
8805 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
8806 // is fine for testing. While it violates a Java-code invariant (the elementData field is
8807 // normally never null), as long as one does not try to add elements, this will still
8808 // work.
8809 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
8810 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008811
Calin Juravle7865ac72017-06-28 11:03:12 -07008812 // Create the class loader..
8813 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8814 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8815 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008816 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008817 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008818 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008819 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008820 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008821
8822 // Make a pretend boot-classpath.
8823 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008824 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008825 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008826 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008827 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008828 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008829 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008830
8831 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8832 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8833 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8834 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008835
8836 // Make it a global ref and return.
8837 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008838 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008839 return soa.Env()->NewGlobalRef(local_ref.get());
8840}
8841
Calin Juravle7865ac72017-06-28 11:03:12 -07008842jobject ClassLinker::CreatePathClassLoader(Thread* self,
8843 const std::vector<const DexFile*>& dex_files) {
8844 return CreateWellKnownClassLoader(self,
8845 dex_files,
8846 WellKnownClasses::dalvik_system_PathClassLoader,
8847 nullptr);
8848}
8849
Andreas Gampe8ac75952015-06-02 21:01:45 -07008850void ClassLinker::DropFindArrayClassCache() {
8851 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8852 find_array_class_cache_next_victim_ = 0;
8853}
8854
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008855void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008856 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008857 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008858 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008859 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8860 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008861 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008862 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008863 }
8864 }
8865}
8866
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008867void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8868 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008869 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008870 Thread* const self = Thread::Current();
8871 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008872 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008873 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008874 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008875 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8876 // class table was modified.
8877 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8878 }
8879}
8880
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008881void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008882 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008883 std::vector<ClassLoaderData> to_delete;
8884 // Do the delete outside the lock to avoid lock violation in jit code cache.
8885 {
8886 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8887 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8888 const ClassLoaderData& data = *it;
8889 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008890 ObjPtr<mirror::ClassLoader> class_loader =
8891 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008892 if (class_loader != nullptr) {
8893 ++it;
8894 } else {
8895 VLOG(class_linker) << "Freeing class loader";
8896 to_delete.push_back(data);
8897 it = class_loaders_.erase(it);
8898 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008899 }
8900 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008901 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinab2ce842018-02-01 19:09:59 +03008902 // CHA unloading analysis and SingleImplementaion cleanups are required.
8903 DeleteClassLoader(self, data, true /*cleanup_cha*/);
Mathieu Chartier65975772016-08-05 10:46:36 -07008904 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008905}
8906
Vladimir Marko21300532017-01-24 18:06:55 +00008907class GetResolvedClassesVisitor : public ClassVisitor {
8908 public:
8909 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8910 : result_(result),
8911 ignore_boot_classes_(ignore_boot_classes),
8912 last_resolved_classes_(result->end()),
8913 last_dex_file_(nullptr),
8914 vlog_is_on_(VLOG_IS_ON(class_linker)),
8915 extra_stats_(),
8916 last_extra_stats_(extra_stats_.end()) { }
8917
8918 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8919 if (!klass->IsProxyClass() &&
8920 !klass->IsArrayClass() &&
8921 klass->IsResolved() &&
8922 !klass->IsErroneousResolved() &&
8923 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8924 const DexFile& dex_file = klass->GetDexFile();
8925 if (&dex_file != last_dex_file_) {
8926 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008927 DexCacheResolvedClasses resolved_classes(
8928 dex_file.GetLocation(),
8929 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8930 dex_file.GetLocationChecksum(),
8931 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008932 last_resolved_classes_ = result_->find(resolved_classes);
8933 if (last_resolved_classes_ == result_->end()) {
8934 last_resolved_classes_ = result_->insert(resolved_classes).first;
8935 }
8936 }
8937 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8938 if (UNLIKELY(vlog_is_on_) && added) {
8939 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8940 if (last_extra_stats_ == extra_stats_.end() ||
8941 last_extra_stats_->first != resolved_classes) {
8942 last_extra_stats_ = extra_stats_.find(resolved_classes);
8943 if (last_extra_stats_ == extra_stats_.end()) {
8944 last_extra_stats_ =
8945 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8946 }
8947 }
8948 }
8949 }
8950 return true;
8951 }
8952
8953 void PrintStatistics() const {
8954 if (vlog_is_on_) {
8955 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8956 auto it = extra_stats_.find(std::addressof(resolved_classes));
8957 DCHECK(it != extra_stats_.end());
8958 const ExtraStats& extra_stats = it->second;
8959 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8960 << " has " << resolved_classes.GetClasses().size() << " / "
8961 << extra_stats.number_of_class_defs_ << " resolved classes";
8962 }
8963 }
8964 }
8965
8966 private:
8967 struct ExtraStats {
8968 explicit ExtraStats(uint32_t number_of_class_defs)
8969 : number_of_class_defs_(number_of_class_defs) {}
8970 uint32_t number_of_class_defs_;
8971 };
8972
8973 std::set<DexCacheResolvedClasses>* result_;
8974 bool ignore_boot_classes_;
8975 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8976 const DexFile* last_dex_file_;
8977
8978 // Statistics.
8979 bool vlog_is_on_;
8980 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8981 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8982};
8983
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008984std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008985 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008986 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008987 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008988 std::set<DexCacheResolvedClasses> ret;
8989 VLOG(class_linker) << "Collecting resolved classes";
8990 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008991 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8992 VisitClasses(&visitor);
8993 if (VLOG_IS_ON(class_linker)) {
8994 visitor.PrintStatistics();
8995 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008996 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008997 return ret;
8998}
8999
Mathieu Chartier65975772016-08-05 10:46:36 -07009000class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9001 public:
9002 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9003 : method_(method),
9004 pointer_size_(pointer_size) {}
9005
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009006 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07009007 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9008 holder_ = klass;
9009 }
9010 // Return false to stop searching if holder_ is not null.
9011 return holder_ == nullptr;
9012 }
9013
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009014 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009015 const ArtMethod* const method_;
9016 const PointerSize pointer_size_;
9017};
9018
9019mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
9020 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9021 CHECK(method->IsCopied());
9022 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9023 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009024 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07009025}
9026
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009027mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9028 return down_cast<mirror::IfTable*>(
9029 mirror::IfTable::Alloc(self,
9030 GetClassRoot(kObjectArrayClass),
9031 ifcount * mirror::IfTable::kMax));
9032}
9033
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009034// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009035template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009036 uint32_t method_idx,
9037 Handle<mirror::DexCache> dex_cache,
9038 Handle<mirror::ClassLoader> class_loader,
9039 ArtMethod* referrer,
9040 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009041template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
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);
9047
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009048} // namespace art