blob: ebac5c1661e231533cb25d346f9212156e3d33c3 [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"
Mathieu Chartiere401d142015-04-22 13:56:20 -070041#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010042#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080043#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080044#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080046#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070047#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070048#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070050#include "class_loader_utils.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070051#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000052#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080053#include "debugger.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080054#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080055#include "dex/dex_file-inl.h"
56#include "dex/dex_file_exception_helpers.h"
57#include "dex/dex_file_loader.h"
David Sehr0225f8e2018-01-31 08:52:24 +000058#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070059#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070060#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070061#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070062#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080063#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000064#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070065#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070066#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070067#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070068#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000069#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070070#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070071#include "handle_scope-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080072#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070073#include "imt_conflict_table.h"
74#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070075#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070076#include "interpreter/interpreter.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070077#include "java_vm_ext.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000078#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080079#include "jit/jit.h"
80#include "jit/jit_code_cache.h"
Calin Juravle33083d62017-01-18 15:29:12 -080081#include "jit/profile_compilation_info.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080082#include "jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070083#include "linear_alloc.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000084#include "mirror/call_site.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080085#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070086#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070087#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070089#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070090#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +010091#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070092#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080093#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070094#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +010095#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000096#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -070097#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080098#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000099#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700100#include "mirror/object_array-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800101#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700102#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800103#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700104#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100105#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700106#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700107#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700108#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700109#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700110#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700111#include "oat_file_assistant.h"
112#include "oat_file_manager.h"
113#include "object_lock.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800114#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700115#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800116#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700117#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700118#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700119#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700120#include "trace.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700121#include "utils.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100122#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800123#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700124#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700125
126namespace art {
127
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800128using android::base::StringPrintf;
129
Mathieu Chartierc7853442015-03-27 14:35:38 -0700130static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700131static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700132
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133static void ThrowNoClassDefFoundError(const char* fmt, ...)
134 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700135 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700136static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700137 va_list args;
138 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800139 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000140 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800141 va_end(args);
142}
143
Andreas Gampe99babb62015-11-02 16:20:00 -0800144static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700145 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700146 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700147 StackHandleScope<1> hs(self);
148 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700149 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700150 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700151
152 if (exception_class == nullptr) {
153 // No exc class ~ no <init>-with-string.
154 CHECK(self->IsExceptionPending());
155 self->ClearException();
156 return false;
157 }
158
Vladimir Markoba118822017-06-12 15:41:56 +0100159 ArtMethod* exception_init_method = exception_class->FindConstructor(
160 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700161 return exception_init_method != nullptr;
162}
163
Alex Lightd6251582016-10-31 11:12:30 -0700164static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700165 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700166 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
167 if (ext == nullptr) {
168 return nullptr;
169 } else {
170 return ext->GetVerifyError();
171 }
172}
173
174// Helper for ThrowEarlierClassFailure. Throws the stored error.
175static void HandleEarlierVerifyError(Thread* self,
176 ClassLinker* class_linker,
177 ObjPtr<mirror::Class> c)
178 REQUIRES_SHARED(Locks::mutator_lock_) {
179 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800180 DCHECK(obj != nullptr);
181 self->AssertNoPendingException();
182 if (obj->IsClass()) {
183 // Previous error has been stored as class. Create a new exception of that type.
184
185 // It's possible the exception doesn't have a <init>(String).
186 std::string temp;
187 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
188
189 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700190 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800191 } else {
192 self->ThrowNewException(descriptor, nullptr);
193 }
194 } else {
195 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700196 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800197 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700198 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800199 CHECK(throwable_class->IsAssignableFrom(error_class));
200 self->SetException(obj->AsThrowable());
201 }
202 self->AssertPendingException();
203}
204
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700205void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700206 // The class failed to initialize on a previous attempt, so we want to throw
207 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
208 // failed in verification, in which case v2 5.4.1 says we need to re-throw
209 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800210 Runtime* const runtime = Runtime::Current();
211 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700212 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700213 if (GetVerifyError(c) != nullptr) {
214 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800215 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700216 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800217 } else {
218 extra = verify_error->AsThrowable()->Dump();
219 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700220 }
David Sehr709b0702016-10-13 09:12:37 -0700221 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
222 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700223 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700224
David Sehr709b0702016-10-13 09:12:37 -0700225 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800226 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800227 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700228 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700229 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000230 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700231 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700232 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800233 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800234 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800235 }
Alex Lightd6251582016-10-31 11:12:30 -0700236 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
237 // might have meant to go down the earlier if statement with the original error but it got
238 // swallowed by the OOM so we end up here.
239 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800240 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
241 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
242 // exception will be a cause.
243 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700244 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700245 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700246 }
247}
248
Brian Carlstromb23eab12014-10-08 17:55:21 -0700249static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700250 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700251 if (VLOG_IS_ON(class_linker)) {
252 std::string temp;
253 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000254 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700255 }
256}
257
258static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700259 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700260 Thread* self = Thread::Current();
261 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700262
263 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700264 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700265
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800266 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
267 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
268 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800269 std::string tmp;
Alex Lightcfda88f2018-02-26 10:09:39 -0800270 LOG(kIsDebugBuild ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
271 << " failed initialization: "
272 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800273 }
274
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700275 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700276 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
277 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700278
Elliott Hughesa4f94742012-05-29 16:28:38 -0700279 // We only wrap non-Error exceptions; an Error can just be used as-is.
280 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000281 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700282 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700283 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700284}
285
Fred Shih381e4ca2014-08-25 17:24:27 -0700286// Gap between two fields in object layout.
287struct FieldGap {
288 uint32_t start_offset; // The offset from the start of the object.
289 uint32_t size; // The gap size of 1, 2, or 4 bytes.
290};
291struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800292 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700293 }
294 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
295 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800296 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700297 // Note that the priority queue returns the largest element, so operator()
298 // should return true if lhs is less than rhs.
299 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700300 }
301};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700302typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700303
304// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800305static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700306 DCHECK(gaps != nullptr);
307
308 uint32_t current_offset = gap_start;
309 while (current_offset != gap_end) {
310 size_t remaining = gap_end - current_offset;
311 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
312 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
313 current_offset += sizeof(uint32_t);
314 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
315 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
316 current_offset += sizeof(uint16_t);
317 } else {
318 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
319 current_offset += sizeof(uint8_t);
320 }
321 DCHECK_LE(current_offset, gap_end) << "Overran gap";
322 }
323}
324// Shuffle fields forward, making use of gaps whenever possible.
325template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000326static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700327 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700328 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700329 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700330 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700331 DCHECK(current_field_idx != nullptr);
332 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700333 DCHECK(gaps != nullptr);
334 DCHECK(field_offset != nullptr);
335
336 DCHECK(IsPowerOfTwo(n));
337 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700338 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700339 Primitive::Type type = field->GetTypeAsPrimitiveType();
340 if (Primitive::ComponentSize(type) < n) {
341 break;
342 }
343 if (!IsAligned<n>(field_offset->Uint32Value())) {
344 MemberOffset old_offset = *field_offset;
345 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
346 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
347 }
David Sehr709b0702016-10-13 09:12:37 -0700348 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700349 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700350 if (!gaps->empty() && gaps->top().size >= n) {
351 FieldGap gap = gaps->top();
352 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100353 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700354 field->SetOffset(MemberOffset(gap.start_offset));
355 if (gap.size > n) {
356 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
357 }
358 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100359 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700360 field->SetOffset(*field_offset);
361 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
362 }
363 ++(*current_field_idx);
364 }
365}
366
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800367ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700368 : boot_class_table_(new ClassTable()),
369 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800370 class_roots_(nullptr),
371 array_iftable_(nullptr),
372 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700373 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000374 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700375 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800376 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800377 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100378 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800379 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700380 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700381 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
382 // For CHA disabled during Aot, see b/34193647.
383
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700384 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700385 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
386 "Array cache size wrong.");
387 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700388}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700389
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800390void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700391 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800392 if (c2 == nullptr) {
393 LOG(FATAL) << "Could not find class " << descriptor;
394 UNREACHABLE();
395 }
396 if (c1.Get() != c2) {
397 std::ostringstream os1, os2;
398 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
399 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
400 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
401 << ". This is most likely the result of a broken build. Make sure that "
402 << "libcore and art projects match.\n\n"
403 << os1.str() << "\n\n" << os2.str();
404 UNREACHABLE();
405 }
406}
407
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800408bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
409 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800410 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700411
Mathieu Chartiere401d142015-04-22 13:56:20 -0700412 Thread* const self = Thread::Current();
413 Runtime* const runtime = Runtime::Current();
414 gc::Heap* const heap = runtime->GetHeap();
415
Jeff Haodcdc85b2015-12-04 14:06:18 -0800416 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700417 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700418
Mathieu Chartiere401d142015-04-22 13:56:20 -0700419 // Use the pointer size from the runtime since we are probably creating the image.
420 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
421
Elliott Hughes30646832011-10-13 16:59:46 -0700422 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700423 // 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 -0800424 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700425 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700426 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700427 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800429 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700430 mirror::Class::SetClassClass(java_lang_Class.Get());
431 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700432 if (kUseBakerReadBarrier) {
433 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800434 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700435 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700436 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800437 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700438 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700439
Elliott Hughes418d20f2011-09-22 14:00:39 -0700440 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700441 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700442 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700443 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700444 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700445
Ian Rogers23435d02012-09-24 11:23:12 -0700446 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700447 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800449 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700450 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000452 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700453
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700454 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800455 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
456 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
457 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
458 java_lang_Object.Get(),
459 java_lang_Object->GetObjectSize(),
460 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700461
Igor Murashkin86083f72017-10-27 10:59:04 -0700462 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000463 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700464 // It might seem the lock here is unnecessary, however all the SubtypeCheck
465 // functions are annotated to require locks all the way down.
466 //
467 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
468 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000469 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
470 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700471 }
472
Ian Rogers23435d02012-09-24 11:23:12 -0700473 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700474 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700475 AllocClass(self, java_lang_Class.Get(),
476 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700477 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700478
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700479 // Setup the char (primitive) class to be used for char[].
480 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 AllocClass(self, java_lang_Class.Get(),
482 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700483 // The primitive char class won't be initialized by
484 // InitializePrimitiveClass until line 459, but strings (and
485 // internal char arrays) will be allocated before that and the
486 // component size, which is computed from the primitive type, needs
487 // to be set here.
488 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700489
Ian Rogers23435d02012-09-24 11:23:12 -0700490 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700491 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700492 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700493 char_array_class->SetComponentType(char_class.Get());
494 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700495
Ian Rogers23435d02012-09-24 11:23:12 -0700496 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700497 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700498 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700499 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700500 mirror::String::SetClass(java_lang_String.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000501 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400502
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700503 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700504 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700505 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700506 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
507 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000508 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700509
Ian Rogers23435d02012-09-24 11:23:12 -0700510 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700511 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700512 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
513 kClassRootsMax));
514 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
516 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
517 SetClassRoot(kClassArrayClass, class_array_class.Get());
518 SetClassRoot(kObjectArrayClass, object_array_class.Get());
519 SetClassRoot(kCharArrayClass, char_array_class.Get());
520 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700521 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700522
Mathieu Chartier6beced42016-11-15 15:51:31 -0800523 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
524 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
525
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700526 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700527 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
528 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
529 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
530 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
531 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
532 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
533 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
534 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535
Ian Rogers23435d02012-09-24 11:23:12 -0700536 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700537 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700538
Ian Rogers23435d02012-09-24 11:23:12 -0700539 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700540 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700541 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700543 mirror::IntArray::SetArrayClass(int_array_class.Get());
544 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545
Mathieu Chartierc7853442015-03-27 14:35:38 -0700546 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
547 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700548 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700549 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
550 mirror::LongArray::SetArrayClass(long_array_class.Get());
551 SetClassRoot(kLongArrayClass, long_array_class.Get());
552
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700553 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700554
Ian Rogers52813c92012-10-11 11:50:38 -0700555 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700556 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700557 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700558 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100559 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700560 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000561 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562
Alex Lightd6251582016-10-31 11:12:30 -0700563
564 // Setup dalvik.system.ClassExt
565 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
566 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
567 SetClassRoot(kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
568 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000569 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700570
Mathieu Chartier66f19252012-09-18 08:57:04 -0700571 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700572 Handle<mirror::Class> object_array_string(hs.NewHandle(
573 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700574 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700575 object_array_string->SetComponentType(java_lang_String.Get());
576 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700577
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000578 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700579 // Create runtime resolution and imt conflict methods.
580 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000581 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
582 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700583
Ian Rogers23435d02012-09-24 11:23:12 -0700584 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
585 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
586 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800587 if (boot_class_path.empty()) {
588 *error_msg = "Boot classpath is empty.";
589 return false;
590 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800591 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800592 if (dex_file.get() == nullptr) {
593 *error_msg = "Null dex file.";
594 return false;
595 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700596 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800597 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700598 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700599
600 // now we can use FindSystemClass
601
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700602 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700603 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
604 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700605
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700606 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
607 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700608 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800609 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700610 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700611 quick_resolution_trampoline_ = GetQuickResolutionStub();
612 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
613 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700614 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700615
Alex Lightd6251582016-10-31 11:12:30 -0700616 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000617 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800618 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700619 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000620 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800621 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000622 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800623 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700624 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000625 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700626 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
627 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700628
Ian Rogers23435d02012-09-24 11:23:12 -0700629 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800630 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800631 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700632
Ian Rogers98379392014-02-24 16:53:16 -0800633 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800634 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700635
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800636 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637
Ian Rogers98379392014-02-24 16:53:16 -0800638 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800639 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700640
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800641 CheckSystemClass(self, int_array_class, "[I");
642 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700643
Ian Rogers98379392014-02-24 16:53:16 -0800644 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800645 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700646
Ian Rogers98379392014-02-24 16:53:16 -0800647 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800648 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800650 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
651 // in class_table_.
652 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700653
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800654 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
655 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656
Ian Rogers23435d02012-09-24 11:23:12 -0700657 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700658 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800659 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700660 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800661 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700662 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
663 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700664 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
665 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700667 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
668 // suspension.
669 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000670 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700671 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000672 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700673 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000674 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700675 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000676 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700677
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700678 CHECK_EQ(object_array_string.Get(),
679 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700680
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800681 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700682
Ian Rogers23435d02012-09-24 11:23:12 -0700683 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700684 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700685
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700686 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700687 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
688 CHECK(class_root != nullptr);
689 SetClassRoot(kJavaLangReflectField, class_root);
690 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700691
692 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700693 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
694 CHECK(class_root != nullptr);
695 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
696 mirror::Field::SetArrayClass(class_root);
697
698 // Create java.lang.reflect.Constructor.class root and array root.
699 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
700 CHECK(class_root != nullptr);
701 SetClassRoot(kJavaLangReflectConstructor, class_root);
702 mirror::Constructor::SetClass(class_root);
703 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
704 CHECK(class_root != nullptr);
705 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
706 mirror::Constructor::SetArrayClass(class_root);
707
708 // Create java.lang.reflect.Method.class root and array root.
709 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
710 CHECK(class_root != nullptr);
711 SetClassRoot(kJavaLangReflectMethod, class_root);
712 mirror::Method::SetClass(class_root);
713 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
714 CHECK(class_root != nullptr);
715 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
716 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700717
Orion Hodson005ac512017-10-24 15:43:43 +0100718 // Create java.lang.invoke.CallSite.class root
719 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
720 CHECK(class_root != nullptr);
721 SetClassRoot(kJavaLangInvokeCallSite, class_root);
722 mirror::CallSite::SetClass(class_root);
723
Narayan Kamathafa48272016-08-03 12:46:58 +0100724 // Create java.lang.invoke.MethodType.class root
725 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
726 CHECK(class_root != nullptr);
727 SetClassRoot(kJavaLangInvokeMethodType, class_root);
728 mirror::MethodType::SetClass(class_root);
729
730 // Create java.lang.invoke.MethodHandleImpl.class root
731 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
732 CHECK(class_root != nullptr);
733 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
734 mirror::MethodHandleImpl::SetClass(class_root);
735
Orion Hodsonc069a302017-01-18 09:23:12 +0000736 // Create java.lang.invoke.MethodHandles.Lookup.class root
737 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
738 CHECK(class_root != nullptr);
739 SetClassRoot(kJavaLangInvokeMethodHandlesLookup, class_root);
740 mirror::MethodHandlesLookup::SetClass(class_root);
741
Orion Hodson005ac512017-10-24 15:43:43 +0100742 // Create java.lang.invoke.VarHandle.class root
743 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000744 CHECK(class_root != nullptr);
Orion Hodson005ac512017-10-24 15:43:43 +0100745 SetClassRoot(kJavaLangInvokeVarHandle, class_root);
746 mirror::VarHandle::SetClass(class_root);
747
748 // Create java.lang.invoke.FieldVarHandle.class root
749 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
750 CHECK(class_root != nullptr);
751 SetClassRoot(kJavaLangInvokeFieldVarHandle, class_root);
752 mirror::FieldVarHandle::SetClass(class_root);
753
754 // Create java.lang.invoke.ArrayElementVarHandle.class root
755 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
756 CHECK(class_root != nullptr);
757 SetClassRoot(kJavaLangInvokeArrayElementVarHandle, class_root);
758 mirror::ArrayElementVarHandle::SetClass(class_root);
759
760 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
761 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
762 CHECK(class_root != nullptr);
763 SetClassRoot(kJavaLangInvokeByteArrayViewVarHandle, class_root);
764 mirror::ByteArrayViewVarHandle::SetClass(class_root);
765
766 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
767 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
768 CHECK(class_root != nullptr);
769 SetClassRoot(kJavaLangInvokeByteBufferViewVarHandle, class_root);
770 mirror::ByteBufferViewVarHandle::SetClass(class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000771
Narayan Kamath000e1882016-10-24 17:14:25 +0100772 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
773 CHECK(class_root != nullptr);
774 SetClassRoot(kDalvikSystemEmulatedStackFrame, class_root);
775 mirror::EmulatedStackFrame::SetClass(class_root);
776
Brian Carlstrom1f870082011-08-23 16:02:11 -0700777 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700778 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000779 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800780 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700781 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700782 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
783 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700784 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700785 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700786 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700787 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
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::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700790 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
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::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700793 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
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::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700796
Ian Rogers23435d02012-09-24 11:23:12 -0700797 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700798 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700799 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700800 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
801 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700802
jeffhao8cd6dda2012-02-22 10:15:34 -0800803 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700804 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800805 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800806 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700807 SetClassRoot(kJavaLangClassNotFoundException,
808 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800809 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700810 SetClassRoot(kJavaLangStackTraceElementArrayClass,
811 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800812 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700813
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700814 // Create conflict tables that depend on the class linker.
815 runtime->FixupConflictTables();
816
Ian Rogers98379392014-02-24 16:53:16 -0800817 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700818
Brian Carlstroma004aa92012-02-08 18:05:09 -0800819 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800820
821 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700822}
823
Ian Rogers98379392014-02-24 16:53:16 -0800824void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800825 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700826
827 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700828 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700829 // as the types of the field can't be resolved prior to the runtime being
830 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700831 StackHandleScope<2> hs(self);
832 Handle<mirror::Class> java_lang_ref_Reference = hs.NewHandle(GetClassRoot(kJavaLangRefReference));
833 Handle<mirror::Class> java_lang_ref_FinalizerReference =
834 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800835
Mathieu Chartierc7853442015-03-27 14:35:38 -0700836 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700837 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
838 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700839
Mathieu Chartierc7853442015-03-27 14:35:38 -0700840 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700841 CHECK_STREQ(queue->GetName(), "queue");
842 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700843
Mathieu Chartierc7853442015-03-27 14:35:38 -0700844 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700845 CHECK_STREQ(queueNext->GetName(), "queueNext");
846 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700847
Mathieu Chartierc7853442015-03-27 14:35:38 -0700848 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700849 CHECK_STREQ(referent->GetName(), "referent");
850 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700851
Mathieu Chartierc7853442015-03-27 14:35:38 -0700852 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700853 CHECK_STREQ(zombie->GetName(), "zombie");
854 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700855
Brian Carlstroma663ea52011-08-19 23:33:41 -0700856 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700857 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700858 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700859 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700860 CHECK(klass != nullptr);
861 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700862 // note SetClassRoot does additional validation.
863 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700864 }
865
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700866 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700867
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700868 // disable the slow paths in FindClass and CreatePrimitiveClass now
869 // that Object, Class, and Object[] are setup
870 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700871
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800872 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700873}
874
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700875void ClassLinker::RunRootClinits() {
876 Thread* self = Thread::Current();
877 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700878 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700879 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700880 StackHandleScope<1> hs(self);
881 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700882 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700883 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700884 }
885 }
886}
887
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200888// Set image methods' entry point to interpreter.
889class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
890 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700891 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200892 : image_pointer_size_(image_pointer_size) {}
893
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700894 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200895 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
896 CHECK(method->GetDeclaringClass() != nullptr);
897 }
898 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
899 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
900 image_pointer_size_);
901 }
902 }
903
904 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700905 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200906
907 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
908};
909
Jeff Haodcdc85b2015-12-04 14:06:18 -0800910struct TrampolineCheckData {
911 const void* quick_resolution_trampoline;
912 const void* quick_imt_conflict_trampoline;
913 const void* quick_generic_jni_trampoline;
914 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700915 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800916 ArtMethod* m;
917 bool error;
918};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800919
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800920bool ClassLinker::InitFromBootImage(std::string* error_msg) {
921 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700922 CHECK(!init_done_);
923
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700924 Runtime* const runtime = Runtime::Current();
925 Thread* const self = Thread::Current();
926 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800927 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
928 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700929 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
930 if (!ValidPointerSize(pointer_size_unchecked)) {
931 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800932 return false;
933 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700934 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800935 if (!runtime->IsAotCompiler()) {
936 // Only the Aot compiler supports having an image with a different pointer size than the
937 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
938 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700939 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800940 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700941 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800942 sizeof(void*));
943 return false;
944 }
945 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800946 std::vector<const OatFile*> oat_files =
947 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
948 DCHECK(!oat_files.empty());
949 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800950 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
951 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700952 GetStoreValueByKey(OatHeader::kImageLocationKey);
953 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800954 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
955 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
956 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
957 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
958 if (kIsDebugBuild) {
959 // Check that the other images use the same trampoline.
960 for (size_t i = 1; i < oat_files.size(); ++i) {
961 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
962 const void* ith_quick_resolution_trampoline =
963 ith_oat_header.GetQuickResolutionTrampoline();
964 const void* ith_quick_imt_conflict_trampoline =
965 ith_oat_header.GetQuickImtConflictTrampoline();
966 const void* ith_quick_generic_jni_trampoline =
967 ith_oat_header.GetQuickGenericJniTrampoline();
968 const void* ith_quick_to_interpreter_bridge_trampoline =
969 ith_oat_header.GetQuickToInterpreterBridge();
970 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
971 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
972 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
973 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
974 // Make sure that all methods in this image do not contain those trampolines as
975 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
976 TrampolineCheckData data;
977 data.error = false;
978 data.pointer_size = GetImagePointerSize();
979 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
980 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
981 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
982 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
983 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700984 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
985 if (obj->IsClass()) {
986 ObjPtr<mirror::Class> klass = obj->AsClass();
987 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
988 const void* entrypoint =
989 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
990 if (entrypoint == data.quick_resolution_trampoline ||
991 entrypoint == data.quick_imt_conflict_trampoline ||
992 entrypoint == data.quick_generic_jni_trampoline ||
993 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
994 data.m = &m;
995 data.error = true;
996 return;
997 }
998 }
999 }
1000 };
1001 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001002 if (data.error) {
1003 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001004 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001005 *error_msg = "Found an ArtMethod with a bad entrypoint";
1006 return false;
1007 }
1008 }
1009 }
1010 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001011
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001012 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1013 down_cast<mirror::ObjectArray<mirror::Class>*>(
1014 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
1015 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001016
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001017 // Special case of setting up the String class early so that we can test arbitrary objects
1018 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001019 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001020
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001021 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001022 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001023 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1024 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001025 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1026 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001027
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001028 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001029 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001030 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001031 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001032 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1033 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001034 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1035 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1036 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1037 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Orion Hodson005ac512017-10-24 15:43:43 +01001038 mirror::CallSite::SetClass(GetClassRoot(kJavaLangInvokeCallSite));
Narayan Kamathafa48272016-08-03 12:46:58 +01001039 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Orion Hodsonc069a302017-01-18 09:23:12 +00001040 mirror::MethodHandlesLookup::SetClass(GetClassRoot(kJavaLangInvokeMethodHandlesLookup));
Orion Hodson005ac512017-10-24 15:43:43 +01001041 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
1042 mirror::VarHandle::SetClass(GetClassRoot(kJavaLangInvokeVarHandle));
1043 mirror::FieldVarHandle::SetClass(GetClassRoot(kJavaLangInvokeFieldVarHandle));
1044 mirror::ArrayElementVarHandle::SetClass(GetClassRoot(kJavaLangInvokeArrayElementVarHandle));
1045 mirror::ByteArrayViewVarHandle::SetClass(GetClassRoot(kJavaLangInvokeByteArrayViewVarHandle));
1046 mirror::ByteBufferViewVarHandle::SetClass(GetClassRoot(kJavaLangInvokeByteBufferViewVarHandle));
Fred Shih4ee7a662014-07-11 09:59:27 -07001047 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001048 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1049 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1050 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1051 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1052 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1053 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1054 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1055 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1056 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1057 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Narayan Kamath000e1882016-10-24 17:14:25 +01001058 mirror::EmulatedStackFrame::SetClass(GetClassRoot(kDalvikSystemEmulatedStackFrame));
Alex Lightd6251582016-10-31 11:12:30 -07001059 mirror::ClassExt::SetClass(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001060
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001061 for (gc::space::ImageSpace* image_space : spaces) {
1062 // Boot class loader, use a null handle.
1063 std::vector<std::unique_ptr<const DexFile>> dex_files;
1064 if (!AddImageSpace(image_space,
1065 ScopedNullHandle<mirror::ClassLoader>(),
1066 /*dex_elements*/nullptr,
1067 /*dex_location*/nullptr,
1068 /*out*/&dex_files,
1069 error_msg)) {
1070 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001071 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072 // Append opened dex files at the end.
1073 boot_dex_files_.insert(boot_dex_files_.end(),
1074 std::make_move_iterator(dex_files.begin()),
1075 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001076 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001077 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1078 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1079 }
Ian Rogers98379392014-02-24 16:53:16 -08001080 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001081
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001082 VLOG(startup) << __FUNCTION__ << " exiting";
1083 return true;
1084}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001085
Jeff Hao5872d7c2016-04-27 11:07:41 -07001086bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001087 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001088 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001089 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1090 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001091}
1092
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001093static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1094 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001095 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001096 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001097 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001098 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001099 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001100 DCHECK(dex_file_field != nullptr);
1101 DCHECK(dex_file_name_field != nullptr);
1102 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001103 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001104 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001105 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001106 // Null dex file means it was probably a jar with no dex files, return a null string.
1107 *out_name = nullptr;
1108 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001109 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001110 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001111 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001112 *out_name = name_object->AsString();
1113 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001115 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116}
1117
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001118static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001119 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001121 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122 DCHECK(out_dex_file_names != nullptr);
1123 DCHECK(error_msg != nullptr);
1124 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001125 StackHandleScope<1> hs(soa.Self());
1126 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Jeff Hao5872d7c2016-04-27 11:07:41 -07001127 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001128 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1129 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001130 *error_msg = StringPrintf("Unknown class loader type %s",
1131 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001132 // Unsupported class loader.
1133 return false;
1134 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001135 // Get element names. Sets error to true on failure.
1136 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1137 REQUIRES_SHARED(Locks::mutator_lock_) {
1138 if (element == nullptr) {
1139 *error_msg = "Null dex element";
1140 *error = true; // Null element is a critical error.
1141 return false; // Had an error, stop the visit.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001142 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001143 ObjPtr<mirror::String> name;
1144 if (!GetDexPathListElementName(element, &name)) {
1145 *error_msg = "Invalid dex path list element";
1146 *error = false; // Invalid element is not a critical error.
1147 return false; // Stop the visit.
1148 }
1149 if (name != nullptr) {
1150 out_dex_file_names->push_front(name.Ptr());
1151 }
1152 return true; // Continue with the next Element.
1153 };
1154 bool error = VisitClassLoaderDexElements(soa, handle, add_element_names, /* error */ false);
1155 if (error) {
1156 // An error occurred during DexPathList Element visiting.
1157 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001158 }
1159 class_loader = class_loader->GetParent();
1160 }
1161 return true;
1162}
1163
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001164class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1165 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001166 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001167 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1168
1169 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001170 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001171 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001172 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001173 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001174 }
1175 }
1176
1177 private:
1178 gc::accounting::HeapBitmap* const live_bitmap_;
1179};
1180
Chang Xingba17dbd2017-06-28 21:27:56 +00001181class FixupInternVisitor {
1182 public:
1183 ALWAYS_INLINE ObjPtr<mirror::Object> TryInsertIntern(mirror::Object* obj) const
1184 REQUIRES_SHARED(Locks::mutator_lock_) {
1185 if (obj != nullptr && obj->IsString()) {
1186 const auto intern = Runtime::Current()->GetInternTable()->InternStrong(obj->AsString());
1187 return intern;
1188 }
1189 return obj;
1190 }
1191
1192 ALWAYS_INLINE void VisitRootIfNonNull(
1193 mirror::CompressedReference<mirror::Object>* root) const
1194 REQUIRES_SHARED(Locks::mutator_lock_) {
1195 if (!root->IsNull()) {
1196 VisitRoot(root);
1197 }
1198 }
1199
1200 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1201 REQUIRES_SHARED(Locks::mutator_lock_) {
1202 root->Assign(TryInsertIntern(root->AsMirrorPtr()));
1203 }
1204
1205 // Visit Class Fields
1206 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1207 MemberOffset offset,
1208 bool is_static ATTRIBUTE_UNUSED) const
1209 REQUIRES_SHARED(Locks::mutator_lock_) {
1210 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1211 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1212 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1213 // Updating images, don't do a read barrier.
1214 // Only string fields are fixed, don't do a verify.
1215 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1216 offset);
1217 obj->SetFieldObject<false, false>(offset, TryInsertIntern(ref));
1218 }
1219 }
1220
1221 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1222 ObjPtr<mirror::Reference> ref) const
1223 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1224 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1225 }
1226
1227 void operator()(mirror::Object* obj) const
1228 REQUIRES_SHARED(Locks::mutator_lock_) {
1229 if (obj->IsDexCache()) {
1230 obj->VisitReferences<true, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1231 } else {
1232 // Don't visit native roots for non-dex-cache
1233 obj->VisitReferences<false, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1234 }
1235 }
1236};
1237
Andreas Gampe2af99022017-04-25 08:32:59 -07001238// new_class_set is the set of classes that were read from the class table section in the image.
1239// If there was no class table section, it is null.
1240// Note: using a class here to avoid having to make ClassLinker internals public.
1241class AppImageClassLoadersAndDexCachesHelper {
1242 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001243 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001244 ClassLinker* class_linker,
1245 gc::space::ImageSpace* space,
1246 Handle<mirror::ClassLoader> class_loader,
1247 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001248 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001249 REQUIRES(!Locks::dex_lock_)
1250 REQUIRES_SHARED(Locks::mutator_lock_);
1251};
1252
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001253void AppImageClassLoadersAndDexCachesHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001254 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001255 gc::space::ImageSpace* space,
1256 Handle<mirror::ClassLoader> class_loader,
1257 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001258 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001259 REQUIRES(!Locks::dex_lock_)
1260 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001261 Thread* const self = Thread::Current();
1262 gc::Heap* const heap = Runtime::Current()->GetHeap();
1263 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001264 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001265 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001266 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001267 const size_t num_dex_caches = dex_caches->GetLength();
1268 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001269 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001270 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001271 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001272 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001273 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1274 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001275 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001276 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001277 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001278 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001279 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001280 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001281 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001282 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001283 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001284 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001285 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001286 DCHECK(it != new_class_set->end());
1287 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001288 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001289 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001290 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001291 DCHECK(it2 != new_class_set->end());
1292 DCHECK_EQ(it2->Read(), super_class);
1293 }
1294 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1295 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001296 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1297 if (!class_linker->IsQuickResolutionStub(code) &&
1298 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001299 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001300 !m.IsNative()) {
1301 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001302 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001303 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001304 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1305 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001306 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1307 if (!class_linker->IsQuickResolutionStub(code) &&
1308 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001309 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001310 !m.IsNative()) {
1311 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001312 }
1313 }
1314 }
1315 }
1316 }
1317 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001318 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001319 {
1320 // Fixup all the literal strings happens at app images which are supposed to be interned.
1321 ScopedTrace timing("Fixup String Intern in image and dex_cache");
1322 const auto& image_header = space->GetImageHeader();
1323 const auto bitmap = space->GetMarkBitmap(); // bitmap of objects
1324 const uint8_t* target_base = space->GetMemMap()->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001325 const ImageSection& objects_section = image_header.GetObjectsSection();
Chang Xingba17dbd2017-06-28 21:27:56 +00001326
1327 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1328 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1329
1330 FixupInternVisitor fixup_intern_visitor;
1331 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_intern_visitor);
1332 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001333 if (kVerifyArtMethodDeclaringClasses) {
1334 ScopedTrace timing("Verify declaring classes");
1335 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1336 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001337 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001338 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001339}
1340
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001341// Update the class loader. Should only be used on classes in the image space.
1342class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001343 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001344 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001345 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001346 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001347
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001348 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001349 // Do not update class loader for boot image classes where the app image
1350 // class loader is only the initiating loader but not the defining loader.
1351 if (klass->GetClassLoader() != nullptr) {
1352 klass->SetClassLoader(class_loader_);
1353 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001354 return true;
1355 }
1356
1357 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001358 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001359};
1360
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001361static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1362 const char* location,
1363 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001364 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001365 DCHECK(error_msg != nullptr);
1366 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001367 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001368 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001369 return std::unique_ptr<const DexFile>();
1370 }
1371 std::string inner_error_msg;
1372 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1373 if (dex_file == nullptr) {
1374 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1375 location,
1376 oat_file->GetLocation().c_str(),
1377 inner_error_msg.c_str());
1378 return std::unique_ptr<const DexFile>();
1379 }
1380
1381 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1382 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1383 location,
1384 dex_file->GetLocationChecksum(),
1385 oat_dex_file->GetDexFileLocationChecksum());
1386 return std::unique_ptr<const DexFile>();
1387 }
1388 return dex_file;
1389}
1390
1391bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1392 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1393 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001394 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001395 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001396 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001397 DCHECK(dex_caches_object != nullptr);
1398 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1399 dex_caches_object->AsObjectArray<mirror::DexCache>();
1400 const OatFile* oat_file = space->GetOatFile();
1401 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001402 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001403 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1404 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1405 dex_file_location.c_str(),
1406 error_msg);
1407 if (dex_file == nullptr) {
1408 return false;
1409 }
1410 dex_cache->SetDexFile(dex_file.get());
1411 out_dex_files->push_back(std::move(dex_file));
1412 }
1413 return true;
1414}
1415
Andreas Gampe0793bec2016-12-01 11:37:33 -08001416// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1417// together and caches some intermediate results.
1418class ImageSanityChecks FINAL {
1419 public:
1420 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1421 REQUIRES_SHARED(Locks::mutator_lock_) {
1422 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001423 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1424 DCHECK(obj != nullptr);
1425 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1426 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1427 if (obj->IsClass()) {
1428 auto klass = obj->AsClass();
1429 for (ArtField& field : klass->GetIFields()) {
1430 CHECK_EQ(field.GetDeclaringClass(), klass);
1431 }
1432 for (ArtField& field : klass->GetSFields()) {
1433 CHECK_EQ(field.GetDeclaringClass(), klass);
1434 }
1435 const auto pointer_size = isc.pointer_size_;
1436 for (auto& m : klass->GetMethods(pointer_size)) {
1437 isc.SanityCheckArtMethod(&m, klass);
1438 }
1439 auto* vtable = klass->GetVTable();
1440 if (vtable != nullptr) {
1441 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1442 }
1443 if (klass->ShouldHaveImt()) {
1444 ImTable* imt = klass->GetImt(pointer_size);
1445 for (size_t i = 0; i < ImTable::kSize; ++i) {
1446 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1447 }
1448 }
1449 if (klass->ShouldHaveEmbeddedVTable()) {
1450 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1451 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1452 }
1453 }
1454 mirror::IfTable* iftable = klass->GetIfTable();
1455 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1456 if (iftable->GetMethodArrayCount(i) > 0) {
1457 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1458 }
1459 }
1460 }
1461 };
1462 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001463 }
1464
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001465 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1466 ClassLinker* class_linker,
1467 mirror::MethodDexCacheType* arr,
1468 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001469 REQUIRES_SHARED(Locks::mutator_lock_) {
1470 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001471 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001472 }
1473
Andreas Gampe0793bec2016-12-01 11:37:33 -08001474 private:
1475 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1476 : spaces_(heap->GetBootImageSpaces()),
1477 pointer_size_(class_linker->GetImagePointerSize()) {
1478 space_begin_.reserve(spaces_.size());
1479 method_sections_.reserve(spaces_.size());
1480 runtime_method_sections_.reserve(spaces_.size());
1481 for (gc::space::ImageSpace* space : spaces_) {
1482 space_begin_.push_back(space->Begin());
1483 auto& header = space->GetImageHeader();
1484 method_sections_.push_back(&header.GetMethodsSection());
1485 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1486 }
1487 }
1488
1489 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1490 REQUIRES_SHARED(Locks::mutator_lock_) {
1491 if (m->IsRuntimeMethod()) {
1492 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1493 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1494 } else if (m->IsCopied()) {
1495 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1496 } else if (expected_class != nullptr) {
1497 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1498 }
1499 if (!spaces_.empty()) {
1500 bool contains = false;
1501 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1502 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1503 contains = method_sections_[i]->Contains(offset) ||
1504 runtime_method_sections_[i]->Contains(offset);
1505 }
1506 CHECK(contains) << m << " not found";
1507 }
1508 }
1509
1510 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1511 ObjPtr<mirror::Class> expected_class)
1512 REQUIRES_SHARED(Locks::mutator_lock_) {
1513 CHECK(arr != nullptr);
1514 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1515 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1516 // expected_class == null means we are a dex cache.
1517 if (expected_class != nullptr) {
1518 CHECK(method != nullptr);
1519 }
1520 if (method != nullptr) {
1521 SanityCheckArtMethod(method, expected_class);
1522 }
1523 }
1524 }
1525
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001526 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001527 REQUIRES_SHARED(Locks::mutator_lock_) {
1528 CHECK_EQ(arr != nullptr, size != 0u);
1529 if (arr != nullptr) {
1530 bool contains = false;
1531 for (auto space : spaces_) {
1532 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001533 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001534 contains = true;
1535 break;
1536 }
1537 }
1538 CHECK(contains);
1539 }
1540 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001541 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1542 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001543 // expected_class == null means we are a dex cache.
1544 if (method != nullptr) {
1545 SanityCheckArtMethod(method, nullptr);
1546 }
1547 }
1548 }
1549
1550 const std::vector<gc::space::ImageSpace*>& spaces_;
1551 const PointerSize pointer_size_;
1552
1553 // Cached sections from the spaces.
1554 std::vector<const uint8_t*> space_begin_;
1555 std::vector<const ImageSection*> method_sections_;
1556 std::vector<const ImageSection*> runtime_method_sections_;
1557};
1558
Andreas Gampebe7af222017-07-25 09:57:28 -07001559static void VerifyAppImage(const ImageHeader& header,
1560 const Handle<mirror::ClassLoader>& class_loader,
1561 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1562 ClassTable* class_table, gc::space::ImageSpace* space)
1563 REQUIRES_SHARED(Locks::mutator_lock_) {
1564 {
1565 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1566 public:
1567 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1568
1569 virtual void Visit(ArtMethod* method)
1570 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1571 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1572 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1573 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1574 }
1575 }
1576
1577 private:
1578 ClassTable* const table_;
1579 };
1580 VerifyClassInTableArtMethodVisitor visitor(class_table);
1581 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1582 }
1583 {
1584 // Verify that all direct interfaces of classes in the class table are also resolved.
1585 std::vector<ObjPtr<mirror::Class>> classes;
1586 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1587 REQUIRES_SHARED(Locks::mutator_lock_) {
1588 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1589 classes.push_back(klass);
1590 }
1591 return true;
1592 };
1593 class_table->Visit(verify_direct_interfaces_in_table);
1594 Thread* self = Thread::Current();
1595 for (ObjPtr<mirror::Class> klass : classes) {
1596 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1597 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1598 << klass->PrettyDescriptor() << " iface #" << i;
1599 }
1600 }
1601 }
1602 // Check that all non-primitive classes in dex caches are also in the class table.
1603 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1604 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1605 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1606 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1607 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1608 if (klass != nullptr && !klass->IsPrimitive()) {
1609 CHECK(class_table->Contains(klass))
1610 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1611 }
1612 }
1613 }
1614}
1615
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001616bool ClassLinker::AddImageSpace(
1617 gc::space::ImageSpace* space,
1618 Handle<mirror::ClassLoader> class_loader,
1619 jobjectArray dex_elements,
1620 const char* dex_location,
1621 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1622 std::string* error_msg) {
1623 DCHECK(out_dex_files != nullptr);
1624 DCHECK(error_msg != nullptr);
1625 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001626 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001627 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001628 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001629 DCHECK(dex_caches_object != nullptr);
1630 Runtime* const runtime = Runtime::Current();
1631 gc::Heap* const heap = runtime->GetHeap();
1632 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001633 // Check that the image is what we are expecting.
1634 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1635 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1636 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1637 image_pointer_size_);
1638 return false;
1639 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001640 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1641 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1642 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1643 expected_image_roots,
1644 header.GetImageRoots()->GetLength());
1645 return false;
1646 }
1647 StackHandleScope<3> hs(self);
1648 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1649 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1650 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1651 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1652 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1653 "Class loader should be the last image root.");
1654 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1655 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001656 DCHECK(class_roots != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001657 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1658 *error_msg = StringPrintf("Expected %d class roots but got %d",
1659 class_roots->GetLength(),
1660 static_cast<int32_t>(kClassRootsMax));
1661 return false;
1662 }
1663 // Check against existing class roots to make sure they match the ones in the boot image.
1664 for (size_t i = 0; i < kClassRootsMax; i++) {
1665 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1666 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1667 return false;
1668 }
1669 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001670 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001671 if (oat_file->GetOatHeader().GetDexFileCount() !=
1672 static_cast<uint32_t>(dex_caches->GetLength())) {
1673 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1674 "image";
1675 return false;
1676 }
1677
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001678 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001679 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1680 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001681 // TODO: Only store qualified paths.
1682 // If non qualified, qualify it.
1683 if (dex_file_location.find('/') == std::string::npos) {
1684 std::string dex_location_path = dex_location;
1685 const size_t pos = dex_location_path.find_last_of('/');
1686 CHECK_NE(pos, std::string::npos);
1687 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1688 dex_file_location = dex_location_path + dex_file_location;
1689 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001690 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1691 dex_file_location.c_str(),
1692 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001693 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001694 return false;
1695 }
1696
1697 if (app_image) {
1698 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1699 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001700 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001701 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001702 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001703 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001704 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001705 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001706 }
1707 }
1708 } else {
1709 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001710 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
1711 this,
1712 dex_cache->GetResolvedMethods(),
1713 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001714 }
1715 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001716 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001717 }
1718 out_dex_files->push_back(std::move(dex_file));
1719 }
1720
1721 if (app_image) {
1722 ScopedObjectAccessUnchecked soa(Thread::Current());
1723 // Check that the class loader resolves the same way as the ones in the image.
1724 // Image class loader [A][B][C][image dex files]
1725 // Class loader = [???][dex_elements][image dex files]
1726 // Need to ensure that [???][dex_elements] == [A][B][C].
1727 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1728 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1729 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1730 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001731 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1732 *error_msg = "Unexpected BootClassLoader in app image";
1733 return false;
1734 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001735 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001736 std::string temp_error_msg;
1737 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1738 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1739 temp_error_msg.c_str());
1740 return false;
1741 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001742 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001743 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1744 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1745 temp_error_msg.c_str());
1746 return false;
1747 }
1748 // Add the temporary dex path list elements at the end.
1749 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1750 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1751 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1752 if (element != nullptr) {
1753 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001754 ObjPtr<mirror::String> name;
1755 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1756 loader_dex_file_names.push_back(name);
1757 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001758 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001759 }
1760 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1761 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1762 static_cast<size_t>(dex_caches->GetLength()));
1763 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1764 // Check that the dex file names match.
1765 bool equal = image_count == loader_dex_file_names.size();
1766 if (equal) {
1767 auto it1 = image_dex_file_names.begin();
1768 auto it2 = loader_dex_file_names.begin();
1769 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1770 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001771 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001772 }
1773 if (!equal) {
1774 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1775 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1776 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001777 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001778 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1779 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1780 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001781 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001782 *error_msg = "Rejecting application image due to class loader mismatch";
1783 // Ignore class loader mismatch for now since these would just use possibly incorrect
1784 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001785 }
1786 }
1787
1788 if (kSanityCheckObjects) {
1789 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1790 auto* dex_cache = dex_caches->Get(i);
1791 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1792 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1793 if (field != nullptr) {
1794 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1795 }
1796 }
1797 }
1798 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001799 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001800 }
1801 }
1802
1803 // Set entry point to interpreter if in InterpretOnly mode.
1804 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001805 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001806 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001807 }
1808
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001809 if (!app_image) {
1810 // Make the string intern table and class table immutable for boot image.
1811 // PIC app oat files may mmap a read-only copy into their own .bss section,
1812 // so enforce that the data in the boot image tables remains unchanged.
1813 //
1814 // We cannot do that for app image even after the fixup as some interned
1815 // String references may actually end up pointing to moveable Strings.
1816 uint8_t* const_section_begin = space->Begin() + header.GetBootImageConstantTablesOffset();
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -07001817 CheckedCall(mprotect,
1818 "protect constant tables",
1819 const_section_begin,
1820 header.GetBootImageConstantTablesSize(),
1821 PROT_READ);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001822 }
1823
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001824 ClassTable* class_table = nullptr;
1825 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001826 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001827 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001828 }
1829 // If we have a class table section, read it and use it for verification in
1830 // UpdateAppImageClassLoadersAndDexCaches.
1831 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001832 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001833 const bool added_class_table = class_table_section.Size() > 0u;
1834 if (added_class_table) {
1835 const uint64_t start_time2 = NanoTime();
1836 size_t read_count = 0;
1837 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1838 /*make copy*/false,
1839 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001840 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001841 }
1842 if (app_image) {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001843 AppImageClassLoadersAndDexCachesHelper::Update(this,
1844 space,
1845 class_loader,
1846 dex_caches,
1847 &temp_set);
Mathieu Chartier69731002016-03-02 16:08:31 -08001848 // Update class loader and resolved strings. If added_class_table is false, the resolved
1849 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001850 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1851 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001852 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001853 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001854
Vladimir Marko305c38b2018-02-14 11:50:07 +00001855 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07001856 // Every class in the app image has initially SubtypeCheckInfo in the
1857 // Uninitialized state.
1858 //
1859 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
1860 // after class initialization is complete. The app image ClassStatus as-is
1861 // are almost all ClassStatus::Initialized, and being in the
1862 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
1863 //
1864 // Force every app image class's SubtypeCheck to be at least kIninitialized.
1865 //
1866 // See also ImageWriter::FixupClass.
1867 ScopedTrace trace("Recalculate app image SubtypeCheck bitstrings");
1868 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
1869 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00001870 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07001871 }
1872 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001873 }
1874 if (!oat_file->GetBssGcRoots().empty()) {
1875 // Insert oat file to class table for visiting .bss GC roots.
1876 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001877 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001878
Mathieu Chartier69731002016-03-02 16:08:31 -08001879 if (added_class_table) {
1880 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1881 class_table->AddClassSet(std::move(temp_set));
1882 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001883
Mathieu Chartier69731002016-03-02 16:08:31 -08001884 if (kIsDebugBuild && app_image) {
1885 // This verification needs to happen after the classes have been added to the class loader.
1886 // Since it ensures classes are in the class table.
Andreas Gampeacbd98b2017-10-12 10:44:11 -07001887 ScopedTrace trace("VerifyAppImage");
Andreas Gampebe7af222017-07-25 09:57:28 -07001888 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08001889 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001890
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001891 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001892 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001893}
1894
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001895bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001896 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1897 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001898}
1899
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001900void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001901 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1902 // enabling tracing requires the mutator lock, there are no race conditions here.
1903 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001904 Thread* const self = Thread::Current();
1905 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001906 if (kUseReadBarrier) {
1907 // We do not track new roots for CC.
1908 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1909 kVisitRootFlagClearRootLog |
1910 kVisitRootFlagStartLoggingNewRoots |
1911 kVisitRootFlagStopLoggingNewRoots));
1912 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001913 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001914 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1915 // There is 3 GC cases to handle:
1916 // Non moving concurrent:
1917 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001918 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001919 //
1920 // Moving non-concurrent:
1921 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1922 // To prevent missing roots, this case needs to ensure that there is no
1923 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1924 // class which is in the class table.
1925 //
1926 // Moving concurrent:
1927 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1928 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001929 //
1930 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1931 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1932 // these objects.
1933 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07001934 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001935 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001936 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001937 for (const ClassLoaderData& data : class_loaders_) {
1938 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1939 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1940 }
1941 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001942 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001943 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001944 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001945 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001946 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001947 // Concurrent moving GC marked new roots through the to-space invariant.
1948 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001949 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001950 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1951 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1952 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1953 if (old_ref != nullptr) {
1954 DCHECK(old_ref->IsClass());
1955 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1956 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1957 // Concurrent moving GC marked new roots through the to-space invariant.
1958 CHECK_EQ(new_ref, old_ref);
1959 }
1960 }
1961 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001962 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001963 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001964 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00001965 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001966 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001967 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001968 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001969 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001970 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001971 }
1972 // We deliberately ignore the class roots in the image since we
1973 // handle image roots by using the MS/CMS rescanning of dirty cards.
1974}
1975
Brian Carlstroma663ea52011-08-19 23:33:41 -07001976// Keep in sync with InitCallback. Anything we visit, we need to
1977// reinit references to when reinitializing a ClassLinker from a
1978// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001979void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001980 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001981 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001982 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001983 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1984 // unloading if we are marking roots.
1985 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001986}
1987
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001988class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1989 public:
1990 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1991 : visitor_(visitor),
1992 done_(false) {}
1993
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001994 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001995 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001996 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001997 if (!done_ && class_table != nullptr) {
1998 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
1999 if (!class_table->Visit(visitor)) {
2000 // If the visitor ClassTable returns false it means that we don't need to continue.
2001 done_ = true;
2002 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002003 }
2004 }
2005
2006 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002007 // Class visitor that limits the class visits from a ClassTable to the classes with
2008 // the provided defining class loader. This filter is used to avoid multiple visits
2009 // of the same class which can be recorded for multiple initiating class loaders.
2010 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2011 public:
2012 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2013 ClassVisitor* visitor)
2014 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2015
2016 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2017 if (klass->GetClassLoader() != defining_class_loader_) {
2018 return true;
2019 }
2020 return (*visitor_)(klass);
2021 }
2022
2023 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2024 ClassVisitor* const visitor_;
2025 };
2026
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002027 ClassVisitor* const visitor_;
2028 // If done is true then we don't need to do any more visiting.
2029 bool done_;
2030};
2031
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002032void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002033 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002034 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2035 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002036 }
2037}
2038
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002039void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002040 Thread* const self = Thread::Current();
2041 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2042 // Not safe to have thread suspension when we are holding a lock.
2043 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002044 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002045 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002046 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002047 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002048 }
2049}
2050
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002051class GetClassesInToVector : public ClassVisitor {
2052 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002053 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002054 classes_.push_back(klass);
2055 return true;
2056 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002057 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002058};
2059
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002060class GetClassInToObjectArray : public ClassVisitor {
2061 public:
2062 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2063 : arr_(arr), index_(0) {}
2064
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002065 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002066 ++index_;
2067 if (index_ <= arr_->GetLength()) {
2068 arr_->Set(index_ - 1, klass);
2069 return true;
2070 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002071 return false;
2072 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002073
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002074 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002075 return index_ <= arr_->GetLength();
2076 }
2077
2078 private:
2079 mirror::ObjectArray<mirror::Class>* const arr_;
2080 int32_t index_;
2081};
2082
2083void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002084 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2085 // is avoiding duplicates.
2086 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002087 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002088 GetClassesInToVector accumulator;
2089 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002090 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002091 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002092 return;
2093 }
2094 }
2095 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002096 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002097 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002098 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002099 // We size the array assuming classes won't be added to the class table during the visit.
2100 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002101 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002102 size_t class_table_size;
2103 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002104 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002105 // Add 100 in case new classes get loaded when we are filling in the object array.
2106 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002107 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002108 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002109 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002110 classes.Assign(
2111 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002112 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002113 GetClassInToObjectArray accumulator(classes.Get());
2114 VisitClasses(&accumulator);
2115 if (accumulator.Succeeded()) {
2116 break;
2117 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002118 }
2119 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2120 // If the class table shrank during creation of the clases array we expect null elements. If
2121 // the class table grew then the loop repeats. If classes are created after the loop has
2122 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002123 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002124 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002125 return;
2126 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002127 }
2128 }
2129}
2130
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002131ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002132 mirror::Class::ResetClass();
2133 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002134 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002135 mirror::Method::ResetClass();
2136 mirror::Reference::ResetClass();
2137 mirror::StackTraceElement::ResetClass();
2138 mirror::String::ResetClass();
2139 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002140 mirror::BooleanArray::ResetArrayClass();
2141 mirror::ByteArray::ResetArrayClass();
2142 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002143 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002144 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002145 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002146 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002147 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002148 mirror::IntArray::ResetArrayClass();
2149 mirror::LongArray::ResetArrayClass();
2150 mirror::ShortArray::ResetArrayClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002151 mirror::CallSite::ResetClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002152 mirror::MethodType::ResetClass();
2153 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002154 mirror::MethodHandlesLookup::ResetClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002155 mirror::VarHandle::ResetClass();
2156 mirror::FieldVarHandle::ResetClass();
2157 mirror::ArrayElementVarHandle::ResetClass();
2158 mirror::ByteArrayViewVarHandle::ResetClass();
2159 mirror::ByteBufferViewVarHandle::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002160 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002161 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002162 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002163 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002164 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002165 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002166}
2167
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002168void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2169 Runtime* const runtime = Runtime::Current();
2170 JavaVMExt* const vm = runtime->GetJavaVM();
2171 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002172 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002173 if (runtime->GetJit() != nullptr) {
2174 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2175 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002176 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002177 code_cache->RemoveMethodsIn(self, *data.allocator);
2178 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002179 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002180 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002181 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002182 }
2183 delete data.allocator;
2184 delete data.class_table;
2185}
2186
Mathieu Chartiere401d142015-04-22 13:56:20 -07002187mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002188 return down_cast<mirror::PointerArray*>(
2189 image_pointer_size_ == PointerSize::k64
2190 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2191 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002192}
2193
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002194mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002195 Thread* self,
2196 const DexFile& dex_file) {
2197 StackHandleScope<1> hs(self);
2198 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002199 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002200 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002201 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002202 self->AssertPendingOOMException();
2203 return nullptr;
2204 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002205 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002206 if (location == nullptr) {
2207 self->AssertPendingOOMException();
2208 return nullptr;
2209 }
2210 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002211 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002212}
2213
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002214mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2215 const DexFile& dex_file,
2216 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002217 ObjPtr<mirror::String> location = nullptr;
2218 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002219 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002220 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002221 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002222 mirror::DexCache::InitializeDexCache(self,
2223 dex_cache,
2224 location,
2225 &dex_file,
2226 linear_alloc,
2227 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002228 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002229 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002230}
2231
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002232mirror::Class* ClassLinker::AllocClass(Thread* self,
2233 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002234 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002235 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002236 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002237 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002238 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002239 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2240 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002241 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002242 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002243 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002244 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002245 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002246}
2247
Ian Rogers6fac4472014-02-25 17:01:10 -08002248mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002249 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002250}
2251
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002252mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002253 Thread* self,
2254 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002255 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2256 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002257}
2258
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002259mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2260 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002261 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002262 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002263 if (kIsDebugBuild) {
2264 StackHandleScope<1> hs(self);
2265 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2266 Thread::PoisonObjectPointersIfDebug();
2267 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002268
2269 // For temporary classes we must wait for them to be retired.
2270 if (init_done_ && klass->IsTemp()) {
2271 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002272 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002273 ThrowEarlierClassFailure(klass);
2274 return nullptr;
2275 }
2276 StackHandleScope<1> hs(self);
2277 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2278 ObjectLock<mirror::Class> lock(self, h_class);
2279 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002280 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002281 lock.WaitIgnoringInterrupts();
2282 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002283 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002284 ThrowEarlierClassFailure(h_class.Get());
2285 return nullptr;
2286 }
2287 CHECK(h_class->IsRetired());
2288 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002289 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002290 }
2291
Brian Carlstromaded5f72011-10-07 17:15:04 -07002292 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002293 size_t index = 0;
2294 // Maximum number of yield iterations until we start sleeping.
2295 static const size_t kNumYieldIterations = 1000;
2296 // How long each sleep is in us.
2297 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002298 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002299 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002300 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002301 {
2302 ObjectTryLock<mirror::Class> lock(self, h_class);
2303 // Can not use a monitor wait here since it may block when returning and deadlock if another
2304 // thread has locked klass.
2305 if (lock.Acquired()) {
2306 // Check for circular dependencies between classes, the lock is required for SetStatus.
2307 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2308 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002309 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002310 return nullptr;
2311 }
2312 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002314 {
2315 // Handle wrapper deals with klass moving.
2316 ScopedThreadSuspension sts(self, kSuspended);
2317 if (index < kNumYieldIterations) {
2318 sched_yield();
2319 } else {
2320 usleep(kSleepDurationUS);
2321 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002322 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002323 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002324 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325
Vladimir Marko72ab6842017-01-20 19:32:50 +00002326 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002327 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002328 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002329 }
2330 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002331 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002332 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002333 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334}
2335
Ian Rogers68b56852014-08-29 20:19:11 -07002336typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2337
2338// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002339ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002340 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002341 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002342 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002343 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002344 return ClassPathEntry(dex_file, dex_class_def);
2345 }
2346 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002347 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002348}
2349
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002350bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2351 Thread* self,
2352 const char* descriptor,
2353 size_t hash,
2354 Handle<mirror::ClassLoader> class_loader,
2355 ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002356 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002357 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002358 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002359 return true;
2360 }
2361
Calin Juravlecdd49122017-07-05 20:09:53 -07002362 if (IsPathOrDexClassLoader(soa, class_loader)) {
2363 // For regular path or dex class loader the search order is:
2364 // - parent
2365 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002366
Calin Juravlecdd49122017-07-05 20:09:53 -07002367 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2368 StackHandleScope<1> hs(self);
2369 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2370 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2371 return false; // One of the parents is not supported.
2372 }
2373 if (*result != nullptr) {
2374 return true; // Found the class up the chain.
2375 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002376
Calin Juravlecdd49122017-07-05 20:09:53 -07002377 // Search the current class loader classpath.
2378 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002379 return true;
2380 }
2381
Calin Juravlecdd49122017-07-05 20:09:53 -07002382 if (IsDelegateLastClassLoader(soa, class_loader)) {
2383 // For delegate last, the search order is:
2384 // - boot class path
2385 // - class loader dex files
2386 // - parent
2387 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2388 if (*result != nullptr) {
2389 return true; // The class is part of the boot class path.
2390 }
2391
2392 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2393 if (*result != nullptr) {
2394 return true; // Found the class in the current class loader
2395 }
2396
2397 // 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 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2401 }
2402
2403 // Unsupported class loader.
2404 *result = nullptr;
2405 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002406}
2407
2408// Finds the class in the boot class loader.
2409// If the class is found the method returns the resolved class. Otherwise it returns null.
2410ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2411 const char* descriptor,
2412 size_t hash) {
2413 ObjPtr<mirror::Class> result = nullptr;
2414 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2415 if (pair.second != nullptr) {
2416 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2417 if (klass != nullptr) {
2418 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002419 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002420 result = DefineClass(self,
2421 descriptor,
2422 hash,
2423 ScopedNullHandle<mirror::ClassLoader>(),
2424 *pair.first,
2425 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002426 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002427 if (result == nullptr) {
2428 CHECK(self->IsExceptionPending()) << descriptor;
2429 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002430 }
2431 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002432 return result;
2433}
Andreas Gampef865ea92015-04-13 22:14:19 -07002434
Calin Juravle415dc3d2017-06-28 11:03:12 -07002435ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2436 ScopedObjectAccessAlreadyRunnable& soa,
2437 const char* descriptor,
2438 size_t hash,
2439 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002440 DCHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002441 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002442
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002443 ObjPtr<mirror::Class> ret;
2444 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2445 const DexFile::ClassDef* dex_class_def =
2446 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2447 if (dex_class_def != nullptr) {
2448 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2449 descriptor,
2450 hash,
2451 class_loader,
2452 *cp_dex_file,
2453 *dex_class_def);
2454 if (klass == nullptr) {
2455 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2456 soa.Self()->ClearException();
2457 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002458 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002459 ret = klass;
2460 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002461 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002462 return true; // Continue with the next DexFile.
2463 };
2464
2465 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2466 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002467}
2468
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002469mirror::Class* ClassLinker::FindClass(Thread* self,
2470 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002471 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002472 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002473 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002474 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002475 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002476 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002477 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2478 // for primitive classes that aren't backed by dex files.
2479 return FindPrimitiveClass(descriptor[0]);
2480 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002481 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002482 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002483 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002484 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002485 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002486 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002487 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002488 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002489 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002490 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002491 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002492 return DefineClass(self,
2493 descriptor,
2494 hash,
2495 ScopedNullHandle<mirror::ClassLoader>(),
2496 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002497 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002498 } else {
2499 // The boot class loader is searched ahead of the application class loader, failures are
2500 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2501 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002502 ObjPtr<mirror::Throwable> pre_allocated =
2503 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002504 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002505 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002506 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002507 }
2508 ObjPtr<mirror::Class> result_ptr;
2509 bool descriptor_equals;
2510 if (descriptor[0] == '[') {
2511 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2512 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2513 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2514 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002515 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002516 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002517 bool known_hierarchy =
2518 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2519 if (result_ptr != nullptr) {
2520 // The chain was understood and we found the class. We still need to add the class to
2521 // the class table to protect from racy programs that can try and redefine the path list
2522 // which would change the Class<?> returned for subsequent evaluation of const-class.
2523 DCHECK(known_hierarchy);
2524 DCHECK(result_ptr->DescriptorEquals(descriptor));
2525 descriptor_equals = true;
2526 } else {
2527 // Either the chain wasn't understood or the class wasn't found.
2528 //
2529 // If the chain was understood but we did not find the class, let the Java-side
2530 // rediscover all this and throw the exception with the right stack trace. Note that
2531 // the Java-side could still succeed for racy programs if another thread is actively
2532 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002533
Calin Juravleccd56952016-12-15 17:57:38 +00002534 if (!self->CanCallIntoJava()) {
2535 // Oops, we can't call into java so we can't run actual class-loader code.
2536 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002537 ObjPtr<mirror::Throwable> pre_allocated =
2538 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2539 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002540 return nullptr;
2541 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002542
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002543 // Inlined DescriptorToDot(descriptor) with extra validation.
2544 //
2545 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2546 // the DescriptorEquals() check below and give a confusing error message. For example,
2547 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2548 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2549 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2550 size_t descriptor_length = strlen(descriptor);
2551 if (UNLIKELY(descriptor[0] != 'L') ||
2552 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2553 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2554 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2555 return nullptr;
2556 }
2557 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2558 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2559
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002560 ScopedLocalRef<jobject> class_loader_object(
2561 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002562 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2563 {
2564 ScopedThreadStateChange tsc(self, kNative);
2565 ScopedLocalRef<jobject> class_name_object(
2566 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2567 if (class_name_object.get() == nullptr) {
2568 DCHECK(self->IsExceptionPending()); // OOME.
2569 return nullptr;
2570 }
2571 CHECK(class_loader_object.get() != nullptr);
2572 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2573 WellKnownClasses::java_lang_ClassLoader_loadClass,
2574 class_name_object.get()));
2575 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002576 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002577 // broken loader - throw NPE to be compatible with Dalvik
2578 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2579 class_name_string.c_str()).c_str());
2580 return nullptr;
2581 }
2582 result_ptr = soa.Decode<mirror::Class>(result.get());
2583 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002584 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002585 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002586 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002587
2588 if (self->IsExceptionPending()) {
2589 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2590 // However, to comply with the RI behavior, first check if another thread succeeded.
2591 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2592 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2593 self->ClearException();
2594 return EnsureResolved(self, descriptor, result_ptr);
2595 }
2596 return nullptr;
2597 }
2598
2599 // Try to insert the class to the class table, checking for mismatch.
2600 ObjPtr<mirror::Class> old;
2601 {
2602 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2603 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2604 old = class_table->Lookup(descriptor, hash);
2605 if (old == nullptr) {
2606 old = result_ptr; // For the comparison below, after releasing the lock.
2607 if (descriptor_equals) {
2608 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2609 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2610 } // else throw below, after releasing the lock.
2611 }
2612 }
2613 if (UNLIKELY(old != result_ptr)) {
2614 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2615 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2616 mirror::Class* loader_class = class_loader->GetClass();
2617 const char* loader_class_name =
2618 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2619 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2620 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2621 << DescriptorToDot(descriptor) << "\").";
2622 return EnsureResolved(self, descriptor, old);
2623 }
2624 if (UNLIKELY(!descriptor_equals)) {
2625 std::string result_storage;
2626 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2627 std::string loader_storage;
2628 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2629 ThrowNoClassDefFoundError(
2630 "Initiating class loader of type %s returned class %s instead of %s.",
2631 DescriptorToDot(loader_class_name).c_str(),
2632 DescriptorToDot(result_name).c_str(),
2633 DescriptorToDot(descriptor).c_str());
2634 return nullptr;
2635 }
2636 // success, return mirror::Class*
2637 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002638}
2639
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002640mirror::Class* ClassLinker::DefineClass(Thread* self,
2641 const char* descriptor,
2642 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002643 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002644 const DexFile& dex_file,
2645 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002646 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002647 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002648
Brian Carlstromaded5f72011-10-07 17:15:04 -07002649 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002650 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002651 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002652 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002653 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002654 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002655 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002656 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002657 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002658 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2659 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002660 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002661 klass.Assign(GetClassRoot(kJavaLangDexCache));
Alex Lightd6251582016-10-31 11:12:30 -07002662 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
2663 klass.Assign(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002664 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002665 }
2666
Andreas Gampefa4333d2017-02-14 11:10:34 -08002667 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002668 // Allocate a class with the status of not ready.
2669 // Interface object should get the right size here. Regular class will
2670 // figure out the right size later and be replaced with one of the right
2671 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002672 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002673 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002674 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002675 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002676 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002677 }
Alex Lightb0f11922017-01-23 14:25:17 -08002678 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2679 // nothing.
2680 DexFile const* new_dex_file = nullptr;
2681 DexFile::ClassDef const* new_class_def = nullptr;
2682 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2683 // will only be called once.
2684 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2685 klass,
2686 class_loader,
2687 dex_file,
2688 dex_class_def,
2689 &new_dex_file,
2690 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002691 // Check to see if an exception happened during runtime callbacks. Return if so.
2692 if (self->IsExceptionPending()) {
2693 return nullptr;
2694 }
Alex Lightb0f11922017-01-23 14:25:17 -08002695 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002696 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002697 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002698 return nullptr;
2699 }
2700 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002701 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002702
Jeff Hao848f70a2014-01-15 13:49:50 -08002703 // Mark the string class by setting its access flag.
2704 if (UNLIKELY(!init_done_)) {
2705 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2706 klass->SetStringClass();
2707 }
2708 }
2709
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002710 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002711 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002712 // Make sure we have a valid empty iftable even if there are errors.
2713 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002714
Mathieu Chartier590fee92013-09-13 13:46:47 -07002715 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002716 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002717 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002718 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2719 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002720 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002721 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002722
Mathieu Chartierc7853442015-03-27 14:35:38 -07002723 // Load the fields and other things after we are inserted in the table. This is so that we don't
2724 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2725 // other reason is that the field roots are only visited from the class table. So we need to be
2726 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002727 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002728 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002729 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002730 // An exception occured during load, set status to erroneous while holding klass' lock in case
2731 // notification is necessary.
2732 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002733 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002734 }
2735 return nullptr;
2736 }
2737
Brian Carlstromaded5f72011-10-07 17:15:04 -07002738 // Finish loading (if necessary) by finding parents
2739 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002740 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002741 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002742 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002743 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002744 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002745 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002746 }
2747 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002748
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002749 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002750 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002751 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002752
Brian Carlstromaded5f72011-10-07 17:15:04 -07002753 // Link the class (if necessary)
2754 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002755 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002756 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002757
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002758 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002759 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002760 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002761 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002762 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002763 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002764 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002765 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002766 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002767 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002768 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002769
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002770 // Instrumentation may have updated entrypoints for all methods of all
2771 // classes. However it could not update methods of this class while we
2772 // were loading it. Now the class is resolved, we can update entrypoints
2773 // as required by instrumentation.
2774 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2775 // We must be in the kRunnable state to prevent instrumentation from
2776 // suspending all threads to update entrypoints while we are doing it
2777 // for this class.
2778 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002779 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002780 }
2781
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002782 /*
2783 * We send CLASS_PREPARE events to the debugger from here. The
2784 * definition of "preparation" is creating the static fields for a
2785 * class and initializing them to the standard default values, but not
2786 * executing any code (that comes later, during "initialization").
2787 *
2788 * We did the static preparation in LinkClass.
2789 *
2790 * The class has been prepared and resolved but possibly not yet verified
2791 * at this point.
2792 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002793 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002794
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002795 // Notify native debugger of the new class and its layout.
2796 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2797
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002798 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002799}
2800
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002801uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2802 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002803 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002804 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002805 size_t num_8 = 0;
2806 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002807 size_t num_32 = 0;
2808 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002809 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002810 // We allow duplicate definitions of the same field in a class_data_item
2811 // but ignore the repeated indexes here, b/21868015.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002812 uint32_t last_field_idx = dex::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002813 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002814 uint32_t field_idx = it.GetMemberIndex();
2815 // Ordering enforced by DexFileVerifier.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002816 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
Vladimir Marko879d27b2016-03-15 20:31:50 +00002817 if (UNLIKELY(field_idx == last_field_idx)) {
2818 continue;
2819 }
2820 last_field_idx = field_idx;
2821 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002822 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002823 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002824 switch (c) {
2825 case 'L':
2826 case '[':
2827 num_ref++;
2828 break;
2829 case 'J':
2830 case 'D':
2831 num_64++;
2832 break;
2833 case 'I':
2834 case 'F':
2835 num_32++;
2836 break;
2837 case 'S':
2838 case 'C':
2839 num_16++;
2840 break;
2841 case 'B':
2842 case 'Z':
2843 num_8++;
2844 break;
2845 default:
2846 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002847 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002848 }
2849 }
2850 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002851 return mirror::Class::ComputeClassSize(false,
2852 0,
2853 num_8,
2854 num_16,
2855 num_32,
2856 num_64,
2857 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002858 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002859}
2860
Alex Lightfc49fec2018-01-16 22:28:36 +00002861// Special case to get oat code without overwriting a trampoline.
2862const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002863 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002864 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002865 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002866 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002867 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2868 if (code != nullptr) {
2869 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002870 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002871 if (method->IsNative()) {
2872 // No code and native? Use generic trampoline.
2873 return GetQuickGenericJniStub();
2874 }
2875 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002876}
2877
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002878bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2879 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2880 return false;
2881 }
2882
Elliott Hughes956af0f2014-12-11 14:34:28 -08002883 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002884 return true;
2885 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002886
2887 Runtime* runtime = Runtime::Current();
2888 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2889 if (instr->InterpretOnly()) {
2890 return true;
2891 }
2892
2893 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2894 // Doing this check avoids doing compiled/interpreter transitions.
2895 return true;
2896 }
2897
2898 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2899 // Force the use of interpreter when it is required by the debugger.
2900 return true;
2901 }
2902
Alex Light8f34aba2017-10-09 13:46:32 -07002903 if (Thread::Current()->IsAsyncExceptionPending()) {
2904 // Force use of interpreter to handle async-exceptions
2905 return true;
2906 }
2907
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002908 if (runtime->IsJavaDebuggable()) {
2909 // For simplicity, we ignore precompiled code and go to the interpreter
2910 // assuming we don't already have jitted code.
2911 // We could look at the oat file where `quick_code` is being defined,
2912 // and check whether it's been compiled debuggable, but we decided to
2913 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002914 jit::Jit* jit = Runtime::Current()->GetJit();
2915 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2916 }
2917
David Srbeckyf4480162016-03-16 00:06:24 +00002918 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002919 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002920 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002921 // since we want to JIT it (at first use) with extra stackmaps for native
2922 // debugging. We keep however all AOT code from the boot image,
2923 // since the JIT-at-first-use is blocking and would result in non-negligible
2924 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002925 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002926 }
2927
2928 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002929}
2930
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002931void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002932 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002933 if (klass->NumDirectMethods() == 0) {
2934 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002935 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002936 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002937 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002938 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002939 return; // OAT file unavailable.
2940 }
Ian Rogers19846512012-02-24 11:42:47 -08002941 }
Alex Light64ad14d2014-08-19 14:23:13 -07002942
Mathieu Chartierf8322842014-05-16 10:59:25 -07002943 const DexFile& dex_file = klass->GetDexFile();
2944 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002945 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002946 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002947 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002948 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002949 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002950 it.SkipAllFields();
Ian Rogers97b52f82014-08-14 11:34:07 -07002951 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002952 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2953 klass->GetDexClassDefIndex(),
2954 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002955 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002956 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002957 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002958 if (!method->IsStatic()) {
2959 // Only update static methods.
2960 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002961 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002962 const void* quick_code = nullptr;
2963 if (has_oat_class) {
2964 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002965 quick_code = oat_method.GetQuickCode();
2966 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002967 // Check whether the method is native, in which case it's generic JNI.
2968 if (quick_code == nullptr && method->IsNative()) {
2969 quick_code = GetQuickGenericJniStub();
2970 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002971 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002972 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002973 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002974 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002975 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002976 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002977}
2978
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002979// Does anything needed to make sure that the compiler will not generate a direct invoke to this
2980// method. Should only be called on non-invokable methods.
2981inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002982 DCHECK(method != nullptr);
2983 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002984 method->SetEntryPointFromQuickCompiledCodePtrSize(
2985 class_linker->GetQuickToInterpreterBridgeTrampoline(),
2986 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07002987}
2988
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002989static void LinkCode(ClassLinker* class_linker,
2990 ArtMethod* method,
2991 const OatFile::OatClass* oat_class,
2992 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002993 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002994 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002995 // The following code only applies to a non-compiler runtime.
2996 return;
2997 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002998 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002999 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003000 if (oat_class != nullptr) {
3001 // Every kind of method should at least get an invoke stub from the oat_method.
3002 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003003 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003004 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003005 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003006
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003007 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003008 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003009 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003010
Alex Light9139e002015-10-09 15:59:48 -07003011 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003012 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003013 return;
3014 }
Ian Rogers19846512012-02-24 11:42:47 -08003015
3016 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003017 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003018 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3019 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003020 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003021 } else if (quick_code == nullptr && method->IsNative()) {
3022 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003023 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003024 // Set entry point from compiled code if there's no code or in interpreter only mode.
3025 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003026 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003027
Ian Rogers62d6c772013-02-27 08:32:07 -08003028 if (method->IsNative()) {
3029 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003030 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003031
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003032 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003033 // We have a native method here without code. Then it should have either the generic JNI
3034 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3035 // TODO: this doesn't handle all the cases where trampolines may be installed.
3036 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003037 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3038 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003039 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003040 }
3041}
3042
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003043void ClassLinker::SetupClass(const DexFile& dex_file,
3044 const DexFile::ClassDef& dex_class_def,
3045 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003046 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003047 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003048 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003049 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003050 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003051 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003052
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003053 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07003054 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003055 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003056 klass->SetAccessFlags(access_flags);
3057 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003058 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003059 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003060
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003061 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003062 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003063}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003064
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003065void ClassLinker::LoadClass(Thread* self,
3066 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003067 const DexFile::ClassDef& dex_class_def,
3068 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003069 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003070 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003071 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003072 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003073 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003074}
3075
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003076LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3077 LinearAlloc* allocator,
3078 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003079 if (length == 0) {
3080 return nullptr;
3081 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003082 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3083 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3084 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003085 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003086 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003087 CHECK(ret != nullptr);
3088 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3089 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003090}
3091
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003092LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3093 LinearAlloc* allocator,
3094 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003095 if (length == 0) {
3096 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003097 }
Vladimir Marko14632852015-08-17 12:07:23 +01003098 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3099 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003100 const size_t storage_size =
3101 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003102 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003103 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003104 CHECK(ret != nullptr);
3105 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003106 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003107 }
3108 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003109}
3110
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003111LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003112 if (class_loader == nullptr) {
3113 return Runtime::Current()->GetLinearAlloc();
3114 }
3115 LinearAlloc* allocator = class_loader->GetAllocator();
3116 DCHECK(allocator != nullptr);
3117 return allocator;
3118}
3119
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003120LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003121 if (class_loader == nullptr) {
3122 return Runtime::Current()->GetLinearAlloc();
3123 }
3124 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3125 LinearAlloc* allocator = class_loader->GetAllocator();
3126 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003127 RegisterClassLoader(class_loader);
3128 allocator = class_loader->GetAllocator();
3129 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003130 }
3131 return allocator;
3132}
3133
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003134void ClassLinker::LoadClassMembers(Thread* self,
3135 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003136 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003137 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003138 {
3139 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3140 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003141 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003142 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003143 // We allow duplicate definitions of the same field in a class_data_item
3144 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003145 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003146 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003147 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3148 allocator,
3149 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003150 size_t num_sfields = 0;
3151 uint32_t last_field_idx = 0u;
3152 for (; it.HasNextStaticField(); it.Next()) {
3153 uint32_t field_idx = it.GetMemberIndex();
3154 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3155 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3156 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003157 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003158 ++num_sfields;
3159 last_field_idx = field_idx;
3160 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003161 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003162
Mathieu Chartiere401d142015-04-22 13:56:20 -07003163 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003164 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3165 allocator,
3166 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003167 size_t num_ifields = 0u;
3168 last_field_idx = 0u;
3169 for (; it.HasNextInstanceField(); it.Next()) {
3170 uint32_t field_idx = it.GetMemberIndex();
3171 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3172 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3173 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003174 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003175 ++num_ifields;
3176 last_field_idx = field_idx;
3177 }
3178 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003179
Vladimir Marko23682bf2015-06-24 14:28:03 +01003180 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3181 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003182 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003183 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3184 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003185 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3186 if (sfields != nullptr) {
3187 sfields->SetSize(num_sfields);
3188 }
3189 if (ifields != nullptr) {
3190 ifields->SetSize(num_ifields);
3191 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003192 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003193 // Set the field arrays.
3194 klass->SetSFieldsPtr(sfields);
3195 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003196 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003197 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3198 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003199 bool has_oat_class = false;
3200 const OatFile::OatClass oat_class =
3201 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3202 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3203 : OatFile::OatClass::Invalid();
3204 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003205 klass->SetMethodsPtr(
3206 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3207 it.NumDirectMethods(),
3208 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003209 size_t class_def_method_index = 0;
Andreas Gampee2abbc62017-09-15 11:59:26 -07003210 uint32_t last_dex_method_index = dex::kDexNoIndex;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003211 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003212 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003213 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3214 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003215 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003216 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003217 uint32_t it_method_index = it.GetMemberIndex();
3218 if (last_dex_method_index == it_method_index) {
3219 // duplicate case
3220 method->SetMethodIndex(last_class_def_method_index);
3221 } else {
3222 method->SetMethodIndex(class_def_method_index);
3223 last_dex_method_index = it_method_index;
3224 last_class_def_method_index = class_def_method_index;
3225 }
3226 class_def_method_index++;
3227 }
3228 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3229 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003230 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003231 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003232 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003233 class_def_method_index++;
3234 }
3235 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003236 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003237 // Ensure that the card is marked so that remembered sets pick up native roots.
3238 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003239 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003240}
3241
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003242void ClassLinker::LoadField(const ClassDataItemIterator& it,
3243 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003244 ArtField* dst) {
3245 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003246 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003247 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003248
3249 // Get access flags from the DexFile. If this is a boot class path class,
3250 // also set its runtime hidden API access flags.
3251 uint32_t access_flags = it.GetFieldAccessFlags();
3252 if (klass->IsBootStrapClassLoaded()) {
3253 access_flags =
3254 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3255 }
3256 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003257}
3258
Mathieu Chartier268764d2016-09-13 12:09:38 -07003259void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003260 const ClassDataItemIterator& it,
3261 Handle<mirror::Class> klass,
3262 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003263 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003264 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003265 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003266
Mathieu Chartier268764d2016-09-13 12:09:38 -07003267 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003268 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003269 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003270 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003271
David Brazdilf6a8a552018-01-15 18:10:50 +00003272 // Get access flags from the DexFile. If this is a boot class path class,
3273 // also set its runtime hidden API access flags.
Andreas Gampe51829322014-08-25 15:05:04 -07003274 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003275
David Brazdilf6a8a552018-01-15 18:10:50 +00003276 if (klass->IsBootStrapClassLoaded()) {
3277 access_flags =
3278 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3279 }
3280
Ian Rogersdfb325e2013-10-30 01:00:44 -07003281 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003282 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003283 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3284 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003285 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003286 klass->SetFinalizable();
3287 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003288 std::string temp;
3289 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003290 // The Enum class declares a "final" finalize() method to prevent subclasses from
3291 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3292 // subclasses, so we exclude it here.
3293 // We also want to avoid setting the flag on Object, where we know that finalize() is
3294 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003295 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3296 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003297 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003298 }
3299 }
3300 }
3301 } else if (method_name[0] == '<') {
3302 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003303 bool is_init = (strcmp("<init>", method_name) == 0);
3304 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003305 if (UNLIKELY(!is_init && !is_clinit)) {
3306 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3307 } else {
3308 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3309 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003310 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003311 access_flags |= kAccConstructor;
3312 }
3313 }
3314 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003315 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3316 // Check if the native method is annotated with @FastNative or @CriticalNative.
3317 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3318 dex_file, dst->GetClassDef(), dex_method_idx);
3319 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003320 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003321}
3322
Ian Rogers7b078e82014-09-10 14:44:24 -07003323void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003324 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003325 self,
3326 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003327 Runtime::Current()->GetLinearAlloc());
3328 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003329 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003330}
3331
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003332void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003333 ObjPtr<mirror::DexCache> dex_cache) {
3334 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003335 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003336 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
3337 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003338}
3339
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003340void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003341 ObjPtr<mirror::DexCache> dex_cache,
3342 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003343 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003344 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003345 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003346 // For app images, the dex cache location may be a suffix of the dex file location since the
3347 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003348 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3349 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003350 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3351 std::string dex_file_location = dex_file.GetLocation();
3352 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003353 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003354 // Take suffix.
3355 const std::string dex_file_suffix = dex_file_location.substr(
3356 dex_file_location.length() - dex_cache_length,
3357 dex_cache_length);
3358 // Example dex_cache location is SettingsProvider.apk and
3359 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003360 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003361 const OatFile* oat_file =
3362 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
3363 // Clean up pass to remove null dex caches. Also check if we need to initialize OatFile .bss.
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003364 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003365 bool initialize_oat_file_bss = (oat_file != nullptr);
Ian Rogers55256cb2017-12-21 17:07:11 -08003366 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003367 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3368 DexCacheData data = *it;
3369 if (self->IsJWeakCleared(data.weak_root)) {
3370 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003371 it = dex_caches_.erase(it);
3372 } else {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003373 if (initialize_oat_file_bss &&
3374 it->dex_file->GetOatDexFile() != nullptr &&
3375 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
3376 initialize_oat_file_bss = false; // Already initialized.
3377 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003378 ++it;
3379 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003380 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003381 if (initialize_oat_file_bss) {
3382 // TODO: Pre-initialize from boot/app image?
3383 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3384 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3385 entry = resolution_method;
3386 }
3387 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003388 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003389 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003390 DexCacheData data;
3391 data.weak_root = dex_cache_jweak;
3392 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003393 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky440a9b32018-02-15 17:47:29 +00003394 AddNativeDebugInfoForDex(self, ArrayRef<const uint8_t>(data.dex_file->Begin(),
3395 data.dex_file->Size()));
Vladimir Markocd556b02017-02-03 11:47:34 +00003396 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003397 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3398 // path dex caches without an image.
3399 data.class_table->InsertStrongRoot(dex_cache);
3400 if (class_loader != nullptr) {
3401 // Since we added a strong root to the class table, do the write barrier as required for
3402 // remembered sets and generational GCs.
3403 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3404 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003405 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003406}
3407
Vladimir Markocd556b02017-02-03 11:47:34 +00003408ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3409 return data.IsValid()
3410 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3411 : nullptr;
3412}
3413
3414ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3415 Thread* self,
3416 ObjPtr<mirror::DexCache> dex_cache,
3417 const DexCacheData& data,
3418 ObjPtr<mirror::ClassLoader> class_loader) {
3419 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3420 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3421 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3422 "Attempt to register dex file %s with multiple class loaders",
3423 data.dex_file->GetLocation().c_str());
3424 return nullptr;
3425 }
3426 return dex_cache;
3427}
3428
Alex Light07f06212017-06-01 14:01:43 -07003429void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3430 ObjPtr<mirror::ClassLoader> class_loader) {
3431 Thread* self = Thread::Current();
3432 StackHandleScope<2> hs(self);
3433 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3434 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3435 const DexFile* dex_file = dex_cache->GetDexFile();
3436 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3437 if (kIsDebugBuild) {
3438 DexCacheData old_data;
3439 {
3440 ReaderMutexLock mu(self, *Locks::dex_lock_);
3441 old_data = FindDexCacheDataLocked(*dex_file);
3442 }
3443 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3444 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3445 << "been registered on dex file " << dex_file->GetLocation();
3446 }
3447 ClassTable* table;
3448 {
3449 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3450 table = InsertClassTableForClassLoader(h_class_loader.Get());
3451 }
3452 WriterMutexLock mu(self, *Locks::dex_lock_);
3453 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3454 table->InsertStrongRoot(h_dex_cache.Get());
3455 if (h_class_loader.Get() != nullptr) {
3456 // Since we added a strong root to the class table, do the write barrier as required for
3457 // remembered sets and generational GCs.
3458 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3459 }
3460}
3461
Vladimir Markocd556b02017-02-03 11:47:34 +00003462ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3463 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003464 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003465 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003466 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003467 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003468 old_data = FindDexCacheDataLocked(dex_file);
3469 }
3470 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3471 if (old_dex_cache != nullptr) {
3472 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003473 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003474 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3475 DCHECK(linear_alloc != nullptr);
3476 ClassTable* table;
3477 {
3478 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3479 table = InsertClassTableForClassLoader(class_loader);
3480 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003481 // Don't alloc while holding the lock, since allocation may need to
3482 // suspend all threads and another thread may need the dex_lock_ to
3483 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003484 StackHandleScope<3> hs(self);
3485 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003486 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003487 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3488 self,
3489 dex_file)));
3490 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003491 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003492 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003493 old_data = FindDexCacheDataLocked(dex_file);
3494 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003495 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003496 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3497 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3498 // that the arrays are null.
3499 mirror::DexCache::InitializeDexCache(self,
3500 h_dex_cache.Get(),
3501 h_location.Get(),
3502 &dex_file,
3503 linear_alloc,
3504 image_pointer_size_);
3505 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003506 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003507 }
3508 if (old_dex_cache != nullptr) {
3509 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3510 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003511 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003512 self->ClearException();
3513 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3514 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3515 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003516 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003517 self->AssertPendingOOMException();
3518 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003519 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003520 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003521 if (h_class_loader.Get() != nullptr) {
3522 // Since we added a strong root to the class table, do the write barrier as required for
3523 // remembered sets and generational GCs.
3524 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3525 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003526 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003527}
3528
Vladimir Markocd556b02017-02-03 11:47:34 +00003529bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003530 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003531 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003532}
3533
Vladimir Markocd556b02017-02-03 11:47:34 +00003534ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3535 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003536 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3537 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003538 if (dex_cache != nullptr) {
3539 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003540 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003541 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003542 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003543 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003544 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003545 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003546 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003547 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3548 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003549 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003550}
3551
Vladimir Markocd556b02017-02-03 11:47:34 +00003552ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3553 const DexFile* dex_file = dex_cache->GetDexFile();
3554 DCHECK(dex_file != nullptr);
3555 ReaderMutexLock mu(self, *Locks::dex_lock_);
3556 // Search assuming unique-ness of dex file.
3557 for (const DexCacheData& data : dex_caches_) {
3558 // Avoid decoding (and read barriers) other unrelated dex caches.
3559 if (data.dex_file == dex_file) {
3560 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3561 if (registered_dex_cache != nullptr) {
3562 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3563 return data.class_table;
3564 }
3565 }
3566 }
3567 return nullptr;
3568}
3569
3570ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3571 // Search assuming unique-ness of dex file.
3572 for (const DexCacheData& data : dex_caches_) {
3573 // Avoid decoding (and read barriers) other unrelated dex caches.
3574 if (data.dex_file == &dex_file) {
3575 return data;
3576 }
3577 }
3578 return DexCacheData();
3579}
3580
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003581mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003582 ObjPtr<mirror::Class> klass =
3583 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003584 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003585 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003586 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003587 }
3588 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003589}
3590
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003591mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003592 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003593 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003594 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003595 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003596 StackHandleScope<1> hs(self);
3597 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003598 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003599 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3600 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003601 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00003602 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003603 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003604 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3605 h_class.Get(),
3606 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003607 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003608 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003609}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003610
Brian Carlstrombe977852011-07-19 14:54:54 -07003611// Create an array class (i.e. the class object for the array, not the
3612// array itself). "descriptor" looks like "[C" or "[[[[B" or
3613// "[Ljava/lang/String;".
3614//
3615// If "descriptor" refers to an array of primitives, look up the
3616// primitive type's internally-generated class object.
3617//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003618// "class_loader" is the class loader of the class that's referring to
3619// us. It's used to ensure that we're looking for the element type in
3620// the right context. It does NOT become the class loader for the
3621// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003622//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003623// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003624mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003625 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003626 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003627 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003628 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003629 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3630 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003631 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003632 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003633 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003634 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3635 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003636 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003637 DCHECK(self->IsExceptionPending());
3638 return nullptr;
3639 } else {
3640 self->ClearException();
3641 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003642 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003643 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3644 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3645 return nullptr;
3646 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003647 // See if the component type is already loaded. Array classes are
3648 // always associated with the class loader of their underlying
3649 // element type -- an array of Strings goes with the loader for
3650 // java/lang/String -- so we need to look for it there. (The
3651 // caller should have checked for the existence of the class
3652 // before calling here, but they did so with *their* class loader,
3653 // not the component type's loader.)
3654 //
3655 // If we find it, the caller adds "loader" to the class' initiating
3656 // loader list, which should prevent us from going through this again.
3657 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003658 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003659 // are the same, because our caller (FindClass) just did the
3660 // lookup. (Even if we get this wrong we still have correct behavior,
3661 // because we effectively do this lookup again when we add the new
3662 // class to the hash table --- necessary because of possible races with
3663 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003664 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003665 ObjPtr<mirror::Class> new_class =
3666 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003667 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003668 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003669 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003670 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003671
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003672 // Fill out the fields in the Class.
3673 //
3674 // It is possible to execute some methods against arrays, because
3675 // all arrays are subclasses of java_lang_Object_, so we need to set
3676 // up a vtable. We can just point at the one in java_lang_Object_.
3677 //
3678 // Array classes are simple enough that we don't need to do a full
3679 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003680 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003681 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003682 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003683 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003684 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003685 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003686 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003687 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003688 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003689 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003690 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003691 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003692 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003693 } else if (strcmp(descriptor, "[J") == 0) {
3694 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003695 }
3696 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003697 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003698 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003699 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003700 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003701 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003702 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003703 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003704 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003705 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003706 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003707 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003708 new_class->SetSuperClass(java_lang_Object);
3709 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003710 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003711 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003712 if (component_type->IsPrimitive()) {
3713 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3714 } else {
3715 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3716 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00003717 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003718 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3719 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3720 new_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003721 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003722 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003723 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003724
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003725 // All arrays have java/lang/Cloneable and java/io/Serializable as
3726 // interfaces. We need to set that up here, so that stuff like
3727 // "instanceof" works right.
3728 //
3729 // Note: The GC could run during the call to FindSystemClass,
3730 // so we need to make sure the class object is GC-valid while we're in
3731 // there. Do this by clearing the interface list so the GC will just
3732 // think that the entries are null.
3733
3734
3735 // Use the single, global copies of "interfaces" and "iftable"
3736 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003737 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003738 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003739 CHECK(array_iftable != nullptr);
3740 new_class->SetIfTable(array_iftable);
3741 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003742
Elliott Hughes00626c22013-06-14 15:04:14 -07003743 // Inherit access flags from the component type.
3744 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3745 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3746 access_flags &= kAccJavaFlagsMask;
3747 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003748 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003749 access_flags |= kAccAbstract | kAccFinal;
3750 access_flags &= ~kAccInterface;
3751
3752 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003753
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003754 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003755 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003756 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3757 // duplicate events in case of races. Array classes don't really follow dedicated
3758 // load and prepare, anyways.
3759 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3760 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3761
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003762 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003763 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003764 }
3765 // Another thread must have loaded the class after we
3766 // started but before we finished. Abandon what we've
3767 // done.
3768 //
3769 // (Yes, this happens.)
3770
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003771 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003772}
3773
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003774mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003775 switch (type) {
3776 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003777 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003778 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003779 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003780 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003781 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003782 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003783 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003784 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003785 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003786 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003787 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003788 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003789 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003790 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003791 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003792 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003793 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003794 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003795 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003796 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003797 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003798 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003799 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003800}
3801
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003802mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003803 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003804 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003805 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003806 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003807 source += " from ";
3808 source += dex_cache->GetLocation()->ToModifiedUtf8();
3809 }
3810 LOG(INFO) << "Loaded class " << descriptor << source;
3811 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003812 {
3813 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003814 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003815 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003816 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003817 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003818 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003819 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003820 VerifyObject(klass);
3821 class_table->InsertWithHash(klass, hash);
3822 if (class_loader != nullptr) {
3823 // This is necessary because we need to have the card dirtied for remembered sets.
3824 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3825 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003826 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003827 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003828 }
3829 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003830 if (kIsDebugBuild) {
3831 // Test that copied methods correctly can find their holder.
3832 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3833 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3834 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003835 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003836 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003837}
3838
Vladimir Marko1998cd02017-01-13 13:02:58 +00003839void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003840 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3841 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3842 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3843 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003844 }
3845}
3846
Alex Lighte64300b2015-12-15 15:02:47 -08003847// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003848void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003849 LengthPrefixedArray<ArtMethod>* new_methods) {
3850 klass->SetMethodsPtrUnchecked(new_methods,
3851 klass->NumDirectMethods(),
3852 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003853 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003854 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003855}
3856
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003857mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003858 const char* descriptor,
3859 ObjPtr<mirror::ClassLoader> class_loader) {
3860 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3861}
3862
3863mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003864 const char* descriptor,
3865 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003866 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003867 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3868 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3869 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003870 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003871 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003872 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003873 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003874 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003875 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003876}
3877
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003878class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3879 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08003880 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003881
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003882 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003883 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003884 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003885 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003886 if (class_table != nullptr) {
3887 class_table->FreezeSnapshot();
3888 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003889 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003890};
3891
3892void ClassLinker::MoveClassTableToPreZygote() {
3893 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003894 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003895 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003896 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003897}
3898
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003899// Look up classes by hash and descriptor and put all matching ones in the result array.
3900class LookupClassesVisitor : public ClassLoaderVisitor {
3901 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003902 LookupClassesVisitor(const char* descriptor,
3903 size_t hash,
3904 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003905 : descriptor_(descriptor),
3906 hash_(hash),
3907 result_(result) {}
3908
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003909 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003910 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003911 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003912 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003913 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3914 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003915 result_->push_back(klass);
3916 }
3917 }
3918
3919 private:
3920 const char* const descriptor_;
3921 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003922 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003923};
3924
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003925void ClassLinker::LookupClasses(const char* descriptor,
3926 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003927 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003928 Thread* const self = Thread::Current();
3929 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003930 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003931 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003932 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003933 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003934 result.push_back(klass);
3935 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003936 LookupClassesVisitor visitor(descriptor, hash, &result);
3937 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003938}
3939
Alex Lightf1f10492015-10-07 16:08:36 -07003940bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3941 Handle<mirror::Class> klass,
3942 Handle<mirror::Class> supertype) {
3943 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003944 DCHECK(klass != nullptr);
3945 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003946
Alex Lightf1f10492015-10-07 16:08:36 -07003947 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3948 VerifyClass(self, supertype);
3949 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003950
3951 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3952 // The supertype is either verified, or we soft failed at AOT time.
3953 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003954 return true;
3955 }
3956 // If we got this far then we have a hard failure.
3957 std::string error_msg =
3958 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003959 klass->PrettyDescriptor().c_str(),
3960 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003961 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003962 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003963 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003964 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003965 // Set during VerifyClass call (if at all).
3966 self->ClearException();
3967 }
3968 // Change into a verify error.
3969 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003970 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003971 self->GetException()->SetCause(cause.Get());
3972 }
3973 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3974 if (Runtime::Current()->IsAotCompiler()) {
3975 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3976 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003977 // Need to grab the lock to change status.
3978 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003979 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003980 return false;
3981}
3982
Andreas Gampecc1b5352016-12-01 16:58:38 -08003983// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
3984// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
3985// before.
3986static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
3987 REQUIRES_SHARED(Locks::mutator_lock_) {
3988 if (!klass->WasVerificationAttempted()) {
3989 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
3990 klass->SetVerificationAttempted();
3991 }
3992}
3993
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003994verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01003995 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07003996 {
3997 // TODO: assert that the monitor on the Class is held
3998 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003999
Andreas Gampe884f3b82016-03-30 19:52:58 -07004000 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004001 ClassStatus old_status = klass->GetStatus();
4002 while (old_status == ClassStatus::kVerifying ||
4003 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004004 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004005 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4006 // case we may see the same status again. b/62912904. This is why the check is
4007 // greater or equal.
4008 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004009 << "Class '" << klass->PrettyClass()
4010 << "' performed an illegal verification state transition from " << old_status
4011 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004012 old_status = klass->GetStatus();
4013 }
jeffhao98eacac2011-09-14 16:11:53 -07004014
Andreas Gampe884f3b82016-03-30 19:52:58 -07004015 // The class might already be erroneous, for example at compile time if we attempted to verify
4016 // this class as a parent to another.
4017 if (klass->IsErroneous()) {
4018 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004019 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004020 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004021
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004022 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004023 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004024 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004025 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004026 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004027
4028 // For AOT, don't attempt to re-verify if we have already found we should
4029 // verify at runtime.
4030 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004031 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004032 }
jeffhao98eacac2011-09-14 16:11:53 -07004033
Vladimir Marko2c64a832018-01-04 11:31:56 +00004034 if (klass->GetStatus() == ClassStatus::kResolved) {
4035 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004036 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004037 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004038 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004039 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004040 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004041 }
4042
4043 // Skip verification if disabled.
4044 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004045 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004046 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004047 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004048 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004049 }
4050
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004051 VLOG(class_linker) << "Beginning verification for class: "
4052 << klass->PrettyDescriptor()
4053 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4054
Ian Rogers9ffb0392012-09-10 11:56:50 -07004055 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004056 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004057 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4058 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004059 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004060 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004061 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004062 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004063
Alex Lightf1f10492015-10-07 16:08:36 -07004064 // Verify all default super-interfaces.
4065 //
4066 // (1) Don't bother if the superclass has already had a soft verification failure.
4067 //
4068 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4069 // recursive initialization by themselves. This is because when an interface is initialized
4070 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4071 // but choose not to for an optimization. If the interfaces is being verified due to a class
4072 // initialization (which would need all the default interfaces to be verified) the class code
4073 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004074 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004075 && !klass->IsInterface()) { // See (2)
4076 int32_t iftable_count = klass->GetIfTableCount();
4077 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4078 // Loop through all interfaces this class has defined. It doesn't matter the order.
4079 for (int32_t i = 0; i < iftable_count; i++) {
4080 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004081 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004082 // We only care if we have default interfaces and can skip if we are already verified...
4083 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4084 continue;
4085 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4086 // We had a hard failure while verifying this interface. Just return immediately.
4087 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004088 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004089 } else if (UNLIKELY(!iface->IsVerified())) {
4090 // We softly failed to verify the iface. Stop checking and clean up.
4091 // Put the iface into the supertype handle so we know what caused us to fail.
4092 supertype.Assign(iface.Get());
4093 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004094 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004095 }
4096 }
4097
Alex Lightf1f10492015-10-07 16:08:36 -07004098 // At this point if verification failed, then supertype is the "first" supertype that failed
4099 // verification (without a specific order). If verification succeeded, then supertype is either
4100 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004101 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004102 supertype.Get() == klass->GetSuperClass() ||
4103 !supertype->IsVerified());
4104
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004105 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004106 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004107 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004108 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004109
4110 VLOG(class_linker) << "Class preverified status for class "
4111 << klass->PrettyDescriptor()
4112 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4113 << ": "
4114 << preverified;
4115
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004116 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4117 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004118 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4119 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004120
Ian Rogers62d6c772013-02-27 08:32:07 -08004121 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004122 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004123 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004124 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004125 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004126
4127 // Verification is done, grab the lock again.
4128 ObjectLock<mirror::Class> lock(self, klass);
4129
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004130 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4131 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004132 VLOG(class_linker) << "Soft verification failure in class "
4133 << klass->PrettyDescriptor()
4134 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4135 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004136 }
Ian Rogers1f539342012-10-03 21:09:42 -07004137 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004138 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004139 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004140 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004141 // Even though there were no verifier failures we need to respect whether the super-class and
4142 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004143 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004144 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004145 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004146 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4147 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004148 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004149 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004150 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004151 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004152 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004153 // Soft failures at compile time should be retried at runtime. Soft
4154 // failures at runtime will be handled by slow paths in the generated
4155 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004156 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004157 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004158 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004159 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004160 // As this is a fake verified status, make sure the methods are _not_ marked
4161 // kAccSkipAccessChecks later.
4162 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004163 }
4164 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004165 } else {
David Sehr709b0702016-10-13 09:12:37 -07004166 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004167 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4168 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004169 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004170 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004171 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004172 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004173 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004174 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004175 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004176 // method.
4177 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004178 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004179 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004180
4181 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4182 // Never skip access checks if the verification soft fail is forced.
4183 // Mark the class as having a verification attempt to avoid re-running the verifier.
4184 klass->SetVerificationAttempted();
4185 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004186 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004187 }
Andreas Gampe48498592014-09-10 19:48:05 -07004188 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004189 // Done verifying. Notify the compiler about the verification status, in case the class
4190 // was verified implicitly (eg super class of a compiled class).
4191 if (Runtime::Current()->IsAotCompiler()) {
4192 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4193 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4194 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004195 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004196}
4197
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004198verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4199 Handle<mirror::Class> klass,
4200 verifier::HardFailLogMode log_level,
4201 std::string* error_msg) {
4202 Runtime* const runtime = Runtime::Current();
4203 return verifier::MethodVerifier::VerifyClass(self,
4204 klass.Get(),
4205 runtime->GetCompilerCallbacks(),
4206 runtime->IsAotCompiler(),
4207 log_level,
4208 error_msg);
4209}
4210
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004211bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004212 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004213 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004214 // If we're compiling, we can only verify the class using the oat file if
4215 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004216 // the compilation unit (app - dependencies). We will let the compiler callback
4217 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004218 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004219 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004220 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004221 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004222 return false;
4223 }
4224 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004225 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004226 return false;
4227 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004228 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004229
Richard Uhler07b3c232015-03-31 15:57:54 -07004230 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004231 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004232 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004233 return false;
4234 }
4235
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004236 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004237 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004238 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004239 return true;
4240 }
4241 // If we only verified a subset of the classes at compile time, we can end up with classes that
4242 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004243 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004244 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004245 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004246 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004247 // Compile time verification failed with a soft error. Compile time verification can fail
4248 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004249 // class ... {
4250 // Foo x;
4251 // .... () {
4252 // if (...) {
4253 // v1 gets assigned a type of resolved class Foo
4254 // } else {
4255 // v1 gets assigned a type of unresolved class Bar
4256 // }
4257 // iput x = v1
4258 // } }
4259 // when we merge v1 following the if-the-else it results in Conflict
4260 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4261 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4262 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4263 // at compile time).
4264 return false;
4265 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004266 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004267 // Compile time verification failed with a hard error. This is caused by invalid instructions
4268 // in the class. These errors are unrecoverable.
4269 return false;
4270 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004271 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004272 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4273 // not loading the class.
4274 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4275 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004276 return false;
4277 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004278 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004279 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004280 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004281 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004282 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004283}
4284
Alex Light5a559862016-01-29 12:24:48 -08004285void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004286 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004287 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004288 }
4289}
4290
Alex Light5a559862016-01-29 12:24:48 -08004291void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004292 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004293 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004294 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004295 return; // native or abstract method
4296 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004297 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004298 return; // nothing to process
4299 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004300 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004301 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004302 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4303 CatchHandlerIterator iterator(handlers_ptr);
4304 for (; iterator.HasNext(); iterator.Next()) {
4305 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4306 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004307 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004308 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004309 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004310 DCHECK(Thread::Current()->IsExceptionPending());
4311 Thread::Current()->ClearException();
4312 }
4313 }
4314 }
4315 handlers_ptr = iterator.EndDataPointer();
4316 }
4317}
4318
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004319mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4320 jstring name,
4321 jobjectArray interfaces,
4322 jobject loader,
4323 jobjectArray methods,
4324 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004325 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004326 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004327 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004328 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004329 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004330 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004331 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004332 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004333 DCHECK(temp_klass->GetClass() != nullptr);
4334 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004335 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4336 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004337 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4338 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4339 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4340 temp_klass->SetName(soa.Decode<mirror::String>(name));
4341 temp_klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004342 // Object has an empty iftable, copy it for that reason.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004343 temp_klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004344 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004345 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004346 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004347
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004348 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004349 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004350
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004351 // Insert the class before loading the fields as the field roots
4352 // (ArtField::declaring_class_) are only visited from the class
4353 // table. There can't be any suspend points between inserting the
4354 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004355 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004356 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004357
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004358 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004359 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004360 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004361 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004362
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004363 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4364 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004365 ArtField& interfaces_sfield = sfields->At(0);
4366 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004367 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004368 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004369
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004370 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004371 ArtField& throws_sfield = sfields->At(1);
4372 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004373 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004374 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004375
Ian Rogers466bb252011-10-14 03:29:56 -07004376 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004377 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004378
Alex Lighte64300b2015-12-15 15:02:47 -08004379 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004380 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004381 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004382 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004383 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004384
4385 // Create the methods array.
4386 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4387 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004388 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4389 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004390 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004391 self->AssertPendingOOMException();
4392 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004393 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004394 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004395
4396 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004397 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004398
4399 // Create virtual method using specified prototypes.
4400 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004401 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004402 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004403 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004404 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004405 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4406 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004407 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004408
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004409 // The super class is java.lang.reflect.Proxy
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004410 temp_klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004411 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004412 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004413 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004414
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004415 // At this point the class is loaded. Publish a ClassLoad event.
4416 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4417 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4418
4419 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004420 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004421 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004422 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004423 // Link the fields and virtual methods, creating vtable and iftables.
4424 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004425 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004426 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004427 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004428 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004429 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004430 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004431 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004432 CHECK(temp_klass->IsRetired());
4433 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004434
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004435 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004436 interfaces_sfield.SetObject<false>(
4437 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004438 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004439 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4440 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004441 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004442 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004443
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004444 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4445
Vladimir Marko305c38b2018-02-14 11:50:07 +00004446 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4447 // See also ClassLinker::EnsureInitialized().
4448 if (kBitstringSubtypeCheckEnabled) {
4449 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4450 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4451 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4452 }
4453
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004454 {
4455 // Lock on klass is released. Lock new class object.
4456 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004457 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004458 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004459
4460 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004461 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004462 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004463 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4464
Ian Rogersc2b44472011-12-14 21:17:17 -08004465 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004466 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4467 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004468 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004469 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004470
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004471 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004472 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004473 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004474 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004475 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004476
4477 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004478 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004479 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004480
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004481 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004482 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004483 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004484 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004485 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004486 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004487}
4488
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004489std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004490 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004491 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004492 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004493 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4494}
4495
Mathieu Chartiere401d142015-04-22 13:56:20 -07004496void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4497 // Create constructor for Proxy that must initialize the method.
Neil Fullerd12c3b02017-11-30 18:03:15 +00004498 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004499
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004500 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4501 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markoba118822017-06-12 15:41:56 +01004502 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->FindConstructor(
4503 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004504 DCHECK(proxy_constructor != nullptr)
4505 << "Could not find <init> method in java.lang.reflect.Proxy";
4506
Jeff Haodb8a6642014-08-14 17:18:52 -07004507 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4508 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004509 DCHECK(out != nullptr);
4510 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004511 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004512 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004513 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004514 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4515 kAccPublic |
4516 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004517 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004518
4519 // Set the original constructor method.
4520 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004521}
4522
Mathieu Chartiere401d142015-04-22 13:56:20 -07004523void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004524 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004525 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4526 CHECK_STREQ(np->GetName(), "<init>");
4527 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004528 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004529}
4530
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004531void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004532 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004533 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004534 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004535 DCHECK(out != nullptr);
4536 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004537
Alex Lighte9dd04f2016-03-16 16:09:45 -07004538 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004539 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004540 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4541 // preference to the invocation handler.
4542 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4543 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004544 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4545 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004546 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4547
4548 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4549 // method they copy might (if it's a default method).
4550 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004551
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004552 // Set the original interface method.
4553 out->SetDataPtrSize(prototype, image_pointer_size_);
4554
Ian Rogers466bb252011-10-14 03:29:56 -07004555 // At runtime the method looks like a reference and argument saving method, clone the code
4556 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004557 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004558}
Jesse Wilson95caa792011-10-12 18:14:17 -04004559
Mathieu Chartiere401d142015-04-22 13:56:20 -07004560void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004561 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004562 CHECK(!prototype->IsFinal());
4563 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004564 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004565
4566 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4567 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004568 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004569 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004570}
4571
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004572bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004573 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004574 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004575 return true;
4576 }
4577 if (!can_init_statics) {
4578 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004579 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004580 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004581 return false;
4582 }
4583 // Check if there are encoded static values needing initialization.
4584 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004585 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004586 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004587 if (dex_class_def->static_values_off_ != 0) {
4588 return false;
4589 }
4590 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004591 // If we are a class we need to initialize all interfaces with default methods when we are
4592 // initialized. Check all of them.
4593 if (!klass->IsInterface()) {
4594 size_t num_interfaces = klass->GetIfTableCount();
4595 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004596 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004597 if (iface->HasDefaultMethods() &&
4598 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4599 return false;
4600 }
4601 }
4602 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004603 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004604 if (klass->IsInterface() || !klass->HasSuperClass()) {
4605 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004606 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004607 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004608 if (!can_init_parents && !super_class->IsInitialized()) {
4609 return false;
4610 }
4611 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004612}
4613
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004614bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4615 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004616 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4617
4618 // Are we already initialized and therefore done?
4619 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4620 // an initialized class will never change its state.
4621 if (klass->IsInitialized()) {
4622 return true;
4623 }
4624
4625 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004626 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004627 return false;
4628 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004629
Ian Rogers7b078e82014-09-10 14:44:24 -07004630 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004631 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004632 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004633 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004634
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004635 // Re-check under the lock in case another thread initialized ahead of us.
4636 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004637 return true;
4638 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004639
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004640 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004641 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004642 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004643 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004644 return false;
4645 }
4646
Vladimir Marko72ab6842017-01-20 19:32:50 +00004647 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4648 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004649
4650 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004651 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004652 if (!klass->IsVerified()) {
4653 // We failed to verify, expect either the klass to be erroneous or verification failed at
4654 // compile time.
4655 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004656 // The class is erroneous. This may be a verifier error, or another thread attempted
4657 // verification and/or initialization and failed. We can distinguish those cases by
4658 // whether an exception is already pending.
4659 if (self->IsExceptionPending()) {
4660 // Check that it's a VerifyError.
4661 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004662 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004663 } else {
4664 // Check that another thread attempted initialization.
4665 DCHECK_NE(0, klass->GetClinitThreadId());
4666 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4667 // Need to rethrow the previous failure now.
4668 ThrowEarlierClassFailure(klass.Get(), true);
4669 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004670 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004671 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004672 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004673 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004674 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004675 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004676 } else {
4677 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004678 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004679
4680 // A separate thread could have moved us all the way to initialized. A "simple" example
4681 // involves a subclass of the current class being initialized at the same time (which
4682 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004683 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004684 if (klass->IsInitialized()) {
4685 return true;
4686 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004687 }
4688
Vladimir Marko2c64a832018-01-04 11:31:56 +00004689 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07004690 // initializing higher up the stack or another thread has beat us
4691 // to initializing and we need to wait. Either way, this
4692 // invocation of InitializeClass will not be responsible for
4693 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004694 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004695 // Could have got an exception during verification.
4696 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004697 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004698 return false;
4699 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004700 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004701 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004702 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004703 return true;
4704 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004705 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004706 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 }
4708
Jeff Haoe2e40342017-07-19 10:45:18 -07004709 // Try to get the oat class's status for this class if the oat file is present. The compiler
4710 // tries to validate superclass descriptors, and writes the result into the oat file.
4711 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4712 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4713 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004714 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004715 const Runtime* runtime = Runtime::Current();
4716 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4717 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4718 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004719 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07004720 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004721 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 return false;
4723 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004724 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004725
Vladimir Marko2c64a832018-01-04 11:31:56 +00004726 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004727 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004728
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004729 // From here out other threads may observe that we're initializing and so changes of state
4730 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004731 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004732 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004733
4734 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004735 }
4736
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004737 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004738 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004739 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004740 if (!super_class->IsInitialized()) {
4741 CHECK(!super_class->IsInterface());
4742 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004743 StackHandleScope<1> hs(self);
4744 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004745 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004746 if (!super_initialized) {
4747 // The super class was verified ahead of entering initializing, we should only be here if
4748 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004749 // For the case of aot compiler, the super class might also be initializing but we don't
4750 // want to process circular dependencies in pre-compile.
4751 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004752 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004753 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004754 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004755 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004756 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004757 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004758 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004759 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004760 return false;
4761 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004762 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004763 }
4764
Alex Lighteb7c1442015-08-31 13:17:42 -07004765 if (!klass->IsInterface()) {
4766 // Initialize interfaces with default methods for the JLS.
4767 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004768 // Only setup the (expensive) handle scope if we actually need to.
4769 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004770 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004771 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4772 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004773 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004774 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004775 CHECK(handle_scope_iface->IsInterface());
4776 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4777 // We have already done this for this interface. Skip it.
4778 continue;
4779 }
4780 // We cannot just call initialize class directly because we need to ensure that ALL
4781 // interfaces with default methods are initialized. Non-default interface initialization
4782 // will not affect other non-default super-interfaces.
4783 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4784 handle_scope_iface,
4785 can_init_statics,
4786 can_init_parents);
4787 if (!iface_initialized) {
4788 ObjectLock<mirror::Class> lock(self, klass);
4789 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004790 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004791 return false;
4792 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004793 }
4794 }
4795 }
4796
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004797 const size_t num_static_fields = klass->NumStaticFields();
4798 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004799 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004800 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004801 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004802 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004803 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004804
4805 // Eagerly fill in static fields so that the we don't have to do as many expensive
4806 // Class::FindStaticField in ResolveField.
4807 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004808 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004809 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004810 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004811 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004812 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004813 } else {
4814 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004815 }
4816 }
4817
Vladimir Markoe11dd502017-12-08 14:09:45 +00004818 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
4819 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07004820 this,
4821 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00004822 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers13735952014-10-08 12:43:28 -07004823 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004824 ClassDataItemIterator field_it(dex_file, class_data);
4825 if (value_it.HasNext()) {
4826 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004827 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004828 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004829 ArtField* field = ResolveField(
Vladimir Markoe11dd502017-12-08 14:09:45 +00004830 field_it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004831 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004832 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004833 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004834 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004835 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004836 if (self->IsExceptionPending()) {
4837 break;
4838 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004839 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004840 }
4841 }
4842 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004843
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004844
Mathieu Chartierda595be2016-08-10 13:57:39 -07004845 if (!self->IsExceptionPending()) {
4846 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4847 if (clinit != nullptr) {
4848 CHECK(can_init_statics);
4849 JValue result;
4850 clinit->Invoke(self, nullptr, 0, &result, "V");
4851 }
4852 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004853 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004854 uint64_t t1 = NanoTime();
4855
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004856 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004857 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004858 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004859
4860 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004861 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004862 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004863 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004864 } else if (Runtime::Current()->IsTransactionAborted()) {
4865 // The exception thrown when the transaction aborted has been caught and cleared
4866 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004867 VLOG(compiler) << "Return from class initializer of "
4868 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004869 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004870 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004871 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004872 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004873 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004874 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4875 RuntimeStats* thread_stats = self->GetStats();
4876 ++global_stats->class_init_count;
4877 ++thread_stats->class_init_count;
4878 global_stats->class_init_time_ns += (t1 - t0);
4879 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004880 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004881 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004882 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004883 std::string temp;
4884 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004885 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004886 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004887 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004888 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004889 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004890 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004891 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004892}
4893
Alex Lighteb7c1442015-08-31 13:17:42 -07004894// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4895// and perform the initialization only on those interfaces that contain default methods.
4896bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4897 Handle<mirror::Class> iface,
4898 bool can_init_statics,
4899 bool can_init_parents) {
4900 CHECK(iface->IsInterface());
4901 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004902 // Only create the (expensive) handle scope if we need it.
4903 if (UNLIKELY(num_direct_ifaces > 0)) {
4904 StackHandleScope<1> hs(self);
4905 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4906 // First we initialize all of iface's super-interfaces recursively.
4907 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004908 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004909 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004910 if (!super_iface->HasBeenRecursivelyInitialized()) {
4911 // Recursive step
4912 handle_super_iface.Assign(super_iface);
4913 if (!InitializeDefaultInterfaceRecursive(self,
4914 handle_super_iface,
4915 can_init_statics,
4916 can_init_parents)) {
4917 return false;
4918 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004919 }
4920 }
4921 }
4922
4923 bool result = true;
4924 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4925 // initialize if we don't have default methods.
4926 if (iface->HasDefaultMethods()) {
4927 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4928 }
4929
4930 // Mark that this interface has undergone recursive default interface initialization so we know we
4931 // can skip it on any later class initializations. We do this even if we are not a default
4932 // interface since we can still avoid the traversal. This is purely a performance optimization.
4933 if (result) {
4934 // TODO This should be done in a better way
4935 ObjectLock<mirror::Class> lock(self, iface);
4936 iface->SetRecursivelyInitialized();
4937 }
4938 return result;
4939}
4940
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004941bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4942 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004943 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004944 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004945 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004946 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004947 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004948 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004949
4950 // When we wake up, repeat the test for init-in-progress. If
4951 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004952 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004953 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004954 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004955 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004956 return false;
4957 }
4958 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004959 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004960 continue;
4961 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004962 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004963 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004964 // Compile time initialization failed.
4965 return false;
4966 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004967 if (klass->IsErroneous()) {
4968 // The caller wants an exception, but it was thrown in a
4969 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004970 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004971 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004972 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004973 return false;
4974 }
4975 if (klass->IsInitialized()) {
4976 return true;
4977 }
David Sehr709b0702016-10-13 09:12:37 -07004978 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004979 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004980 }
Ian Rogers07140832014-09-30 15:43:59 -07004981 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004982}
4983
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004984static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4985 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004986 ArtMethod* method,
4987 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004988 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004989 DCHECK(Thread::Current()->IsExceptionPending());
4990 DCHECK(!m->IsProxyMethod());
4991 const DexFile* dex_file = m->GetDexFile();
4992 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4993 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004994 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07004995 std::string return_type = dex_file->PrettyType(return_type_idx);
4996 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004997 ThrowWrappedLinkageError(klass.Get(),
4998 "While checking class %s method %s signature against %s %s: "
4999 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005000 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5001 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005002 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005003 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005004 return_type.c_str(), class_loader.c_str());
5005}
5006
5007static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5008 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005009 ArtMethod* method,
5010 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005011 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005012 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005013 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005014 DCHECK(Thread::Current()->IsExceptionPending());
5015 DCHECK(!m->IsProxyMethod());
5016 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005017 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5018 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005019 ThrowWrappedLinkageError(klass.Get(),
5020 "While checking class %s method %s signature against %s %s: "
5021 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005022 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5023 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005024 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005025 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005026 index, arg_type.c_str(), class_loader.c_str());
5027}
5028
5029static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5030 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005031 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005032 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005033 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005034 ThrowLinkageError(klass.Get(),
5035 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005036 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5037 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005038 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005039 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005040 error_msg.c_str());
5041}
5042
Ian Rogersb5fb2072014-12-02 17:22:02 -08005043static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005044 Handle<mirror::Class> klass,
5045 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005046 ArtMethod* method1,
5047 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005048 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005049 {
5050 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005051 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005052 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005053 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005054 return false;
5055 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005056 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005057 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005058 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005059 return false;
5060 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005061 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005062 ThrowSignatureMismatch(klass, super_klass, method1,
5063 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005064 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005065 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005066 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005067 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005068 return false;
5069 }
5070 }
5071 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5072 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5073 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005074 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005075 ThrowSignatureMismatch(klass, super_klass, method1,
5076 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005077 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005078 return false;
5079 }
5080 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005081 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005082 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005083 ThrowSignatureMismatch(klass, super_klass, method1,
5084 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005085 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005086 return false;
5087 }
5088 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005089 }
5090 uint32_t num_types = types1->Size();
5091 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005092 ThrowSignatureMismatch(klass, super_klass, method1,
5093 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005094 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005095 return false;
5096 }
5097 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005098 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005099 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005100 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005101 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005102 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005103 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005104 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005105 return false;
5106 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005107 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005108 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005109 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005110 if (UNLIKELY(other_param_type == nullptr)) {
5111 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005112 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005113 return false;
5114 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005115 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005116 ThrowSignatureMismatch(klass, super_klass, method1,
5117 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5118 i,
David Sehr709b0702016-10-13 09:12:37 -07005119 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005120 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005121 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005122 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005123 return false;
5124 }
5125 }
5126 return true;
5127}
5128
5129
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005130bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005131 if (klass->IsInterface()) {
5132 return true;
5133 }
Ian Rogers151f2212014-05-06 11:27:27 -07005134 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005135 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005136 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005137 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005138 if (klass->HasSuperClass() &&
5139 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005140 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005141 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005142 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5143 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5144 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005145 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5146 klass,
5147 super_klass,
5148 m,
5149 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005150 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005151 return false;
5152 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005153 }
5154 }
5155 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005156 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005157 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5158 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5159 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005160 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005161 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5162 j, image_pointer_size_);
5163 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5164 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005165 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5166 klass,
5167 super_klass,
5168 m,
5169 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005170 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005171 return false;
5172 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005173 }
5174 }
5175 }
5176 }
5177 return true;
5178}
5179
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005180bool ClassLinker::EnsureInitialized(Thread* self,
5181 Handle<mirror::Class> c,
5182 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005183 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005184 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005185
Mathieu Chartier524507a2014-08-27 15:28:28 -07005186 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005187 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005188 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005189 return true;
5190 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005191 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5192 //
5193 // Ensure the bitstring is initialized before any of the class initialization
5194 // logic occurs. Once a class initializer starts running, objects can
5195 // escape into the heap and use the subtype checking code.
5196 //
5197 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5198 // can be used as a source for the IsSubClass check, and that all ancestors
5199 // of the class are Assigned (can be used as a target for IsSubClass check)
5200 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005201 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005202 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005203 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005204 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5205 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005206 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005207 if (!success) {
5208 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005209 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005210 }
5211 } else {
5212 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005213 }
5214 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005215}
5216
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005217void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5218 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005219 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005220 for (ArtField& field : new_class->GetIFields()) {
5221 if (field.GetDeclaringClass() == temp_class) {
5222 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005223 }
5224 }
5225
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005226 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005227 for (ArtField& field : new_class->GetSFields()) {
5228 if (field.GetDeclaringClass() == temp_class) {
5229 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005230 }
5231 }
5232
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005233 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005234 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005235 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005236 if (method.GetDeclaringClass() == temp_class) {
5237 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005238 }
5239 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005240
5241 // Make sure the remembered set and mod-union tables know that we updated some of the native
5242 // roots.
5243 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005244}
5245
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005246void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005247 CHECK(class_loader->GetAllocator() == nullptr);
5248 CHECK(class_loader->GetClassTable() == nullptr);
5249 Thread* const self = Thread::Current();
5250 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005251 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005252 // Create and set the class table.
5253 data.class_table = new ClassTable;
5254 class_loader->SetClassTable(data.class_table);
5255 // Create and set the linear allocator.
5256 data.allocator = Runtime::Current()->CreateLinearAlloc();
5257 class_loader->SetAllocator(data.allocator);
5258 // Add to the list so that we know to free the data later.
5259 class_loaders_.push_back(data);
5260}
5261
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005262ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005263 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005264 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005265 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005266 ClassTable* class_table = class_loader->GetClassTable();
5267 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005268 RegisterClassLoader(class_loader);
5269 class_table = class_loader->GetClassTable();
5270 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005271 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005272 return class_table;
5273}
5274
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005275ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005276 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005277}
5278
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005279static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005280 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005281 while (klass->HasSuperClass()) {
5282 klass = klass->GetSuperClass();
5283 if (klass->ShouldHaveImt()) {
5284 return klass->GetImt(pointer_size);
5285 }
5286 }
5287 return nullptr;
5288}
5289
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005290bool ClassLinker::LinkClass(Thread* self,
5291 const char* descriptor,
5292 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005293 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005294 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005295 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005296
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005297 if (!LinkSuperClass(klass)) {
5298 return false;
5299 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005300 ArtMethod* imt_data[ImTable::kSize];
5301 // If there are any new conflicts compared to super class.
5302 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005303 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005304 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005305 return false;
5306 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005307 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005308 return false;
5309 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005310 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005311 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005312 return false;
5313 }
5314 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005315 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005316
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005317 ImTable* imt = nullptr;
5318 if (klass->ShouldHaveImt()) {
5319 // If there are any new conflicts compared to the super class we can not make a copy. There
5320 // can be cases where both will have a conflict method at the same slot without having the same
5321 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5322 // will possibly create a table that is incorrect for either of the classes.
5323 // Same IMT with new_conflict does not happen very often.
5324 if (!new_conflict) {
5325 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5326 if (super_imt != nullptr) {
5327 bool imt_equals = true;
5328 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5329 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5330 }
5331 if (imt_equals) {
5332 imt = super_imt;
5333 }
5334 }
5335 }
5336 if (imt == nullptr) {
5337 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5338 imt = reinterpret_cast<ImTable*>(
5339 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5340 if (imt == nullptr) {
5341 return false;
5342 }
5343 imt->Populate(imt_data, image_pointer_size_);
5344 }
5345 }
5346
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005347 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5348 // We don't need to retire this class as it has no embedded tables or it was created the
5349 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005350 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005351
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005352 if (klass->ShouldHaveEmbeddedVTable()) {
5353 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005354 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005355 if (klass->ShouldHaveImt()) {
5356 klass->SetImt(imt, image_pointer_size_);
5357 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005358
5359 // Update CHA info based on whether we override methods.
5360 // Have to do this before setting the class as resolved which allows
5361 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005362 if (cha_ != nullptr) {
5363 cha_->UpdateAfterLoadingOf(klass);
5364 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005365
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005366 // This will notify waiters on klass that saw the not yet resolved
5367 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005368 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005369 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005370 } else {
5371 CHECK(!klass->IsResolved());
5372 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005373 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005374 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005375 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5376 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5377 // may not see any references to the target space and clean the card for a class if another
5378 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005379 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005380 klass->SetSFieldsPtrUnchecked(nullptr);
5381 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005382 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005383 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005384 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005385 return false;
5386 }
5387
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005388 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5389 ObjectLock<mirror::Class> lock(self, h_new_class);
5390 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005391
5392 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005393 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005394 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005395 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005396 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005397 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005398 if (class_loader != nullptr) {
5399 // We updated the class in the class table, perform the write barrier so that the GC knows
5400 // about the change.
5401 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5402 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005403 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005404 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005405 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5406 }
5407 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005408
Mingyao Yang063fc772016-08-02 11:02:54 -07005409 // Update CHA info based on whether we override methods.
5410 // Have to do this before setting the class as resolved which allows
5411 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005412 if (cha_ != nullptr) {
5413 cha_->UpdateAfterLoadingOf(h_new_class);
5414 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005415
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005416 // This will notify waiters on temp class that saw the not yet resolved class in the
5417 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005418 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005419
Vladimir Marko2c64a832018-01-04 11:31:56 +00005420 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005421 // This will notify waiters on new_class that saw the not yet resolved
5422 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005423 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005424 // Return the new class.
5425 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005426 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005427 return true;
5428}
5429
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005430bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005431 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005432 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005433 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5434 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005435 // Check that a class does not inherit from itself directly.
5436 //
5437 // TODO: This is a cheap check to detect the straightforward case
5438 // of a class extending itself (b/28685551), but we should do a
5439 // proper cycle detection on loaded classes, to detect all cases
5440 // of class circularity errors (b/28830038).
5441 if (super_class_idx == class_def.class_idx_) {
5442 ThrowClassCircularityError(klass.Get(),
5443 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005444 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005445 return false;
5446 }
5447
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005448 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005449 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005450 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005451 return false;
5452 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005453 // Verify
5454 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005455 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005456 super_class->PrettyDescriptor().c_str(),
5457 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005458 return false;
5459 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005460 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005461 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005462 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005463 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005464 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005465 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005466 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005467 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005468 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005469 DCHECK(Thread::Current()->IsExceptionPending());
5470 return false;
5471 }
5472 // Verify
5473 if (!klass->CanAccess(interface)) {
5474 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005475 ThrowIllegalAccessError(klass.Get(),
5476 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005477 interface->PrettyDescriptor().c_str(),
5478 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005479 return false;
5480 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005481 }
5482 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005483 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005484 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005485 return true;
5486}
5487
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005488bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005489 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005490 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005491 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005492 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005493 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005494 return false;
5495 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005496 return true;
5497 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005498 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005499 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005500 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005501 return false;
5502 }
5503 // Verify
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005504 if (klass->IsInterface() && super != GetClassRoot(kJavaLangObject)) {
5505 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5506 return false;
5507 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005508 if (super->IsFinal()) {
5509 ThrowVerifyError(klass.Get(),
5510 "Superclass %s of %s is declared final",
5511 super->PrettyDescriptor().c_str(),
5512 klass->PrettyDescriptor().c_str());
5513 return false;
5514 }
5515 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005516 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005517 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005518 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005519 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005520 return false;
5521 }
5522 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005523 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005524 super->PrettyDescriptor().c_str(),
5525 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005526 return false;
5527 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005528
Brian Carlstromf3632832014-05-20 15:36:53 -07005529 // Inherit kAccClassIsFinalizable from the superclass in case this
5530 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005531 if (super->IsFinalizable()) {
5532 klass->SetFinalizable();
5533 }
5534
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005535 // Inherit class loader flag form super class.
5536 if (super->IsClassLoaderClass()) {
5537 klass->SetClassLoaderClass();
5538 }
5539
Elliott Hughes2da50362011-10-10 16:57:08 -07005540 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005541 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005542 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005543 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005544 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005545 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005546 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005547 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005548 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005549 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005550 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005551 return false;
5552 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005553
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005554 if (kIsDebugBuild) {
5555 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005556 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005557 CHECK(super->IsResolved());
5558 super = super->GetSuperClass();
5559 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005560 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005561 return true;
5562}
5563
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005564// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005565bool ClassLinker::LinkMethods(Thread* self,
5566 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005567 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005568 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005569 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005570 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005571 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5572 // need to have default methods be in the virtuals array of each class but we don't set that up
5573 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005574 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005575 // Link virtual methods then interface methods.
5576 // We set up the interface lookup table first because we need it to determine if we need to update
5577 // any vtable entries with new default method implementations.
5578 return SetupInterfaceLookupTable(self, klass, interfaces)
5579 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005580 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005581}
5582
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005583// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5584// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5585// caches in the implementation below.
5586class MethodNameAndSignatureComparator FINAL : public ValueObject {
5587 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005588 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005589 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005590 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5591 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005592 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005593 }
5594
5595 const char* GetName() {
5596 if (name_ == nullptr) {
5597 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5598 }
5599 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005600 }
5601
Mathieu Chartiere401d142015-04-22 13:56:20 -07005602 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005603 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005604 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005605 const DexFile* other_dex_file = other->GetDexFile();
5606 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5607 if (dex_file_ == other_dex_file) {
5608 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5609 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005610 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005611 uint32_t other_name_len;
5612 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5613 &other_name_len);
5614 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5615 return false;
5616 }
5617 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5618 }
5619
5620 private:
5621 // Dex file for the method to compare against.
5622 const DexFile* const dex_file_;
5623 // MethodId for the method to compare against.
5624 const DexFile::MethodId* const mid_;
5625 // Lazily computed name from the dex file's strings.
5626 const char* name_;
5627 // Lazily computed name length.
5628 uint32_t name_len_;
5629};
5630
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005631class LinkVirtualHashTable {
5632 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005633 LinkVirtualHashTable(Handle<mirror::Class> klass,
5634 size_t hash_size,
5635 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005636 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005637 : klass_(klass),
5638 hash_size_(hash_size),
5639 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005640 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005641 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5642 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005643
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005644 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005645 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5646 virtual_method_index, image_pointer_size_);
5647 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005648 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005649 uint32_t index = hash % hash_size_;
5650 // Linear probe until we have an empty slot.
5651 while (hash_table_[index] != invalid_index_) {
5652 if (++index == hash_size_) {
5653 index = 0;
5654 }
5655 }
5656 hash_table_[index] = virtual_method_index;
5657 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005658
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005659 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005660 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005661 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005662 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005663 size_t index = hash % hash_size_;
5664 while (true) {
5665 const uint32_t value = hash_table_[index];
5666 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5667 // the block and can safely assume not found.
5668 if (value == invalid_index_) {
5669 break;
5670 }
5671 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005672 ArtMethod* virtual_method =
5673 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5674 if (comparator->HasSameNameAndSignature(
5675 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005676 hash_table_[index] = removed_index_;
5677 return value;
5678 }
5679 }
5680 if (++index == hash_size_) {
5681 index = 0;
5682 }
5683 }
5684 return GetNotFoundIndex();
5685 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005686
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005687 static uint32_t GetNotFoundIndex() {
5688 return invalid_index_;
5689 }
5690
5691 private:
5692 static const uint32_t invalid_index_;
5693 static const uint32_t removed_index_;
5694
5695 Handle<mirror::Class> klass_;
5696 const size_t hash_size_;
5697 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005698 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005699};
5700
5701const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5702const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5703
Stephen Hines1ddd9132017-02-08 01:51:18 -08005704bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005705 Thread* self,
5706 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005707 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005708 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005709 if (klass->IsInterface()) {
5710 // No vtable.
5711 if (!IsUint<16>(num_virtual_methods)) {
5712 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5713 return false;
5714 }
5715 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005716 // Assign each method an IMT index and set the default flag.
5717 for (size_t i = 0; i < num_virtual_methods; ++i) {
5718 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5719 m->SetMethodIndex(i);
5720 if (!m->IsAbstract()) {
5721 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5722 has_defaults = true;
5723 }
5724 }
5725 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5726 // during initialization. This is a performance optimization. We could simply traverse the
5727 // virtual_methods_ array again during initialization.
5728 if (has_defaults) {
5729 klass->SetHasDefaultMethods();
5730 }
5731 return true;
5732 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005733 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5734 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005735 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005736 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005737 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005738 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005739 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005740 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005741 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005742 return false;
5743 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005744 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005745 vtable->SetElementPtrSize(
5746 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005747 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005748 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5749 // might give us new default methods). If no new interfaces then we can skip the rest since
5750 // the class cannot override any of the super-class's methods. This is required for
5751 // correctness since without it we might not update overridden default method vtable entries
5752 // correctly.
5753 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005754 klass->SetVTable(vtable.Get());
5755 return true;
5756 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005757 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005758 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005759 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005760 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005761 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5762 // might give us new default methods). See comment above.
5763 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005764 klass->SetVTable(super_vtable);
5765 return true;
5766 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005767 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5768 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005769 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005770 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005771 return false;
5772 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005773 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005774 // How the algorithm works:
5775 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5776 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5777 // method which has not been matched to a vtable method, and j if the virtual method at the
5778 // index overrode the super virtual method at index j.
5779 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5780 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5781 // the need for the initial vtable which we later shrink back down).
5782 // 3. Add non overridden methods to the end of the vtable.
5783 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005784 // + 1 so that even if we only have new default methods we will still be able to use this hash
5785 // table (i.e. it will never have 0 size).
5786 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005787 uint32_t* hash_table_ptr;
5788 std::unique_ptr<uint32_t[]> hash_heap_storage;
5789 if (hash_table_size <= kMaxStackHash) {
5790 hash_table_ptr = reinterpret_cast<uint32_t*>(
5791 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5792 } else {
5793 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5794 hash_table_ptr = hash_heap_storage.get();
5795 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005796 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005797 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005798 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005799 DCHECK(klass->GetVirtualMethodDuringLinking(
5800 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005801 hash_table.Add(i);
5802 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005803 // 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 -07005804 // the hash table.
5805 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005806 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005807 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005808 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5809 super_method->GetAccessFlags())) {
5810 // Continue on to the next method since this one is package private and canot be overridden.
5811 // Before Android 4.1, the package-private method super_method might have been incorrectly
5812 // overridden.
5813 continue;
5814 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005815 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005816 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005817 // We remove the method so that subsequent lookups will be faster by making the hash-map
5818 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005819 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5820 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005821 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5822 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005823 if (super_method->IsFinal()) {
5824 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5825 virtual_method->PrettyMethod().c_str(),
5826 super_method->GetDeclaringClassDescriptor());
5827 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005828 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005829 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5830 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005831 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005832 // We didn't directly override this method but we might through default methods...
5833 // Check for default method update.
5834 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005835 switch (FindDefaultMethodImplementation(self,
5836 super_method,
5837 klass,
5838 /*out*/&default_method)) {
5839 case DefaultMethodSearchResult::kDefaultConflict: {
5840 // A conflict was found looking for default methods. Note this (assuming it wasn't
5841 // pre-existing) in the translations map.
5842 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5843 // Don't generate another conflict method to reduce memory use as an optimization.
5844 default_translations->insert(
5845 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5846 }
5847 break;
5848 }
5849 case DefaultMethodSearchResult::kAbstractFound: {
5850 // No conflict but method is abstract.
5851 // We note that this vtable entry must be made abstract.
5852 if (UNLIKELY(!super_method->IsAbstract())) {
5853 default_translations->insert(
5854 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5855 }
5856 break;
5857 }
5858 case DefaultMethodSearchResult::kDefaultFound: {
5859 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5860 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5861 // Found a default method implementation that is new.
5862 // TODO Refactor this add default methods to virtuals here and not in
5863 // LinkInterfaceMethods maybe.
5864 // The problem is default methods might override previously present
5865 // default-method or miranda-method vtable entries from the superclass.
5866 // Unfortunately we need these to be entries in this class's virtuals. We do not
5867 // give these entries there until LinkInterfaceMethods so we pass this map around
5868 // to let it know which vtable entries need to be updated.
5869 // Make a note that vtable entry j must be updated, store what it needs to be updated
5870 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5871 // then.
5872 default_translations->insert(
5873 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005874 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5875 << " overridden by default "
5876 << default_method->PrettyMethod()
5877 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005878 }
5879 break;
5880 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005881 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005882 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005883 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005884 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005885 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005886 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005887 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005888 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5889 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005890 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005891 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005892 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005893 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005894 local_method->SetMethodIndex(actual_count);
5895 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005896 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005897 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005898 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005899 return false;
5900 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005901 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005902 CHECK_LE(actual_count, max_count);
5903 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005904 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005905 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005906 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005907 return false;
5908 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005909 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005910 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005911 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005912 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005913 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005914 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5915 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005916 return false;
5917 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005918 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005919 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005920 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005921 return false;
5922 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005923 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005924 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5925 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005926 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005927 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005928 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005929 }
5930 return true;
5931}
5932
Alex Light9139e002015-10-09 15:59:48 -07005933// Determine if the given iface has any subinterface in the given list that declares the method
5934// specified by 'target'.
5935//
5936// Arguments
5937// - self: The thread we are running on
5938// - target: A comparator that will match any method that overrides the method we are checking for
5939// - iftable: The iftable we are searching for an overriding method on.
5940// - ifstart: The index of the interface we are checking to see if anything overrides
5941// - iface: The interface we are checking to see if anything overrides.
5942// - image_pointer_size:
5943// The image pointer size.
5944//
5945// Returns
5946// - True: There is some method that matches the target comparator defined in an interface that
5947// is a subtype of iface.
5948// - False: There is no method that matches the target comparator in any interface that is a subtype
5949// of iface.
5950static bool ContainsOverridingMethodOf(Thread* self,
5951 MethodNameAndSignatureComparator& target,
5952 Handle<mirror::IfTable> iftable,
5953 size_t ifstart,
5954 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005955 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005956 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005957 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005958 DCHECK(iface != nullptr);
5959 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07005960 DCHECK_GE(ifstart, 0u);
5961 DCHECK_LT(ifstart, iftable->Count());
5962 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5963 DCHECK(iface->IsInterface());
5964
5965 size_t iftable_count = iftable->Count();
5966 StackHandleScope<1> hs(self);
5967 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5968 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5969 // Skip ifstart since our current interface obviously cannot override itself.
5970 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005971 // Iterate through every method on this interface. The order does not matter.
5972 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07005973 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08005974 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07005975 // Check if the i'th interface is a subtype of this one.
5976 if (iface->IsAssignableFrom(current_iface.Get())) {
5977 return true;
5978 }
5979 break;
5980 }
5981 }
5982 }
5983 return false;
5984}
5985
Alex Lighteb7c1442015-08-31 13:17:42 -07005986// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07005987// out_default_method and returns kDefaultFound on success. If no default method was found return
5988// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
5989// default_method conflict) it will return kDefaultConflict.
5990ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
5991 Thread* self,
5992 ArtMethod* target_method,
5993 Handle<mirror::Class> klass,
5994 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07005995 DCHECK(self != nullptr);
5996 DCHECK(target_method != nullptr);
5997 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07005998
5999 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006000
6001 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6002 // table. This lets us walk the table backwards when searching for default methods. The first one
6003 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6004 // track of it and then continue checking all other interfaces, since we need to throw an error if
6005 // we encounter conflicting default method implementations (one is not a subtype of the other).
6006 //
6007 // The order of unrelated interfaces does not matter and is not defined.
6008 size_t iftable_count = klass->GetIfTableCount();
6009 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006010 // No interfaces. We have already reset out to null so just return kAbstractFound.
6011 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006012 }
6013
Alex Light9139e002015-10-09 15:59:48 -07006014 StackHandleScope<3> hs(self);
6015 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006016 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006017 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006018 MethodNameAndSignatureComparator target_name_comparator(
6019 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6020 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006021 for (size_t k = iftable_count; k != 0; ) {
6022 --k;
6023
Alex Lighteb7c1442015-08-31 13:17:42 -07006024 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006025
6026 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006027 // Iterate through every declared method on this interface. The order does not matter.
6028 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6029 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006030 // Skip abstract methods and methods with different names.
6031 if (current_method->IsAbstract() ||
6032 !target_name_comparator.HasSameNameAndSignature(
6033 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6034 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006035 } else if (!current_method->IsPublic()) {
6036 // The verifier should have caught the non-public method for dex version 37. Just warn and
6037 // skip it since this is from before default-methods so we don't really need to care that it
6038 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006039 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6040 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006041 << "This will be a fatal error in subsequent versions of android. "
6042 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006043 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006044 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006045 // We have multiple default impls of the same method. This is a potential default conflict.
6046 // We need to check if this possibly conflicting method is either a superclass of the chosen
6047 // default implementation or is overridden by a non-default interface method. In either case
6048 // there is no conflict.
6049 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6050 !ContainsOverridingMethodOf(self,
6051 target_name_comparator,
6052 iftable,
6053 k,
6054 iface,
6055 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006056 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006057 << current_method->PrettyMethod() << " and "
6058 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6059 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006060 *out_default_method = nullptr;
6061 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006062 } else {
6063 break; // Continue checking at the next interface.
6064 }
6065 } else {
Alex Light9139e002015-10-09 15:59:48 -07006066 // chosen_iface == null
6067 if (!ContainsOverridingMethodOf(self,
6068 target_name_comparator,
6069 iftable,
6070 k,
6071 iface,
6072 image_pointer_size_)) {
6073 // Don't set this as the chosen interface if something else is overriding it (because that
6074 // other interface would be potentially chosen instead if it was default). If the other
6075 // interface was abstract then we wouldn't select this interface as chosen anyway since
6076 // the abstract method masks it.
6077 *out_default_method = current_method;
6078 chosen_iface.Assign(iface.Get());
6079 // We should now finish traversing the graph to find if we have default methods that
6080 // conflict.
6081 } else {
David Sehr709b0702016-10-13 09:12:37 -07006082 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6083 << "' was "
6084 << "skipped because it was overridden by an abstract method in a "
6085 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006086 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006087 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006088 break;
6089 }
6090 }
Alex Light9139e002015-10-09 15:59:48 -07006091 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006092 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6093 << "' selected "
6094 << "as the implementation for '" << target_method->PrettyMethod()
6095 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006096 return DefaultMethodSearchResult::kDefaultFound;
6097 } else {
6098 return DefaultMethodSearchResult::kAbstractFound;
6099 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006100}
6101
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006102ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006103 ArtMethod* conflict_method,
6104 ArtMethod* interface_method,
6105 ArtMethod* method,
6106 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006107 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006108 Runtime* const runtime = Runtime::Current();
6109 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6110 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6111
6112 // Create a new entry if the existing one is the shared conflict method.
6113 ArtMethod* new_conflict_method = new_entry
6114 ? runtime->CreateImtConflictMethod(linear_alloc)
6115 : conflict_method;
6116
6117 // Allocate a new table. Note that we will leak this table at the next conflict,
6118 // but that's a tradeoff compared to making the table fixed size.
6119 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006120 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6121 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006122 if (data == nullptr) {
6123 LOG(ERROR) << "Failed to allocate conflict table";
6124 return conflict_method;
6125 }
6126 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6127 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006128 method,
6129 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006130
6131 // Do a fence to ensure threads see the data in the table before it is assigned
6132 // to the conflict method.
6133 // Note that there is a race in the presence of multiple threads and we may leak
6134 // memory from the LinearAlloc, but that's a tradeoff compared to using
6135 // atomic operations.
6136 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006137 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006138 return new_conflict_method;
6139}
6140
Vladimir Marko921094a2017-01-12 18:37:06 +00006141bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6142 Handle<mirror::Class> klass,
6143 Handle<mirror::IfTable> iftable) {
6144 DCHECK(!klass->IsInterface());
6145 const bool has_superclass = klass->HasSuperClass();
6146 const bool extend_super_iftable = has_superclass;
6147 const size_t ifcount = klass->GetIfTableCount();
6148 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6149 for (size_t i = 0; i < ifcount; ++i) {
6150 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6151 if (num_methods > 0) {
6152 const bool is_super = i < super_ifcount;
6153 // This is an interface implemented by a super-class. Therefore we can just copy the method
6154 // array from the superclass.
6155 const bool super_interface = is_super && extend_super_iftable;
6156 ObjPtr<mirror::PointerArray> method_array;
6157 if (super_interface) {
6158 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6159 DCHECK(if_table != nullptr);
6160 DCHECK(if_table->GetMethodArray(i) != nullptr);
6161 // If we are working on a super interface, try extending the existing method array.
6162 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6163 } else {
6164 method_array = AllocPointerArray(self, num_methods);
6165 }
6166 if (UNLIKELY(method_array == nullptr)) {
6167 self->AssertPendingOOMException();
6168 return false;
6169 }
6170 iftable->SetMethodArray(i, method_array);
6171 }
6172 }
6173 return true;
6174}
6175
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006176void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6177 ArtMethod* imt_conflict_method,
6178 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006179 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006180 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006181 // Place method in imt if entry is empty, place conflict otherwise.
6182 if (*imt_ref == unimplemented_method) {
6183 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006184 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006185 // If we are not a conflict and we have the same signature and name as the imt
6186 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006187 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6188 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006189 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006190 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006191 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006192 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006193 *imt_ref = current_method;
6194 } else {
Alex Light9139e002015-10-09 15:59:48 -07006195 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006196 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006197 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006198 } else {
6199 // Place the default conflict method. Note that there may be an existing conflict
6200 // method in the IMT, but it could be one tailored to the super class, with a
6201 // specific ImtConflictTable.
6202 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006203 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006204 }
6205}
6206
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006207void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006208 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6209 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006210 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006211 Runtime* const runtime = Runtime::Current();
6212 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6213 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006214 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006215 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006216 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006217 FillIMTFromIfTable(klass->GetIfTable(),
6218 unimplemented_method,
6219 conflict_method,
6220 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006221 /*create_conflict_tables*/true,
6222 /*ignore_copied_methods*/false,
6223 &new_conflict,
6224 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006225 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006226 if (!klass->ShouldHaveImt()) {
6227 return;
6228 }
6229 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6230 // we can just use the same pointer.
6231 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006232 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006233 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6234 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6235 bool same = true;
6236 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6237 ArtMethod* method = imt_data[i];
6238 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6239 if (method != super_method) {
6240 bool is_conflict_table = method->IsRuntimeMethod() &&
6241 method != unimplemented_method &&
6242 method != conflict_method;
6243 // Verify conflict contents.
6244 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6245 super_method != unimplemented_method &&
6246 super_method != conflict_method;
6247 if (!is_conflict_table || !super_conflict_table) {
6248 same = false;
6249 } else {
6250 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6251 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6252 same = same && table1->Equals(table2, image_pointer_size_);
6253 }
6254 }
6255 }
6256 if (same) {
6257 imt = super_imt;
6258 }
6259 }
6260 if (imt == nullptr) {
6261 imt = klass->GetImt(image_pointer_size_);
6262 DCHECK(imt != nullptr);
6263 imt->Populate(imt_data, image_pointer_size_);
6264 } else {
6265 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006266 }
6267}
6268
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006269ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6270 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006271 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006272 void* data = linear_alloc->Alloc(Thread::Current(),
6273 ImtConflictTable::ComputeSize(count,
6274 image_pointer_size));
6275 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6276}
6277
6278ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6279 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6280}
6281
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006282void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006283 ArtMethod* unimplemented_method,
6284 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006285 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006286 bool create_conflict_tables,
6287 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006288 /*out*/bool* new_conflict,
6289 /*out*/ArtMethod** imt) {
6290 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006291 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006292 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006293 const size_t num_virtuals = interface->NumVirtualMethods();
6294 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6295 // Virtual methods can be larger than the if table methods if there are default methods.
6296 DCHECK_GE(num_virtuals, method_array_count);
6297 if (kIsDebugBuild) {
6298 if (klass->IsInterface()) {
6299 DCHECK_EQ(method_array_count, 0u);
6300 } else {
6301 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6302 }
6303 }
6304 if (method_array_count == 0) {
6305 continue;
6306 }
6307 auto* method_array = if_table->GetMethodArray(i);
6308 for (size_t j = 0; j < method_array_count; ++j) {
6309 ArtMethod* implementation_method =
6310 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6311 if (ignore_copied_methods && implementation_method->IsCopied()) {
6312 continue;
6313 }
6314 DCHECK(implementation_method != nullptr);
6315 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6316 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6317 // or interface methods in the IMT here they will not create extra conflicts since we compare
6318 // names and signatures in SetIMTRef.
6319 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006320 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006321
6322 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6323 // the same implementation method, keep track of this to avoid creating a conflict table in
6324 // this case.
6325
6326 // Conflict table size for each IMT slot.
6327 ++conflict_counts[imt_index];
6328
6329 SetIMTRef(unimplemented_method,
6330 imt_conflict_method,
6331 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006332 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006333 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006334 }
6335 }
6336
6337 if (create_conflict_tables) {
6338 // Create the conflict tables.
6339 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006340 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006341 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006342 if (imt[i] == imt_conflict_method) {
6343 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6344 if (new_table != nullptr) {
6345 ArtMethod* new_conflict_method =
6346 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6347 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6348 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006349 } else {
6350 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006351 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006352 }
6353 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006354 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006355 }
6356 }
6357
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006358 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006359 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006360 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6361 // Virtual methods can be larger than the if table methods if there are default methods.
6362 if (method_array_count == 0) {
6363 continue;
6364 }
6365 auto* method_array = if_table->GetMethodArray(i);
6366 for (size_t j = 0; j < method_array_count; ++j) {
6367 ArtMethod* implementation_method =
6368 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6369 if (ignore_copied_methods && implementation_method->IsCopied()) {
6370 continue;
6371 }
6372 DCHECK(implementation_method != nullptr);
6373 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006374 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006375 if (!imt[imt_index]->IsRuntimeMethod() ||
6376 imt[imt_index] == unimplemented_method ||
6377 imt[imt_index] == imt_conflict_method) {
6378 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006379 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006380 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6381 const size_t num_entries = table->NumEntries(image_pointer_size_);
6382 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6383 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006384 }
6385 }
6386 }
6387}
6388
Alex Lighteb7c1442015-08-31 13:17:42 -07006389// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6390// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006391static bool NotSubinterfaceOfAny(
6392 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6393 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006394 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006395 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006396 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006397 for (ObjPtr<mirror::Class> c : classes) {
6398 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006399 return false;
6400 }
6401 }
6402 return true;
6403}
6404
6405// Fills in and flattens the interface inheritance hierarchy.
6406//
6407// By the end of this function all interfaces in the transitive closure of to_process are added to
6408// the iftable and every interface precedes all of its sub-interfaces in this list.
6409//
6410// all I, J: Interface | I <: J implies J precedes I
6411//
6412// (note A <: B means that A is a subtype of B)
6413//
6414// This returns the total number of items in the iftable. The iftable might be resized down after
6415// this call.
6416//
6417// We order this backwards so that we do not need to reorder superclass interfaces when new
6418// interfaces are added in subclass's interface tables.
6419//
6420// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6421// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6422// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6423// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006424static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006425 size_t super_ifcount,
6426 std::vector<mirror::Class*> to_process)
6427 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006428 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006429 // This is the set of all class's already in the iftable. Used to make checking if a class has
6430 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006431 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006432 // The first super_ifcount elements are from the superclass. We note that they are already added.
6433 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006434 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006435 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6436 classes_in_iftable.insert(iface);
6437 }
6438 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006439 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006440 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6441 // At this point in the loop current-iface-list has the invariant that:
6442 // for every pair of interfaces I,J within it:
6443 // if index_of(I) < index_of(J) then I is not a subtype of J
6444
6445 // If we have already seen this element then all of its super-interfaces must already be in the
6446 // current-iface-list so we can skip adding it.
6447 if (!ContainsElement(classes_in_iftable, interface)) {
6448 // We haven't seen this interface so add all of its super-interfaces onto the
6449 // current-iface-list, skipping those already on it.
6450 int32_t ifcount = interface->GetIfTableCount();
6451 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006452 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 if (!ContainsElement(classes_in_iftable, super_interface)) {
6454 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6455 classes_in_iftable.insert(super_interface);
6456 iftable->SetInterface(filled_ifcount, super_interface);
6457 filled_ifcount++;
6458 }
6459 }
6460 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6461 // Place this interface onto the current-iface-list after all of its super-interfaces.
6462 classes_in_iftable.insert(interface);
6463 iftable->SetInterface(filled_ifcount, interface);
6464 filled_ifcount++;
6465 } else if (kIsDebugBuild) {
6466 // Check all super-interfaces are already in the list.
6467 int32_t ifcount = interface->GetIfTableCount();
6468 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006469 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006470 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006471 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6472 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006473 }
6474 }
6475 }
6476 if (kIsDebugBuild) {
6477 // Check that the iftable is ordered correctly.
6478 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006479 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006480 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006481 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006482 // !(if_a <: if_b)
6483 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006484 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6485 << ") extends "
6486 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006487 << "interface list.";
6488 }
6489 }
6490 }
6491 return filled_ifcount;
6492}
6493
6494bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6495 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6496 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006497 const bool has_superclass = klass->HasSuperClass();
6498 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006499 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006500 const size_t num_interfaces =
6501 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006502 if (num_interfaces == 0) {
6503 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006504 if (LIKELY(has_superclass)) {
6505 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6506 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006507 // Class implements no interfaces.
6508 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006509 return true;
6510 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006511 // Class implements same interfaces as parent, are any of these not marker interfaces?
6512 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006513 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006514 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006515 if (super_iftable->GetMethodArrayCount(i) > 0) {
6516 has_non_marker_interface = true;
6517 break;
6518 }
6519 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006520 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006521 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006522 klass->SetIfTable(super_iftable);
6523 return true;
6524 }
6525 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006526 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006527 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006528 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006529 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006530 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006531 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006532 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006533 if (UNLIKELY(!interface->IsInterface())) {
6534 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006535 ThrowIncompatibleClassChangeError(klass.Get(),
6536 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006537 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006538 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6539 return false;
6540 }
6541 ifcount += interface->GetIfTableCount();
6542 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006543 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006544 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006545 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006546 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006547 return false;
6548 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006549 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006550 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006551 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006552 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006553 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006554 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006555 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006556 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006557
6558 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6559 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6560 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006561 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006562
6563 size_t new_ifcount;
6564 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006565 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006566 std::vector<mirror::Class*> to_add;
6567 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006568 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006569 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006570 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006571 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006572
6573 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006574 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006575
Ian Rogers7b078e82014-09-10 14:44:24 -07006576 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006577
Ian Rogersb52b01a2012-01-12 17:01:38 -08006578 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006579 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006580 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006581 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006582 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006583 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006584 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006585 return false;
6586 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006587 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006588 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006589 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006590 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006591 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006592 return true;
6593}
6594
Alex Light1f3925d2016-09-07 12:04:20 -07006595// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6596// of methods must be unique.
6597static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6598 return nullptr;
6599}
6600
6601template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006602static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006603 const ScopedArenaVector<ArtMethod*>& list,
6604 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006605 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006606 for (ArtMethod* method : list) {
6607 if (cmp.HasSameNameAndSignature(method)) {
6608 return method;
6609 }
6610 }
Alex Light1f3925d2016-09-07 12:04:20 -07006611 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006612}
6613
Alex Light1f3925d2016-09-07 12:04:20 -07006614// Check that all vtable entries are present in this class's virtuals or are the same as a
6615// superclasses vtable entry.
6616static void CheckClassOwnsVTableEntries(Thread* self,
6617 Handle<mirror::Class> klass,
6618 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006619 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006620 StackHandleScope<2> hs(self);
6621 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006622 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006623 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006624 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006625 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6626 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6627 CHECK(m != nullptr);
6628
Alex Lighta41a30782017-03-29 11:33:19 -07006629 if (m->GetMethodIndexDuringLinking() != i) {
6630 LOG(WARNING) << m->PrettyMethod()
6631 << " has an unexpected method index for its spot in the vtable for class"
6632 << klass->PrettyClass();
6633 }
Alex Lighte64300b2015-12-15 15:02:47 -08006634 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6635 auto is_same_method = [m] (const ArtMethod& meth) {
6636 return &meth == m;
6637 };
Alex Light3f980532017-03-17 15:10:32 -07006638 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6639 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6640 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6641 << klass->PrettyClass() << " or any of its superclasses!";
6642 }
Alex Lighte64300b2015-12-15 15:02:47 -08006643 }
6644}
6645
Alex Light1f3925d2016-09-07 12:04:20 -07006646// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6647// method is overridden in a subclass.
6648static void CheckVTableHasNoDuplicates(Thread* self,
6649 Handle<mirror::Class> klass,
6650 PointerSize pointer_size)
6651 REQUIRES_SHARED(Locks::mutator_lock_) {
6652 StackHandleScope<1> hs(self);
6653 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6654 int32_t num_entries = vtable->GetLength();
6655 for (int32_t i = 0; i < num_entries; i++) {
6656 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6657 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6658 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6659 vtable_entry->GetAccessFlags())) {
6660 continue;
6661 }
6662 MethodNameAndSignatureComparator name_comparator(
6663 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006664 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006665 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006666 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6667 other_entry->GetAccessFlags())) {
6668 continue;
6669 }
Alex Light3f980532017-03-17 15:10:32 -07006670 if (vtable_entry == other_entry ||
6671 name_comparator.HasSameNameAndSignature(
6672 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6673 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6674 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6675 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6676 << other_entry->PrettyMethod() << " (0x" << std::hex
6677 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6678 }
Alex Light1f3925d2016-09-07 12:04:20 -07006679 }
6680 }
6681}
6682
6683static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6684 REQUIRES_SHARED(Locks::mutator_lock_) {
6685 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6686 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6687}
6688
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006689void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6690 ArtMethod* unimplemented_method,
6691 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006692 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006693 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006694 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006695 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006696 if (super_class->ShouldHaveImt()) {
6697 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6698 for (size_t i = 0; i < ImTable::kSize; ++i) {
6699 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006700 }
6701 } else {
6702 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006703 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006704 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006705 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006706 FillIMTFromIfTable(if_table,
6707 unimplemented_method,
6708 imt_conflict_method,
6709 klass.Get(),
6710 /*create_conflict_table*/false,
6711 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006712 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006713 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006714 }
6715 }
6716}
6717
Vladimir Marko921094a2017-01-12 18:37:06 +00006718class ClassLinker::LinkInterfaceMethodsHelper {
6719 public:
6720 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6721 Handle<mirror::Class> klass,
6722 Thread* self,
6723 Runtime* runtime)
6724 : class_linker_(class_linker),
6725 klass_(klass),
6726 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6727 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6728 self_(self),
6729 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6730 allocator_(&stack_),
6731 default_conflict_methods_(allocator_.Adapter()),
6732 overriding_default_conflict_methods_(allocator_.Adapter()),
6733 miranda_methods_(allocator_.Adapter()),
6734 default_methods_(allocator_.Adapter()),
6735 overriding_default_methods_(allocator_.Adapter()),
6736 move_table_(allocator_.Adapter()) {
6737 }
6738
6739 ArtMethod* FindMethod(ArtMethod* interface_method,
6740 MethodNameAndSignatureComparator& interface_name_comparator,
6741 ArtMethod* vtable_impl)
6742 REQUIRES_SHARED(Locks::mutator_lock_);
6743
6744 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6745 MethodNameAndSignatureComparator& interface_name_comparator)
6746 REQUIRES_SHARED(Locks::mutator_lock_);
6747
6748 bool HasNewVirtuals() const {
6749 return !(miranda_methods_.empty() &&
6750 default_methods_.empty() &&
6751 overriding_default_methods_.empty() &&
6752 overriding_default_conflict_methods_.empty() &&
6753 default_conflict_methods_.empty());
6754 }
6755
6756 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6757
6758 ObjPtr<mirror::PointerArray> UpdateVtable(
6759 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6760 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6761
6762 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6763
6764 void UpdateIMT(ArtMethod** out_imt);
6765
6766 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6767 if (kIsDebugBuild) {
6768 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6769 // Check that there are no stale methods are in the dex cache array.
6770 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6771 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006772 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6773 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006774 CHECK(move_table_.find(m) == move_table_.end() ||
6775 // The original versions of copied methods will still be present so allow those too.
6776 // Note that if the first check passes this might fail to GetDeclaringClass().
6777 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6778 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6779 [m] (ArtMethod& meth) {
6780 return &meth == m;
6781 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6782 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6783 }
6784 }
6785 }
6786
6787 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6788 LengthPrefixedArray<ArtMethod>* methods) {
6789 if (kIsDebugBuild) {
6790 CHECK(methods != nullptr);
6791 // Put some random garbage in old methods to help find stale pointers.
6792 if (methods != old_methods && old_methods != nullptr) {
6793 // Need to make sure the GC is not running since it could be scanning the methods we are
6794 // about to overwrite.
6795 ScopedThreadStateChange tsc(self_, kSuspended);
6796 gc::ScopedGCCriticalSection gcs(self_,
6797 gc::kGcCauseClassLinker,
6798 gc::kCollectorTypeClassLinker);
6799 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6800 method_size_,
6801 method_alignment_);
6802 memset(old_methods, 0xFEu, old_size);
6803 }
6804 }
6805 }
6806
6807 private:
6808 size_t NumberOfNewVirtuals() const {
6809 return miranda_methods_.size() +
6810 default_methods_.size() +
6811 overriding_default_conflict_methods_.size() +
6812 overriding_default_methods_.size() +
6813 default_conflict_methods_.size();
6814 }
6815
6816 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6817 return !klass_->IsInterface();
6818 }
6819
6820 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6821 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6822 << "Interfaces should only have default-conflict methods appended to them.";
6823 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6824 << miranda_methods_.size()
6825 << " default_methods=" << default_methods_.size()
6826 << " overriding_default_methods=" << overriding_default_methods_.size()
6827 << " default_conflict_methods=" << default_conflict_methods_.size()
6828 << " overriding_default_conflict_methods="
6829 << overriding_default_conflict_methods_.size();
6830 }
6831
6832 ClassLinker* class_linker_;
6833 Handle<mirror::Class> klass_;
6834 size_t method_alignment_;
6835 size_t method_size_;
6836 Thread* const self_;
6837
6838 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6839 // the virtual methods array.
6840 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6841 // during cross compilation.
6842 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6843 ArenaStack stack_;
6844 ScopedArenaAllocator allocator_;
6845
6846 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6847 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6848 ScopedArenaVector<ArtMethod*> miranda_methods_;
6849 ScopedArenaVector<ArtMethod*> default_methods_;
6850 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6851
6852 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6853};
6854
6855ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6856 ArtMethod* interface_method,
6857 MethodNameAndSignatureComparator& interface_name_comparator,
6858 ArtMethod* vtable_impl) {
6859 ArtMethod* current_method = nullptr;
6860 switch (class_linker_->FindDefaultMethodImplementation(self_,
6861 interface_method,
6862 klass_,
6863 /*out*/&current_method)) {
6864 case DefaultMethodSearchResult::kDefaultConflict: {
6865 // Default method conflict.
6866 DCHECK(current_method == nullptr);
6867 ArtMethod* default_conflict_method = nullptr;
6868 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6869 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6870 default_conflict_method = vtable_impl;
6871 } else {
6872 // See if we already have a conflict method for this method.
6873 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6874 interface_name_comparator,
6875 default_conflict_methods_,
6876 overriding_default_conflict_methods_);
6877 if (LIKELY(preexisting_conflict != nullptr)) {
6878 // We already have another conflict we can reuse.
6879 default_conflict_method = preexisting_conflict;
6880 } else {
6881 // Note that we do this even if we are an interface since we need to create this and
6882 // cannot reuse another classes.
6883 // Create a new conflict method for this to use.
6884 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6885 new(default_conflict_method) ArtMethod(interface_method,
6886 class_linker_->GetImagePointerSize());
6887 if (vtable_impl == nullptr) {
6888 // Save the conflict method. We need to add it to the vtable.
6889 default_conflict_methods_.push_back(default_conflict_method);
6890 } else {
6891 // Save the conflict method but it is already in the vtable.
6892 overriding_default_conflict_methods_.push_back(default_conflict_method);
6893 }
6894 }
6895 }
6896 current_method = default_conflict_method;
6897 break;
6898 } // case kDefaultConflict
6899 case DefaultMethodSearchResult::kDefaultFound: {
6900 DCHECK(current_method != nullptr);
6901 // Found a default method.
6902 if (vtable_impl != nullptr &&
6903 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6904 // We found a default method but it was the same one we already have from our
6905 // superclass. Don't bother adding it to our vtable again.
6906 current_method = vtable_impl;
6907 } else if (LIKELY(FillTables())) {
6908 // Interfaces don't need to copy default methods since they don't have vtables.
6909 // Only record this default method if it is new to save space.
6910 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6911 // would make lookup for interface super much faster. (We would only need to scan
6912 // the iftable to find if there is a NSME or AME.)
6913 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6914 default_methods_,
6915 overriding_default_methods_);
6916 if (old == nullptr) {
6917 // We found a default method implementation and there were no conflicts.
6918 if (vtable_impl == nullptr) {
6919 // Save the default method. We need to add it to the vtable.
6920 default_methods_.push_back(current_method);
6921 } else {
6922 // Save the default method but it is already in the vtable.
6923 overriding_default_methods_.push_back(current_method);
6924 }
6925 } else {
6926 CHECK(old == current_method) << "Multiple default implementations selected!";
6927 }
6928 }
6929 break;
6930 } // case kDefaultFound
6931 case DefaultMethodSearchResult::kAbstractFound: {
6932 DCHECK(current_method == nullptr);
6933 // Abstract method masks all defaults.
6934 if (vtable_impl != nullptr &&
6935 vtable_impl->IsAbstract() &&
6936 !vtable_impl->IsDefaultConflicting()) {
6937 // We need to make this an abstract method but the version in the vtable already is so
6938 // don't do anything.
6939 current_method = vtable_impl;
6940 }
6941 break;
6942 } // case kAbstractFound
6943 }
6944 return current_method;
6945}
6946
6947ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
6948 ArtMethod* interface_method,
6949 MethodNameAndSignatureComparator& interface_name_comparator) {
6950 // Find out if there is already a miranda method we can use.
6951 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6952 miranda_methods_);
6953 if (miranda_method == nullptr) {
6954 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
6955 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6956 CHECK(miranda_method != nullptr);
6957 // Point the interface table at a phantom slot.
6958 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
6959 miranda_methods_.push_back(miranda_method);
6960 }
6961 return miranda_method;
6962}
6963
6964void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
6965 LogNewVirtuals();
6966
6967 const size_t old_method_count = klass_->NumMethods();
6968 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
6969 DCHECK_NE(old_method_count, new_method_count);
6970
6971 // Attempt to realloc to save RAM if possible.
6972 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
6973 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
6974 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6975 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6976 // CopyFrom has internal read barriers.
6977 //
6978 // TODO We should maybe move some of this into mirror::Class or at least into another method.
6979 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6980 method_size_,
6981 method_alignment_);
6982 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
6983 method_size_,
6984 method_alignment_);
6985 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
6986 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01006987 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00006988 self_, old_methods, old_methods_ptr_size, new_size));
6989 CHECK(methods != nullptr); // Native allocation failure aborts.
6990
6991 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6992 if (methods != old_methods) {
6993 // Maps from heap allocated miranda method to linear alloc miranda method.
6994 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
6995 // Copy over the old methods.
6996 for (auto& m : klass_->GetMethods(pointer_size)) {
6997 move_table_.emplace(&m, &*out);
6998 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
6999 // barriers when it copies.
7000 out->CopyFrom(&m, pointer_size);
7001 ++out;
7002 }
7003 }
7004 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7005 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7006 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007007 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7008 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007009 ArtMethod& new_method = *out;
7010 new_method.CopyFrom(mir_method, pointer_size);
7011 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7012 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7013 << "Miranda method should be abstract!";
7014 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007015 // Update the entry in the method array, as the array will be used for future lookups,
7016 // where thread suspension is allowed.
7017 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7018 // would not see them.
7019 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007020 ++out;
7021 }
7022 // We need to copy the default methods into our own method table since the runtime requires that
7023 // every method on a class's vtable be in that respective class's virtual method table.
7024 // NOTE This means that two classes might have the same implementation of a method from the same
7025 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7026 // default method found on a class with one found on the declaring interface directly and must
7027 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007028 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7029 &overriding_default_methods_}) {
7030 for (size_t i = 0; i < methods_vec->size(); ++i) {
7031 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007032 ArtMethod& new_method = *out;
7033 new_method.CopyFrom(def_method, pointer_size);
7034 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7035 // verified yet it shouldn't have methods that are skipping access checks.
7036 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7037 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007038 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007039 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7040 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7041 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7042 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007043 // Update the entry in the method array, as the array will be used for future lookups,
7044 // where thread suspension is allowed.
7045 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7046 // would not see them.
7047 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007048 ++out;
7049 }
7050 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007051 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7052 &overriding_default_conflict_methods_}) {
7053 for (size_t i = 0; i < methods_vec->size(); ++i) {
7054 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007055 ArtMethod& new_method = *out;
7056 new_method.CopyFrom(conf_method, pointer_size);
7057 // This is a type of default method (there are default method impls, just a conflict) so
7058 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7059 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7060 // methods that are skipping access checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007061 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007062 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7063 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7064 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7065 DCHECK(new_method.IsDefaultConflicting());
7066 // The actual method might or might not be marked abstract since we just copied it from a
7067 // (possibly default) interface method. We need to set it entry point to be the bridge so
7068 // that the compiler will not invoke the implementation of whatever method we copied from.
7069 EnsureThrowsInvocationError(class_linker_, &new_method);
7070 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007071 // Update the entry in the method array, as the array will be used for future lookups,
7072 // where thread suspension is allowed.
7073 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7074 // would not see them.
7075 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007076 ++out;
7077 }
7078 }
7079 methods->SetSize(new_method_count);
7080 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7081}
7082
7083ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7084 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7085 ObjPtr<mirror::PointerArray> old_vtable) {
7086 // Update the vtable to the new method structures. We can skip this for interfaces since they
7087 // do not have vtables.
7088 const size_t old_vtable_count = old_vtable->GetLength();
7089 const size_t new_vtable_count = old_vtable_count +
7090 miranda_methods_.size() +
7091 default_methods_.size() +
7092 default_conflict_methods_.size();
7093
7094 ObjPtr<mirror::PointerArray> vtable =
7095 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7096 if (UNLIKELY(vtable == nullptr)) {
7097 self_->AssertPendingOOMException();
7098 return nullptr;
7099 }
7100
7101 size_t vtable_pos = old_vtable_count;
7102 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7103 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7104 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7105 default_conflict_methods_,
7106 miranda_methods_}) {
7107 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007108 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007109 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7110 // fields are references into the dex file the method was defined in. Since the ArtMethod
7111 // does not store that information it uses declaring_class_->dex_cache_.
7112 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7113 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7114 ++vtable_pos;
7115 }
7116 }
7117 DCHECK_EQ(vtable_pos, new_vtable_count);
7118
7119 // Update old vtable methods. We use the default_translations map to figure out what each
7120 // vtable entry should be updated to, if they need to be at all.
7121 for (size_t i = 0; i < old_vtable_count; ++i) {
7122 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7123 // Try and find what we need to change this method to.
7124 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007125 if (translation_it != default_translations.end()) {
7126 if (translation_it->second.IsInConflict()) {
7127 // Find which conflict method we are to use for this method.
7128 MethodNameAndSignatureComparator old_method_comparator(
7129 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7130 // We only need to look through overriding_default_conflict_methods since this is an
7131 // overridden method we are fixing up here.
7132 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7133 old_method_comparator, overriding_default_conflict_methods_);
7134 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7135 translated_method = new_conflict_method;
7136 } else if (translation_it->second.IsAbstract()) {
7137 // Find which miranda method we are to use for this method.
7138 MethodNameAndSignatureComparator old_method_comparator(
7139 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7140 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7141 miranda_methods_);
7142 DCHECK(miranda_method != nullptr);
7143 translated_method = miranda_method;
7144 } else {
7145 // Normal default method (changed from an older default or abstract interface method).
7146 DCHECK(translation_it->second.IsTranslation());
7147 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007148 auto it = move_table_.find(translated_method);
7149 DCHECK(it != move_table_.end());
7150 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007151 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007152 } else {
7153 auto it = move_table_.find(translated_method);
7154 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007155 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007156
7157 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007158 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007159 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007160 if (kIsDebugBuild) {
7161 auto* methods = klass_->GetMethodsPtr();
7162 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007163 reinterpret_cast<uintptr_t>(translated_method));
7164 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007165 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7166 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007167 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007168 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007169 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007170 }
7171 }
7172 klass_->SetVTable(vtable.Ptr());
7173 return vtable;
7174}
7175
7176void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7177 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7178 const size_t ifcount = klass_->GetIfTableCount();
7179 // Go fix up all the stale iftable pointers.
7180 for (size_t i = 0; i < ifcount; ++i) {
7181 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7182 auto* method_array = iftable->GetMethodArray(i);
7183 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7184 DCHECK(m != nullptr) << klass_->PrettyClass();
7185 auto it = move_table_.find(m);
7186 if (it != move_table_.end()) {
7187 auto* new_m = it->second;
7188 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7189 method_array->SetElementPtrSize(j, new_m, pointer_size);
7190 }
7191 }
7192 }
7193}
7194
7195void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7196 // Fix up IMT next.
7197 for (size_t i = 0; i < ImTable::kSize; ++i) {
7198 auto it = move_table_.find(out_imt[i]);
7199 if (it != move_table_.end()) {
7200 out_imt[i] = it->second;
7201 }
7202 }
7203}
7204
Alex Light705ad492015-09-21 11:36:30 -07007205// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007206bool ClassLinker::LinkInterfaceMethods(
7207 Thread* self,
7208 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007209 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007210 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007211 ArtMethod** out_imt) {
7212 StackHandleScope<3> hs(self);
7213 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007214
7215 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007216 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007217 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007218 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007219 const size_t ifcount = klass->GetIfTableCount();
7220
Vladimir Marko921094a2017-01-12 18:37:06 +00007221 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007222
7223 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7224 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007225 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007226 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007227 const bool extend_super_iftable = has_superclass;
7228 if (has_superclass && fill_tables) {
7229 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007230 unimplemented_method,
7231 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007232 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007233 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007234 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007235 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7236 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007237 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007238 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7239 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007240 }
7241 }
7242
Vladimir Marko921094a2017-01-12 18:37:06 +00007243 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7244
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007245 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007246 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007247 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7248 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7249 // they will already be null. This has the additional benefit that the declarer of a miranda
7250 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007251 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007252 --i;
Alex Light9139e002015-10-09 15:59:48 -07007253 DCHECK_LT(i, ifcount);
7254
Alex Light705ad492015-09-21 11:36:30 -07007255 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007256 if (num_methods > 0) {
7257 StackHandleScope<2> hs2(self);
7258 const bool is_super = i < super_ifcount;
7259 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007260 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7261 // conflict methods. Just set this as nullptr in those cases.
7262 Handle<mirror::PointerArray> method_array(fill_tables
7263 ? hs2.NewHandle(iftable->GetMethodArray(i))
7264 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007265
Alex Lighte64300b2015-12-15 15:02:47 -08007266 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007267 ScopedNullHandle<mirror::PointerArray> null_handle;
7268 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007269 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007270
Alex Light9139e002015-10-09 15:59:48 -07007271 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7272 // and confusing. Default methods should always look through all the superclasses
7273 // because they are the last choice of an implementation. We get around this by looking
7274 // at the super-classes iftable methods (copied into method_array previously) when we are
7275 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007276 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007277 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007278 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007279 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007280 using_virtuals = true;
7281 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7282 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007283 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007284 // For a new interface, however, we need the whole vtable in case a new
7285 // interface method is implemented in the whole superclass.
7286 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007287 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007288 input_vtable_array = vtable;
7289 input_array_length = input_vtable_array->GetLength();
7290 }
Alex Lighte64300b2015-12-15 15:02:47 -08007291
Alex Lighteb7c1442015-08-31 13:17:42 -07007292 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007293 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007294 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007295 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007296 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007297 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007298 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007299 // For each method listed in the interface's method list, find the
7300 // matching method in our class's method list. We want to favor the
7301 // subclass over the superclass, which just requires walking
7302 // back from the end of the vtable. (This only matters if the
7303 // superclass defines a private method and this class redefines
7304 // it -- otherwise it would use the same vtable slot. In .dex files
7305 // those don't end up in the virtual method table, so it shouldn't
7306 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007307 //
7308 // To find defaults we need to do the same but also go over interfaces.
7309 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007310 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007311 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007312 ArtMethod* vtable_method = using_virtuals ?
7313 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007314 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7315 ArtMethod* vtable_method_for_name_comparison =
7316 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007317 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007318 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007319 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007320 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7321 // allocations.
7322 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007323 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007324 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007325 vtable_method->PrettyMethod().c_str(),
7326 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007327 return false;
Alex Light9139e002015-10-09 15:59:48 -07007328 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007329 // We might have a newer, better, default method for this, so we just skip it. If we
7330 // are still using this we will select it again when scanning for default methods. To
7331 // obviate the need to copy the method again we will make a note that we already found
7332 // a default here.
7333 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007334 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007335 break;
7336 } else {
7337 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007338 if (LIKELY(fill_tables)) {
7339 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7340 // Place method in imt if entry is empty, place conflict otherwise.
7341 SetIMTRef(unimplemented_method,
7342 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007343 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007344 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007345 /*out*/imt_ptr);
7346 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007347 break;
7348 }
7349 }
Alex Light9139e002015-10-09 15:59:48 -07007350 }
7351 // Continue on to the next method if we are done.
7352 if (LIKELY(found_impl)) {
7353 continue;
7354 } else if (LIKELY(super_interface)) {
7355 // Don't look for a default implementation when the super-method is implemented directly
7356 // by the class.
7357 //
7358 // See if we can use the superclasses method and skip searching everything else.
7359 // Note: !found_impl && super_interface
7360 CHECK(extend_super_iftable);
7361 // If this is a super_interface method it is possible we shouldn't override it because a
7362 // superclass could have implemented it directly. We get the method the superclass used
7363 // to implement this to know if we can override it with a default method. Doing this is
7364 // safe since we know that the super_iftable is filled in so we can simply pull it from
7365 // there. We don't bother if this is not a super-classes interface since in that case we
7366 // have scanned the entire vtable anyway and would have found it.
7367 // TODO This is rather dirty but it is faster than searching through the entire vtable
7368 // every time.
7369 ArtMethod* supers_method =
7370 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7371 DCHECK(supers_method != nullptr);
7372 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007373 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007374 // The method is not overridable by a default method (i.e. it is directly implemented
7375 // in some class). Therefore move onto the next interface method.
7376 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007377 } else {
7378 // If the super-classes method is override-able by a default method we need to keep
7379 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7380 // 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 -07007381 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7382 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7383 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007384 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007385 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7386 << " and not 'nullptr' or "
7387 << supers_method->PrettyMethod()
7388 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007389 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007390 }
7391 }
7392 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007393 ArtMethod* current_method = helper.FindMethod(interface_method,
7394 interface_name_comparator,
7395 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007396 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007397 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007398 // We could not find an implementation for this method and since it is a brand new
7399 // interface we searched the entire vtable (and all default methods) for an
7400 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007401 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7402 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007403 }
7404
7405 if (current_method != nullptr) {
7406 // We found a default method implementation. Record it in the iftable and IMT.
7407 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7408 SetIMTRef(unimplemented_method,
7409 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007410 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007411 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007412 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007413 }
7414 }
Alex Light705ad492015-09-21 11:36:30 -07007415 } // For each method in interface end.
7416 } // if (num_methods > 0)
7417 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007418 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007419 if (helper.HasNewVirtuals()) {
7420 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7421 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7422 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7423
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007424 // 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 -07007425 // suspension assert.
7426 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007427
Alex Light705ad492015-09-21 11:36:30 -07007428 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007429 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007430 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007431 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007432 return false;
7433 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007434 helper.UpdateIfTable(iftable);
7435 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007436 }
Alex Light705ad492015-09-21 11:36:30 -07007437
Vladimir Marko921094a2017-01-12 18:37:06 +00007438 helper.CheckNoStaleMethodsInDexCache();
7439 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007440 } else {
7441 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007442 }
Alex Light705ad492015-09-21 11:36:30 -07007443 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007444 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007445 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007446 return true;
7447}
7448
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007449bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007450 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007451 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007452}
7453
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007454bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007455 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007456 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007457}
7458
Brian Carlstromdbc05252011-09-09 01:59:59 -07007459struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007460 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007461 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007462 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007463 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007464 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007465 // 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 -07007466 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7467 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007468 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007469 if (type1 == Primitive::kPrimNot) {
7470 // Reference always goes first.
7471 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007472 }
Vladimir Markod5777482014-11-12 17:02:02 +00007473 if (type2 == Primitive::kPrimNot) {
7474 // Reference always goes first.
7475 return false;
7476 }
7477 size_t size1 = Primitive::ComponentSize(type1);
7478 size_t size2 = Primitive::ComponentSize(type2);
7479 if (size1 != size2) {
7480 // Larger primitive types go first.
7481 return size1 > size2;
7482 }
7483 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7484 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007485 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007486 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7487 // by name and for equal names by type id index.
7488 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7489 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007490 }
7491};
7492
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007493bool ClassLinker::LinkFields(Thread* self,
7494 Handle<mirror::Class> klass,
7495 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007496 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007497 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007498 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007499 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7500 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007501
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007502 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007503 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007504 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007505 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007506 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007507 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007508 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007509 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007510 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007511 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007512 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007513 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007514
David Sehr709b0702016-10-13 09:12:37 -07007515 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007516
Brian Carlstromdbc05252011-09-09 01:59:59 -07007517 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007518 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007519 //
7520 // The overall sort order order is:
7521 // 1) All object reference fields, sorted alphabetically.
7522 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7523 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7524 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7525 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7526 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7527 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7528 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7529 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7530 //
7531 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7532 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007533 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007534 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007535 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007536 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007537 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007538 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007539 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7540 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007541
Fred Shih381e4ca2014-08-25 17:24:27 -07007542 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007543 size_t current_field = 0;
7544 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007545 FieldGaps gaps;
7546
Brian Carlstromdbc05252011-09-09 01:59:59 -07007547 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007548 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007549 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007550 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007551 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007552 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007553 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007554 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7555 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007556 MemberOffset old_offset = field_offset;
7557 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7558 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7559 }
Roland Levillain14d90572015-07-16 10:52:26 +01007560 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007561 grouped_and_sorted_fields.pop_front();
7562 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007563 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007564 field_offset = MemberOffset(field_offset.Uint32Value() +
7565 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007566 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007567 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7568 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007569 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7570 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7571 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7572 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007573 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7574 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007575 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007576
Elliott Hughesadb460d2011-10-05 17:02:34 -07007577 // 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 -07007578 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007579 // We know there are no non-reference fields in the Reference classes, and we know
7580 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007581 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007582 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007583 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007584 --num_reference_fields;
7585 }
7586
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007587 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007588 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007589 if (is_static) {
7590 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007591 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007592 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007593 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007594 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007595 if (num_reference_fields == 0 || super_class == nullptr) {
7596 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007597 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007598 if (super_class == nullptr ||
7599 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7600 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007601 }
7602 }
7603 if (kIsDebugBuild) {
7604 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7605 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007606 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007607 while (cur_super != nullptr) {
7608 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7609 cur_super = cur_super->GetSuperClass();
7610 }
7611 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007612 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007613 } else {
7614 // Check that there is at least num_reference_fields other than Object.class.
7615 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007616 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007617 }
7618 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007619 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007620 std::string temp;
7621 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7622 size_t previous_size = klass->GetObjectSize();
7623 if (previous_size != 0) {
7624 // Make sure that we didn't originally have an incorrect size.
7625 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007626 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007627 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007628 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007629 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007630
7631 if (kIsDebugBuild) {
7632 // Make sure that the fields array is ordered by name but all reference
7633 // offsets are at the beginning as far as alignment allows.
7634 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007635 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007636 : klass->GetFirstReferenceInstanceFieldOffset();
7637 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7638 num_reference_fields *
7639 sizeof(mirror::HeapReference<mirror::Object>));
7640 MemberOffset current_ref_offset = start_ref_offset;
7641 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007642 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007643 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007644 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7645 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007646 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007647 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007648 // NOTE: The field names can be the same. This is not possible in the Java language
7649 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007650 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007651 }
7652 Primitive::Type type = field->GetTypeAsPrimitiveType();
7653 bool is_primitive = type != Primitive::kPrimNot;
7654 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7655 strcmp("referent", field->GetName()) == 0) {
7656 is_primitive = true; // We lied above, so we have to expect a lie here.
7657 }
7658 MemberOffset offset = field->GetOffsetDuringLinking();
7659 if (is_primitive) {
7660 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7661 // Shuffled before references.
7662 size_t type_size = Primitive::ComponentSize(type);
7663 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7664 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7665 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7666 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7667 }
7668 } else {
7669 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7670 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7671 sizeof(mirror::HeapReference<mirror::Object>));
7672 }
7673 }
7674 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7675 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007676 return true;
7677}
7678
Vladimir Marko76649e82014-11-10 18:32:59 +00007679// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007680void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007681 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007682 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007683 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007684 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007685 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007686 // Compute reference offsets unless our superclass overflowed.
7687 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7688 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007689 if (num_reference_fields != 0u) {
7690 // All of the fields that contain object references are guaranteed be grouped in memory
7691 // starting at an appropriately aligned address after super class object data.
7692 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7693 sizeof(mirror::HeapReference<mirror::Object>));
7694 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007695 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007696 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007697 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007698 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007699 reference_offsets |= (0xffffffffu << start_bit) &
7700 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007701 }
7702 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007703 }
7704 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007705 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007706}
7707
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007708ObjPtr<mirror::String> ClassLinker::ResolveString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007709 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007710 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007711 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007712 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007713 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007714 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007715 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007716 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07007717 uint32_t utf16_length;
7718 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007719 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007720 if (string != nullptr) {
7721 dex_cache->SetResolvedString(string_idx, string);
7722 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007723 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007724}
7725
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007726ObjPtr<mirror::String> ClassLinker::LookupString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007727 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007728 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007729 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007730 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007731 return resolved;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007732 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007733 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007734 uint32_t utf16_length;
7735 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007736 ObjPtr<mirror::String> string =
7737 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007738 if (string != nullptr) {
7739 dex_cache->SetResolvedString(string_idx, string);
7740 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007741 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007742}
7743
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007744ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
7745 ObjPtr<mirror::DexCache> dex_cache,
7746 ObjPtr<mirror::ClassLoader> class_loader) {
7747 const DexFile& dex_file = *dex_cache->GetDexFile();
7748 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7749 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7750 ObjPtr<mirror::Class> type = nullptr;
7751 if (descriptor[1] == '\0') {
7752 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7753 // for primitive classes that aren't backed by dex files.
7754 type = FindPrimitiveClass(descriptor[0]);
7755 } else {
7756 Thread* const self = Thread::Current();
7757 DCHECK(self != nullptr);
7758 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7759 // Find the class in the loaded classes table.
7760 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
7761 }
7762 if (type != nullptr) {
7763 if (type->IsResolved()) {
7764 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07007765 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007766 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007767 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007768 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007769 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007770}
7771
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007772ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
7773 Handle<mirror::DexCache> dex_cache,
7774 Handle<mirror::ClassLoader> class_loader) {
7775 Thread* self = Thread::Current();
7776 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
7777 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
7778 if (resolved != nullptr) {
7779 // TODO: we used to throw here if resolved's class loader was not the
7780 // boot class loader. This was to permit different classes with the
7781 // same name to be loaded simultaneously by different loaders
7782 dex_cache->SetResolvedType(type_idx, resolved);
7783 } else {
7784 CHECK(self->IsExceptionPending())
7785 << "Expected pending exception for failed resolution of: " << descriptor;
7786 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7787 StackHandleScope<1> hs(self);
7788 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
7789 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
7790 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7791 self->ClearException();
7792 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7793 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007794 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007795 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007796 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007797 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00007798 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007799}
7800
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007801std::string DescribeSpace(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
7802 std::ostringstream oss;
7803 gc::Heap* heap = Runtime::Current()->GetHeap();
7804 gc::space::ContinuousSpace* cs = heap->FindContinuousSpaceFromAddress(klass.Ptr());
7805 if (cs != nullptr) {
7806 if (cs->IsImageSpace()) {
7807 oss << "image;" << cs->GetName() << ";" << cs->AsImageSpace()->GetImageFilename();
7808 } else {
7809 oss << "continuous;" << cs->GetName();
7810 }
7811 } else {
7812 gc::space::DiscontinuousSpace* ds =
7813 heap->FindDiscontinuousSpaceFromObject(klass, /* fail_ok */ true);
7814 if (ds != nullptr) {
7815 oss << "discontinuous;" << ds->GetName();
7816 } else {
7817 oss << "invalid";
7818 }
7819 }
7820 return oss.str();
7821}
7822
7823std::string DescribeLoaders(ObjPtr<mirror::ClassLoader> loader, const char* class_descriptor)
7824 REQUIRES_SHARED(Locks::mutator_lock_) {
7825 std::ostringstream oss;
7826 uint32_t hash = ComputeModifiedUtf8Hash(class_descriptor);
7827 ObjPtr<mirror::Class> path_class_loader =
7828 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_PathClassLoader);
7829 ObjPtr<mirror::Class> dex_class_loader =
7830 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexClassLoader);
7831 ObjPtr<mirror::Class> delegate_last_class_loader =
7832 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DelegateLastClassLoader);
7833
7834 // Print the class loader chain.
7835 bool found_class = false;
7836 const char* loader_separator = "";
7837 if (loader == nullptr) {
7838 oss << "BootClassLoader"; // This would be unexpected.
7839 }
7840 for (; loader != nullptr; loader = loader->GetParent()) {
7841 oss << loader_separator << loader->GetClass()->PrettyDescriptor();
7842 loader_separator = ";";
7843 // If we didn't find the interface yet, try to find it in the current class loader.
7844 if (!found_class) {
7845 ClassTable* table = Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(loader);
7846 ObjPtr<mirror::Class> klass =
7847 (table != nullptr) ? table->Lookup(class_descriptor, hash) : nullptr;
7848 if (klass != nullptr) {
7849 found_class = true;
7850 oss << "[hit:" << DescribeSpace(klass) << "]";
7851 }
7852 }
7853
7854 // For PathClassLoader, DexClassLoader or DelegateLastClassLoader
7855 // also dump the dex file locations.
7856 if (loader->GetClass() == path_class_loader ||
7857 loader->GetClass() == dex_class_loader ||
7858 loader->GetClass() == delegate_last_class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08007859 oss << "(";
7860 ScopedObjectAccessUnchecked soa(Thread::Current());
7861 StackHandleScope<1> hs(soa.Self());
7862 Handle<mirror::ClassLoader> handle(hs.NewHandle(loader));
7863 const char* path_separator = "";
7864 VisitClassLoaderDexFiles(soa,
7865 handle,
7866 [&](const DexFile* dex_file) {
7867 oss << path_separator << dex_file->GetLocation();
7868 path_separator = ":";
7869 return true; // Continue with the next DexFile.
7870 });
7871 oss << ")";
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007872 }
7873 }
7874
7875 return oss.str();
7876}
7877
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007878ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
7879 ObjPtr<mirror::DexCache> dex_cache,
7880 ObjPtr<mirror::ClassLoader> class_loader,
7881 uint32_t method_idx) {
7882 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7883 // functions can optimize the search if the dex_cache is the same as the DexCache
7884 // of the class, with fall-back to name and signature search otherwise.
7885 ArtMethod* resolved = nullptr;
7886 if (klass->IsInterface()) {
7887 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7888 } else {
7889 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7890 }
7891 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7892 if (resolved != nullptr) {
7893 // In case of jmvti, the dex file gets verified before being registered, so first
7894 // check if it's registered before checking class tables.
7895 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007896 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
7897 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007898 << "DexFile referrer: " << dex_file.GetLocation()
7899 << " ClassLoader: " << DescribeLoaders(class_loader, "");
7900 // Be a good citizen and update the dex cache to speed subsequent calls.
7901 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007902 // Disable the following invariant check as the verifier breaks it. b/73760543
7903 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7904 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
7905 // << "Method: " << resolved->PrettyMethod() << ", "
7906 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
7907 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007908 }
7909 return resolved;
7910}
7911
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007912template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00007913ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007914 Handle<mirror::DexCache> dex_cache,
7915 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007916 ArtMethod* referrer,
7917 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007918 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007919 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007920 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007921 PointerSize pointer_size = image_pointer_size_;
7922 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007923 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007924 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7925 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007926 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7927 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007928 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007929 return resolved;
7930 }
Vladimir Marko89011192017-12-11 13:45:05 +00007931 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007932 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007933 ObjPtr<mirror::Class> klass = nullptr;
7934 if (valid_dex_cache_method) {
7935 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7936 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007937 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007938 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007939 // We normaly should not end up here. However the verifier currently doesn't guarantee
7940 // the invariant of having the klass in the class table. b/73760543
7941 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007942 }
Vladimir Markoba118822017-06-12 15:41:56 +01007943 } else {
7944 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007945 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01007946 if (klass == nullptr) {
7947 DCHECK(Thread::Current()->IsExceptionPending());
7948 return nullptr;
7949 }
7950 }
7951
7952 // Check if the invoke type matches the class type.
7953 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
7954 CheckInvokeClassMismatch</* kThrow */ true>(
7955 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007956 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007957 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007958 }
Vladimir Markoba118822017-06-12 15:41:56 +01007959
7960 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007961 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007962 }
Vladimir Markoba118822017-06-12 15:41:56 +01007963
7964 // Note: We can check for IllegalAccessError only if we have a referrer.
7965 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
7966 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
7967 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
7968 if (!referring_class->CheckResolvedMethodAccess(methods_class,
7969 resolved,
7970 dex_cache.Get(),
7971 method_idx,
7972 type)) {
7973 DCHECK(Thread::Current()->IsExceptionPending());
7974 return nullptr;
7975 }
7976 }
7977
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007978 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01007979 if (LIKELY(resolved != nullptr) &&
7980 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
7981 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007982 return resolved;
7983 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007984 // If we had a method, or if we can find one with another lookup type,
7985 // it's an incompatible-class-change error.
7986 if (resolved == nullptr) {
7987 if (klass->IsInterface()) {
7988 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, pointer_size);
7989 } else {
7990 // If there was an interface method with the same signature,
7991 // we would have found it also in the "copied" methods.
7992 DCHECK(klass->FindInterfaceMethod(dex_cache.Get(), method_idx, pointer_size) == nullptr);
7993 }
7994 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007995 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007996 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007997 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007998 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007999 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8000 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008001 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008002 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008003 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008004 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008005 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008006}
8007
Vladimir Marko89011192017-12-11 13:45:05 +00008008ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008009 Handle<mirror::DexCache> dex_cache,
8010 Handle<mirror::ClassLoader> class_loader) {
8011 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008012 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008013 if (resolved != nullptr) {
8014 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008015 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8016 return resolved;
8017 }
8018 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008019 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
8020 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008021 if (klass == nullptr) {
8022 Thread::Current()->AssertPendingException();
8023 return nullptr;
8024 }
8025 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008026 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8027 } else {
8028 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008029 }
8030
8031 return resolved;
8032}
8033
Vladimir Markof44d36c2017-03-14 14:18:46 +00008034ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8035 ObjPtr<mirror::DexCache> dex_cache,
8036 ObjPtr<mirror::ClassLoader> class_loader,
8037 bool is_static) {
8038 const DexFile& dex_file = *dex_cache->GetDexFile();
8039 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8040 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8041 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008042 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008043 }
8044 if (klass == nullptr) {
8045 // The class has not been resolved yet, so the field is also unresolved.
8046 return nullptr;
8047 }
8048 DCHECK(klass->IsResolved());
8049 Thread* self = is_static ? Thread::Current() : nullptr;
8050
8051 // First try to find a field declared directly by `klass` by the field index.
8052 ArtField* resolved_field = is_static
8053 ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8054 : klass->FindInstanceField(dex_cache, field_idx);
8055
8056 if (resolved_field == nullptr) {
8057 // If not found in `klass` by field index, search the class hierarchy using the name and type.
8058 const char* name = dex_file.GetFieldName(field_id);
8059 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8060 resolved_field = is_static
8061 ? mirror::Class::FindStaticField(self, klass, name, type)
8062 : klass->FindInstanceField(name, type);
8063 }
8064
8065 if (resolved_field != nullptr) {
8066 dex_cache->SetResolvedField(field_idx, resolved_field, image_pointer_size_);
8067 }
8068 return resolved_field;
8069}
8070
Vladimir Markoe11dd502017-12-08 14:09:45 +00008071ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008072 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008073 Handle<mirror::ClassLoader> class_loader,
8074 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008075 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008076 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008077 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008078 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008079 return resolved;
8080 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008081 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008082 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008083 Thread* const self = Thread::Current();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008084 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008085 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008086 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008087 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008088 }
8089
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008090 if (is_static) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008091 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008092 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07008093 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008094 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008095
Andreas Gampe58a5af82014-07-31 16:23:49 -07008096 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008097 const char* name = dex_file.GetFieldName(field_id);
8098 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8099 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07008100 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008101 } else {
8102 resolved = klass->FindInstanceField(name, type);
8103 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07008104 if (resolved == nullptr) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008105 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008106 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008107 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008108 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07008109 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008110 return resolved;
8111}
8112
Vladimir Markoe11dd502017-12-08 14:09:45 +00008113ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008114 Handle<mirror::DexCache> dex_cache,
8115 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008116 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008117 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008118 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008119 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008120 return resolved;
8121 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008122 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008123 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008124 Thread* self = Thread::Current();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008125 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008126 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008127 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008128 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008129 }
8130
Vladimir Markof44d36c2017-03-14 14:18:46 +00008131 StringPiece name(dex_file.GetFieldName(field_id));
8132 StringPiece type(dex_file.GetFieldTypeDescriptor(field_id));
Mathieu Chartierf8322842014-05-16 10:59:25 -07008133 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008134 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008135 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008136 } else {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008137 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008138 }
8139 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008140}
8141
Vladimir Markoaf940202017-12-08 15:01:18 +00008142ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8143 Thread* self,
8144 uint32_t proto_idx,
8145 Handle<mirror::DexCache> dex_cache,
8146 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008147 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008148 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008149
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008150 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008151 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008152 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008153 }
8154
Narayan Kamath25352fc2016-08-03 12:46:58 +01008155 StackHandleScope<4> hs(self);
8156
8157 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008158 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008159 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8160 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008161 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008162 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008163 DCHECK(self->IsExceptionPending());
8164 return nullptr;
8165 }
8166
8167 // Then resolve the argument types.
8168 //
8169 // TODO: Is there a better way to figure out the number of method arguments
8170 // other than by looking at the shorty ?
8171 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8172
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008173 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008174 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008175 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8176 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008177 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008178 DCHECK(self->IsExceptionPending());
8179 return nullptr;
8180 }
8181
8182 DexFileParameterIterator it(dex_file, proto_id);
8183 int32_t i = 0;
8184 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8185 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008186 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008187 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008188 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008189 DCHECK(self->IsExceptionPending());
8190 return nullptr;
8191 }
8192
8193 method_params->Set(i++, param_class.Get());
8194 }
8195
8196 DCHECK(!it.HasNext());
8197
8198 Handle<mirror::MethodType> type = hs.NewHandle(
8199 mirror::MethodType::Create(self, return_type, method_params));
8200 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8201
8202 return type.Get();
8203}
8204
Vladimir Markoaf940202017-12-08 15:01:18 +00008205ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
8206 uint32_t proto_idx,
8207 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008208 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008209 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8210 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008211 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008212}
8213
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008214mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8215 Thread* self,
8216 const DexFile::MethodHandleItem& method_handle,
8217 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008218 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008219 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8220 mirror::MethodHandle::Kind kind;
8221 bool is_static;
8222 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008223 switch (handle_type) {
8224 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008225 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008226 is_static = true;
8227 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008228 break;
8229 }
8230 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008231 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008232 is_static = true;
8233 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008234 break;
8235 }
8236 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008237 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008238 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008239 num_params = 2;
8240 break;
8241 }
8242 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008243 kind = mirror::MethodHandle::Kind::kInstanceGet;
8244 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008245 num_params = 1;
8246 break;
8247 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008248 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008249 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008250 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008251 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008252 case DexFile::MethodHandleType::kInvokeInterface:
8253 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008254 }
8255
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008256 ArtField* target_field =
8257 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8258 if (LIKELY(target_field != nullptr)) {
8259 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8260 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8261 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8262 ThrowIllegalAccessErrorField(referring_class, target_field);
8263 return nullptr;
8264 }
8265 } else {
8266 DCHECK(Thread::Current()->IsExceptionPending());
8267 return nullptr;
8268 }
8269
8270 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008271 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8272 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8273 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8274 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008275 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008276 DCHECK(self->IsExceptionPending());
8277 return nullptr;
8278 }
8279
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008280 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008281 Handle<mirror::Class> return_type;
8282 switch (handle_type) {
8283 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008284 method_params->Set(0, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008285 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8286 break;
8287 }
8288 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008289 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008290 break;
8291 }
8292 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008293 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008294 method_params->Set(1, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008295 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8296 break;
8297 }
8298 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008299 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008300 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008301 break;
8302 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008303 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008304 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008305 case DexFile::MethodHandleType::kInvokeConstructor:
8306 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008307 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008308 UNREACHABLE();
8309 }
8310
8311 for (int32_t i = 0; i < num_params; ++i) {
8312 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8313 DCHECK(self->IsExceptionPending());
8314 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008315 }
8316 }
8317
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008318 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008319 DCHECK(self->IsExceptionPending());
8320 return nullptr;
8321 }
8322
8323 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008324 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8325 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008326 DCHECK(self->IsExceptionPending());
8327 return nullptr;
8328 }
Orion Hodson631827d2017-04-10 14:53:47 +01008329
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008330 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8331 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8332}
8333
8334mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8335 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008336 const DexFile::MethodHandleItem& method_handle,
8337 ArtMethod* referrer) {
8338 DexFile::MethodHandleType handle_type =
8339 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8340 mirror::MethodHandle::Kind kind;
8341 uint32_t receiver_count = 0;
8342 ArtMethod* target_method = nullptr;
8343 switch (handle_type) {
8344 case DexFile::MethodHandleType::kStaticPut:
8345 case DexFile::MethodHandleType::kStaticGet:
8346 case DexFile::MethodHandleType::kInstancePut:
8347 case DexFile::MethodHandleType::kInstanceGet:
8348 UNREACHABLE();
8349 case DexFile::MethodHandleType::kInvokeStatic: {
8350 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8351 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008352 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8353 method_handle.field_or_method_idx_,
8354 referrer,
8355 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008356 break;
8357 }
8358 case DexFile::MethodHandleType::kInvokeInstance: {
8359 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8360 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008361 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8362 method_handle.field_or_method_idx_,
8363 referrer,
8364 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008365 break;
8366 }
8367 case DexFile::MethodHandleType::kInvokeConstructor: {
8368 // Constructors are currently implemented as a transform. They
8369 // are special cased later in this method.
8370 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8371 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008372 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8373 method_handle.field_or_method_idx_,
8374 referrer,
8375 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008376 break;
8377 }
8378 case DexFile::MethodHandleType::kInvokeDirect: {
8379 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8380 receiver_count = 1;
8381 StackHandleScope<2> hs(self);
8382 // A constant method handle with type kInvokeDirect can refer to
8383 // a method that is private or to a method in a super class. To
8384 // disambiguate the two options, we resolve the method ignoring
8385 // the invocation type to determine if the method is private. We
8386 // then resolve again specifying the intended invocation type to
8387 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008388 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008389 hs.NewHandle(referrer->GetDexCache()),
8390 hs.NewHandle(referrer->GetClassLoader()));
8391 if (UNLIKELY(target_method == nullptr)) {
8392 break;
8393 }
8394
8395 if (target_method->IsPrivate()) {
8396 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008397 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8398 method_handle.field_or_method_idx_,
8399 referrer,
8400 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008401 } else {
8402 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008403 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8404 method_handle.field_or_method_idx_,
8405 referrer,
8406 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008407 if (UNLIKELY(target_method == nullptr)) {
8408 break;
8409 }
8410 // Find the method specified in the parent in referring class
8411 // so invoke-super invokes the method in the parent of the
8412 // referrer.
8413 target_method =
8414 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8415 kRuntimePointerSize);
8416 }
8417 break;
8418 }
8419 case DexFile::MethodHandleType::kInvokeInterface: {
8420 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8421 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008422 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8423 method_handle.field_or_method_idx_,
8424 referrer,
8425 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008426 break;
8427 }
Orion Hodson631827d2017-04-10 14:53:47 +01008428 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008429
8430 if (UNLIKELY(target_method == nullptr)) {
8431 DCHECK(Thread::Current()->IsExceptionPending());
8432 return nullptr;
8433 }
8434
8435 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8436 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8437 uint32_t access_flags = target_method->GetAccessFlags();
8438 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8439 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8440 return nullptr;
8441 }
8442
8443 // Calculate the number of parameters from the method shorty. We add the
8444 // receiver count (0 or 1) and deduct one for the return value.
8445 uint32_t shorty_length;
8446 target_method->GetShorty(&shorty_length);
8447 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8448
8449 StackHandleScope<7> hs(self);
8450 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8451 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8452 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8453 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8454 if (method_params.Get() == nullptr) {
8455 DCHECK(self->IsExceptionPending());
8456 return nullptr;
8457 }
8458
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008459 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008460 if (receiver_count != 0) {
8461 // Insert receiver
8462 method_params->Set(index++, target_method->GetDeclaringClass());
8463 }
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008464 DexFileParameterIterator it(*target_method->GetDexFile(), target_method->GetPrototype());
8465 Handle<mirror::DexCache> target_method_dex_cache(hs.NewHandle(target_method->GetDexCache()));
8466 Handle<mirror::ClassLoader> target_method_class_loader(hs.NewHandle(target_method->GetClassLoader()));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008467 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008468 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008469 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008470 ObjPtr<mirror::Class> klass = ResolveType(type_idx,
8471 target_method_dex_cache,
8472 target_method_class_loader);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008473 if (nullptr == klass) {
8474 DCHECK(self->IsExceptionPending());
8475 return nullptr;
8476 }
8477 method_params->Set(index++, klass);
8478 it.Next();
8479 }
8480
Vladimir Markob45528c2017-07-27 14:14:28 +01008481 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008482 if (UNLIKELY(return_type.IsNull())) {
8483 DCHECK(self->IsExceptionPending());
8484 return nullptr;
8485 }
8486
8487 Handle<mirror::MethodType>
8488 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8489 if (UNLIKELY(method_type.IsNull())) {
8490 DCHECK(self->IsExceptionPending());
8491 return nullptr;
8492 }
8493
8494 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8495 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8496 Handle<mirror::MethodHandlesLookup> lookup =
8497 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8498 return lookup->FindConstructor(self, constructor_class, method_type);
8499 }
8500
8501 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8502 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8503}
8504
Vladimir Markoaf940202017-12-08 15:01:18 +00008505ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8506 uint32_t method_handle_idx,
8507 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008508 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008509 const DexFile* const dex_file = referrer->GetDexFile();
8510 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8511 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8512 case DexFile::MethodHandleType::kStaticPut:
8513 case DexFile::MethodHandleType::kStaticGet:
8514 case DexFile::MethodHandleType::kInstancePut:
8515 case DexFile::MethodHandleType::kInstanceGet:
8516 return ResolveMethodHandleForField(self, method_handle, referrer);
8517 case DexFile::MethodHandleType::kInvokeStatic:
8518 case DexFile::MethodHandleType::kInvokeInstance:
8519 case DexFile::MethodHandleType::kInvokeConstructor:
8520 case DexFile::MethodHandleType::kInvokeDirect:
8521 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008522 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008523 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008524}
8525
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008526bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8527 return (entry_point == GetQuickResolutionStub()) ||
8528 (quick_resolution_trampoline_ == entry_point);
8529}
8530
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008531bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8532 return (entry_point == GetQuickToInterpreterBridge()) ||
8533 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8534}
8535
8536bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8537 return (entry_point == GetQuickGenericJniStub()) ||
8538 (quick_generic_jni_trampoline_ == entry_point);
8539}
8540
David Sehra49e0532017-08-25 08:05:29 -07008541bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8542 return entry_point == GetJniDlsymLookupStub();
8543}
8544
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008545const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8546 return GetQuickGenericJniStub();
8547}
8548
Mathieu Chartiere401d142015-04-22 13:56:20 -07008549void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008550 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008551 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8552 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008553 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008554 }
8555}
8556
Alex Lightdb01a092017-04-03 15:39:55 -07008557void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8558 DCHECK(method->IsObsolete());
8559 // We cannot mess with the entrypoints of native methods because they are used to determine how
8560 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8561 if (!method->IsNative()) {
8562 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8563 }
8564}
8565
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008566void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008567 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008568 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008569 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8570 << NumNonZygoteClasses() << "\n";
8571}
8572
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008573class CountClassesVisitor : public ClassLoaderVisitor {
8574 public:
8575 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8576
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008577 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008578 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008579 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008580 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008581 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8582 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008583 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008584 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008585
8586 size_t num_zygote_classes;
8587 size_t num_non_zygote_classes;
8588};
8589
8590size_t ClassLinker::NumZygoteClasses() const {
8591 CountClassesVisitor visitor;
8592 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008593 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008594}
8595
8596size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008597 CountClassesVisitor visitor;
8598 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008599 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008600}
8601
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008602size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008603 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008604 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008605 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008606}
8607
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008608pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008609 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008610}
8611
8612pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008613 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008614}
8615
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008616void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008617 DCHECK(!init_done_);
8618
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008619 DCHECK(klass != nullptr);
8620 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008621
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008622 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008623 DCHECK(class_roots != nullptr);
8624 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008625 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008626}
8627
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008628const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8629 static const char* class_roots_descriptors[] = {
8630 "Ljava/lang/Class;",
8631 "Ljava/lang/Object;",
8632 "[Ljava/lang/Class;",
8633 "[Ljava/lang/Object;",
8634 "Ljava/lang/String;",
8635 "Ljava/lang/DexCache;",
8636 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008637 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008638 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008639 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008640 "Ljava/lang/reflect/Proxy;",
8641 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008642 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008643 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008644 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008645 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008646 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008647 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008648 "Ljava/lang/invoke/MethodType;",
Orion Hodson005ac512017-10-24 15:43:43 +01008649 "Ljava/lang/invoke/VarHandle;",
8650 "Ljava/lang/invoke/FieldVarHandle;",
8651 "Ljava/lang/invoke/ArrayElementVarHandle;",
8652 "Ljava/lang/invoke/ByteArrayViewVarHandle;",
8653 "Ljava/lang/invoke/ByteBufferViewVarHandle;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008654 "Ljava/lang/ClassLoader;",
8655 "Ljava/lang/Throwable;",
8656 "Ljava/lang/ClassNotFoundException;",
8657 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008658 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008659 "Z",
8660 "B",
8661 "C",
8662 "D",
8663 "F",
8664 "I",
8665 "J",
8666 "S",
8667 "V",
8668 "[Z",
8669 "[B",
8670 "[C",
8671 "[D",
8672 "[F",
8673 "[I",
8674 "[J",
8675 "[S",
8676 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008677 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008678 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008679 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8680 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008681
8682 const char* descriptor = class_roots_descriptors[class_root];
8683 CHECK(descriptor != nullptr);
8684 return descriptor;
8685}
8686
Calin Juravle7865ac72017-06-28 11:03:12 -07008687jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
Andreas Gampe473191c2017-12-28 16:55:31 -08008688 const std::vector<const DexFile*>& dex_files,
8689 jclass loader_class,
8690 jobject parent_loader) {
Calin Juravle7865ac72017-06-28 11:03:12 -07008691 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8692 WellKnownClasses::dalvik_system_PathClassLoader) ||
8693 self->GetJniEnv()->IsSameObject(loader_class,
8694 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8695
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008696 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8697 // We could move the jobject to the callers, but all call-sites do this...
8698 ScopedObjectAccessUnchecked soa(self);
8699
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008700 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008701 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008702
Mathieu Chartierc7853442015-03-27 14:35:38 -07008703 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008704 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008705
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008706 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008707 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008708 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008709 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008710 mirror::ObjectArray<mirror::Object>::Alloc(self,
8711 dex_elements_class.Get(),
8712 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008713 Handle<mirror::Class> h_dex_element_class =
8714 hs.NewHandle(dex_elements_class->GetComponentType());
8715
Mathieu Chartierc7853442015-03-27 14:35:38 -07008716 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008717 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008718 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008719
Andreas Gampe08883de2016-11-08 13:20:52 -08008720 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00008721 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008722
Andreas Gampe08883de2016-11-08 13:20:52 -08008723 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00008724 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008725
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008726 // Fill the elements array.
8727 int32_t index = 0;
8728 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008729 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008730
Calin Juravle7865ac72017-06-28 11:03:12 -07008731 // CreateWellKnownClassLoader is only used by gtests and compiler.
8732 // 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 -07008733 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8734 self,
8735 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008736 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008737 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008738
Mathieu Chartier3738e982017-05-12 16:07:28 -07008739 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8740 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008741 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008742 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008743 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008744 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008745
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008746 Handle<mirror::String> h_file_name = hs2.NewHandle(
8747 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008748 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008749 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8750
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008751 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008752 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008753 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008754
8755 h_dex_elements->Set(index, h_element.Get());
8756 index++;
8757 }
8758 DCHECK_EQ(index, h_dex_elements->GetLength());
8759
8760 // Create DexPathList.
8761 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008762 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008763 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008764 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008765 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08008766 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
8767 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
8768 // elements.
8769 {
8770 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
8771 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
8772 DCHECK(native_lib_dirs != nullptr);
8773 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
8774 DCHECK(list_class != nullptr);
8775 {
8776 StackHandleScope<1> h_list_scope(self);
8777 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
8778 bool list_init = EnsureInitialized(self, h_list_class, true, true);
8779 DCHECK(list_init);
8780 list_class = h_list_class.Get();
8781 }
8782 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
8783 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
8784 // is fine for testing. While it violates a Java-code invariant (the elementData field is
8785 // normally never null), as long as one does not try to add elements, this will still
8786 // work.
8787 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
8788 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008789
Calin Juravle7865ac72017-06-28 11:03:12 -07008790 // Create the class loader..
8791 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8792 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8793 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008794 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008795 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008796 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008797 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008798 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008799
8800 // Make a pretend boot-classpath.
8801 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008802 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008803 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008804 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008805 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008806 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008807 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008808
8809 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8810 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8811 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8812 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008813
8814 // Make it a global ref and return.
8815 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008816 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008817 return soa.Env()->NewGlobalRef(local_ref.get());
8818}
8819
Calin Juravle7865ac72017-06-28 11:03:12 -07008820jobject ClassLinker::CreatePathClassLoader(Thread* self,
8821 const std::vector<const DexFile*>& dex_files) {
8822 return CreateWellKnownClassLoader(self,
8823 dex_files,
8824 WellKnownClasses::dalvik_system_PathClassLoader,
8825 nullptr);
8826}
8827
Andreas Gampe8ac75952015-06-02 21:01:45 -07008828void ClassLinker::DropFindArrayClassCache() {
8829 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8830 find_array_class_cache_next_victim_ = 0;
8831}
8832
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008833void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008834 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008835 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008836 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008837 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8838 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008839 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008840 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008841 }
8842 }
8843}
8844
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008845void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8846 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008847 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008848 Thread* const self = Thread::Current();
8849 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008850 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008851 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008852 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008853 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8854 // class table was modified.
8855 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8856 }
8857}
8858
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008859void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008860 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008861 std::vector<ClassLoaderData> to_delete;
8862 // Do the delete outside the lock to avoid lock violation in jit code cache.
8863 {
8864 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8865 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8866 const ClassLoaderData& data = *it;
8867 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008868 ObjPtr<mirror::ClassLoader> class_loader =
8869 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008870 if (class_loader != nullptr) {
8871 ++it;
8872 } else {
8873 VLOG(class_linker) << "Freeing class loader";
8874 to_delete.push_back(data);
8875 it = class_loaders_.erase(it);
8876 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008877 }
8878 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008879 for (ClassLoaderData& data : to_delete) {
8880 DeleteClassLoader(self, data);
8881 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008882}
8883
Vladimir Marko21300532017-01-24 18:06:55 +00008884class GetResolvedClassesVisitor : public ClassVisitor {
8885 public:
8886 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8887 : result_(result),
8888 ignore_boot_classes_(ignore_boot_classes),
8889 last_resolved_classes_(result->end()),
8890 last_dex_file_(nullptr),
8891 vlog_is_on_(VLOG_IS_ON(class_linker)),
8892 extra_stats_(),
8893 last_extra_stats_(extra_stats_.end()) { }
8894
8895 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8896 if (!klass->IsProxyClass() &&
8897 !klass->IsArrayClass() &&
8898 klass->IsResolved() &&
8899 !klass->IsErroneousResolved() &&
8900 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8901 const DexFile& dex_file = klass->GetDexFile();
8902 if (&dex_file != last_dex_file_) {
8903 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008904 DexCacheResolvedClasses resolved_classes(
8905 dex_file.GetLocation(),
8906 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8907 dex_file.GetLocationChecksum(),
8908 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008909 last_resolved_classes_ = result_->find(resolved_classes);
8910 if (last_resolved_classes_ == result_->end()) {
8911 last_resolved_classes_ = result_->insert(resolved_classes).first;
8912 }
8913 }
8914 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8915 if (UNLIKELY(vlog_is_on_) && added) {
8916 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8917 if (last_extra_stats_ == extra_stats_.end() ||
8918 last_extra_stats_->first != resolved_classes) {
8919 last_extra_stats_ = extra_stats_.find(resolved_classes);
8920 if (last_extra_stats_ == extra_stats_.end()) {
8921 last_extra_stats_ =
8922 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8923 }
8924 }
8925 }
8926 }
8927 return true;
8928 }
8929
8930 void PrintStatistics() const {
8931 if (vlog_is_on_) {
8932 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8933 auto it = extra_stats_.find(std::addressof(resolved_classes));
8934 DCHECK(it != extra_stats_.end());
8935 const ExtraStats& extra_stats = it->second;
8936 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8937 << " has " << resolved_classes.GetClasses().size() << " / "
8938 << extra_stats.number_of_class_defs_ << " resolved classes";
8939 }
8940 }
8941 }
8942
8943 private:
8944 struct ExtraStats {
8945 explicit ExtraStats(uint32_t number_of_class_defs)
8946 : number_of_class_defs_(number_of_class_defs) {}
8947 uint32_t number_of_class_defs_;
8948 };
8949
8950 std::set<DexCacheResolvedClasses>* result_;
8951 bool ignore_boot_classes_;
8952 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8953 const DexFile* last_dex_file_;
8954
8955 // Statistics.
8956 bool vlog_is_on_;
8957 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8958 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8959};
8960
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008961std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008962 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008963 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008964 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008965 std::set<DexCacheResolvedClasses> ret;
8966 VLOG(class_linker) << "Collecting resolved classes";
8967 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008968 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8969 VisitClasses(&visitor);
8970 if (VLOG_IS_ON(class_linker)) {
8971 visitor.PrintStatistics();
8972 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008973 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008974 return ret;
8975}
8976
Mathieu Chartier65975772016-08-05 10:46:36 -07008977class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
8978 public:
8979 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
8980 : method_(method),
8981 pointer_size_(pointer_size) {}
8982
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008983 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07008984 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
8985 holder_ = klass;
8986 }
8987 // Return false to stop searching if holder_ is not null.
8988 return holder_ == nullptr;
8989 }
8990
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008991 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07008992 const ArtMethod* const method_;
8993 const PointerSize pointer_size_;
8994};
8995
8996mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
8997 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
8998 CHECK(method->IsCopied());
8999 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9000 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009001 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07009002}
9003
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009004mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9005 return down_cast<mirror::IfTable*>(
9006 mirror::IfTable::Alloc(self,
9007 GetClassRoot(kObjectArrayClass),
9008 ifcount * mirror::IfTable::kMax));
9009}
9010
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009011// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009012template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009013 uint32_t method_idx,
9014 Handle<mirror::DexCache> dex_cache,
9015 Handle<mirror::ClassLoader> class_loader,
9016 ArtMethod* referrer,
9017 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009018template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009019 uint32_t method_idx,
9020 Handle<mirror::DexCache> dex_cache,
9021 Handle<mirror::ClassLoader> class_loader,
9022 ArtMethod* referrer,
9023 InvokeType type);
9024
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009025} // namespace art