blob: 2e625a704854bf2d41ae8d5ea77c9b5718d0aa61 [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;
Vladimir Markob066d432018-01-03 13:14:37 +00003363 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3364 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3365 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3366 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003367 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003368 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3369 DexCacheData data = *it;
3370 if (self->IsJWeakCleared(data.weak_root)) {
3371 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003372 it = dex_caches_.erase(it);
3373 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003374 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003375 it->dex_file->GetOatDexFile() != nullptr &&
3376 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003377 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003378 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003379 ++it;
3380 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003381 }
Vladimir Markob066d432018-01-03 13:14:37 +00003382 if (initialize_oat_file_data) {
3383 // Initialize the .data.bimg.rel.ro section.
3384 if (!oat_file->GetBootImageRelocations().empty()) {
3385 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3386 CheckedCall(mprotect,
3387 "un-protect boot image relocations",
3388 reloc_begin,
3389 oat_file->DataBimgRelRoSize(),
3390 PROT_READ | PROT_WRITE);
3391 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3392 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3393 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3394 const_cast<uint32_t&>(relocation) += boot_image_begin;
3395 }
3396 CheckedCall(mprotect,
3397 "protect boot image relocations",
3398 reloc_begin,
3399 oat_file->DataBimgRelRoSize(),
3400 PROT_READ);
3401 }
3402
3403 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003404 // TODO: Pre-initialize from boot/app image?
3405 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3406 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3407 entry = resolution_method;
3408 }
3409 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003410 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003411 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003412 DexCacheData data;
3413 data.weak_root = dex_cache_jweak;
3414 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003415 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky440a9b32018-02-15 17:47:29 +00003416 AddNativeDebugInfoForDex(self, ArrayRef<const uint8_t>(data.dex_file->Begin(),
3417 data.dex_file->Size()));
Vladimir Markocd556b02017-02-03 11:47:34 +00003418 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003419 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3420 // path dex caches without an image.
3421 data.class_table->InsertStrongRoot(dex_cache);
3422 if (class_loader != nullptr) {
3423 // Since we added a strong root to the class table, do the write barrier as required for
3424 // remembered sets and generational GCs.
3425 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3426 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003427 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003428}
3429
Vladimir Markocd556b02017-02-03 11:47:34 +00003430ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3431 return data.IsValid()
3432 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3433 : nullptr;
3434}
3435
3436ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3437 Thread* self,
3438 ObjPtr<mirror::DexCache> dex_cache,
3439 const DexCacheData& data,
3440 ObjPtr<mirror::ClassLoader> class_loader) {
3441 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3442 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3443 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3444 "Attempt to register dex file %s with multiple class loaders",
3445 data.dex_file->GetLocation().c_str());
3446 return nullptr;
3447 }
3448 return dex_cache;
3449}
3450
Alex Light07f06212017-06-01 14:01:43 -07003451void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3452 ObjPtr<mirror::ClassLoader> class_loader) {
3453 Thread* self = Thread::Current();
3454 StackHandleScope<2> hs(self);
3455 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3456 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3457 const DexFile* dex_file = dex_cache->GetDexFile();
3458 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3459 if (kIsDebugBuild) {
3460 DexCacheData old_data;
3461 {
3462 ReaderMutexLock mu(self, *Locks::dex_lock_);
3463 old_data = FindDexCacheDataLocked(*dex_file);
3464 }
3465 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3466 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3467 << "been registered on dex file " << dex_file->GetLocation();
3468 }
3469 ClassTable* table;
3470 {
3471 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3472 table = InsertClassTableForClassLoader(h_class_loader.Get());
3473 }
3474 WriterMutexLock mu(self, *Locks::dex_lock_);
3475 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3476 table->InsertStrongRoot(h_dex_cache.Get());
3477 if (h_class_loader.Get() != nullptr) {
3478 // Since we added a strong root to the class table, do the write barrier as required for
3479 // remembered sets and generational GCs.
3480 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3481 }
3482}
3483
Vladimir Markocd556b02017-02-03 11:47:34 +00003484ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3485 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003486 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003487 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003488 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003489 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003490 old_data = FindDexCacheDataLocked(dex_file);
3491 }
3492 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3493 if (old_dex_cache != nullptr) {
3494 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003495 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003496 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3497 DCHECK(linear_alloc != nullptr);
3498 ClassTable* table;
3499 {
3500 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3501 table = InsertClassTableForClassLoader(class_loader);
3502 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003503 // Don't alloc while holding the lock, since allocation may need to
3504 // suspend all threads and another thread may need the dex_lock_ to
3505 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003506 StackHandleScope<3> hs(self);
3507 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003508 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003509 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3510 self,
3511 dex_file)));
3512 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003513 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003514 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003515 old_data = FindDexCacheDataLocked(dex_file);
3516 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003517 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003518 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3519 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3520 // that the arrays are null.
3521 mirror::DexCache::InitializeDexCache(self,
3522 h_dex_cache.Get(),
3523 h_location.Get(),
3524 &dex_file,
3525 linear_alloc,
3526 image_pointer_size_);
3527 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003528 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003529 }
3530 if (old_dex_cache != nullptr) {
3531 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3532 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003533 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003534 self->ClearException();
3535 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3536 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3537 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003538 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003539 self->AssertPendingOOMException();
3540 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003541 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003542 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003543 if (h_class_loader.Get() != nullptr) {
3544 // Since we added a strong root to the class table, do the write barrier as required for
3545 // remembered sets and generational GCs.
3546 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3547 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003548 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003549}
3550
Vladimir Markocd556b02017-02-03 11:47:34 +00003551bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003552 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003553 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003554}
3555
Vladimir Markocd556b02017-02-03 11:47:34 +00003556ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3557 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003558 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3559 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003560 if (dex_cache != nullptr) {
3561 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003562 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003563 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003564 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003565 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003566 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003567 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003568 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003569 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3570 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003571 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003572}
3573
Vladimir Markocd556b02017-02-03 11:47:34 +00003574ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3575 const DexFile* dex_file = dex_cache->GetDexFile();
3576 DCHECK(dex_file != nullptr);
3577 ReaderMutexLock mu(self, *Locks::dex_lock_);
3578 // Search assuming unique-ness of dex file.
3579 for (const DexCacheData& data : dex_caches_) {
3580 // Avoid decoding (and read barriers) other unrelated dex caches.
3581 if (data.dex_file == dex_file) {
3582 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3583 if (registered_dex_cache != nullptr) {
3584 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3585 return data.class_table;
3586 }
3587 }
3588 }
3589 return nullptr;
3590}
3591
3592ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3593 // Search assuming unique-ness of dex file.
3594 for (const DexCacheData& data : dex_caches_) {
3595 // Avoid decoding (and read barriers) other unrelated dex caches.
3596 if (data.dex_file == &dex_file) {
3597 return data;
3598 }
3599 }
3600 return DexCacheData();
3601}
3602
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003603mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003604 ObjPtr<mirror::Class> klass =
3605 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003606 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003607 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003608 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003609 }
3610 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003611}
3612
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003613mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003614 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003615 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003616 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003617 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003618 StackHandleScope<1> hs(self);
3619 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003620 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003621 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3622 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003623 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00003624 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003625 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003626 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3627 h_class.Get(),
3628 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003629 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003630 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003631}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003632
Brian Carlstrombe977852011-07-19 14:54:54 -07003633// Create an array class (i.e. the class object for the array, not the
3634// array itself). "descriptor" looks like "[C" or "[[[[B" or
3635// "[Ljava/lang/String;".
3636//
3637// If "descriptor" refers to an array of primitives, look up the
3638// primitive type's internally-generated class object.
3639//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003640// "class_loader" is the class loader of the class that's referring to
3641// us. It's used to ensure that we're looking for the element type in
3642// the right context. It does NOT become the class loader for the
3643// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003644//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003645// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003646mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003647 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003648 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003649 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003650 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003651 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3652 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003653 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003654 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003655 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003656 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3657 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003658 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003659 DCHECK(self->IsExceptionPending());
3660 return nullptr;
3661 } else {
3662 self->ClearException();
3663 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003664 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003665 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3666 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3667 return nullptr;
3668 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003669 // See if the component type is already loaded. Array classes are
3670 // always associated with the class loader of their underlying
3671 // element type -- an array of Strings goes with the loader for
3672 // java/lang/String -- so we need to look for it there. (The
3673 // caller should have checked for the existence of the class
3674 // before calling here, but they did so with *their* class loader,
3675 // not the component type's loader.)
3676 //
3677 // If we find it, the caller adds "loader" to the class' initiating
3678 // loader list, which should prevent us from going through this again.
3679 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003680 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003681 // are the same, because our caller (FindClass) just did the
3682 // lookup. (Even if we get this wrong we still have correct behavior,
3683 // because we effectively do this lookup again when we add the new
3684 // class to the hash table --- necessary because of possible races with
3685 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003686 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003687 ObjPtr<mirror::Class> new_class =
3688 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003689 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003690 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003691 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003692 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003693
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003694 // Fill out the fields in the Class.
3695 //
3696 // It is possible to execute some methods against arrays, because
3697 // all arrays are subclasses of java_lang_Object_, so we need to set
3698 // up a vtable. We can just point at the one in java_lang_Object_.
3699 //
3700 // Array classes are simple enough that we don't need to do a full
3701 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003702 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003703 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003704 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003705 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003706 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003707 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003708 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003709 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003710 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003711 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003712 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003713 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003714 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003715 } else if (strcmp(descriptor, "[J") == 0) {
3716 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003717 }
3718 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003719 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003720 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003721 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003722 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003723 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003724 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003725 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003726 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003727 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003728 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003729 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003730 new_class->SetSuperClass(java_lang_Object);
3731 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003732 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003733 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003734 if (component_type->IsPrimitive()) {
3735 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3736 } else {
3737 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3738 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00003739 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003740 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3741 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3742 new_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003743 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003744 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003745 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003746
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003747 // All arrays have java/lang/Cloneable and java/io/Serializable as
3748 // interfaces. We need to set that up here, so that stuff like
3749 // "instanceof" works right.
3750 //
3751 // Note: The GC could run during the call to FindSystemClass,
3752 // so we need to make sure the class object is GC-valid while we're in
3753 // there. Do this by clearing the interface list so the GC will just
3754 // think that the entries are null.
3755
3756
3757 // Use the single, global copies of "interfaces" and "iftable"
3758 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003759 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003760 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003761 CHECK(array_iftable != nullptr);
3762 new_class->SetIfTable(array_iftable);
3763 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003764
Elliott Hughes00626c22013-06-14 15:04:14 -07003765 // Inherit access flags from the component type.
3766 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3767 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3768 access_flags &= kAccJavaFlagsMask;
3769 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003770 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003771 access_flags |= kAccAbstract | kAccFinal;
3772 access_flags &= ~kAccInterface;
3773
3774 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003775
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003776 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003777 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003778 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3779 // duplicate events in case of races. Array classes don't really follow dedicated
3780 // load and prepare, anyways.
3781 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3782 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3783
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003784 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003786 }
3787 // Another thread must have loaded the class after we
3788 // started but before we finished. Abandon what we've
3789 // done.
3790 //
3791 // (Yes, this happens.)
3792
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003793 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003794}
3795
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003796mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003797 switch (type) {
3798 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003799 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003800 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003801 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003802 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003803 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003804 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003805 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003806 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003807 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003808 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003809 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003810 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003811 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003812 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003813 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003814 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003815 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003816 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003817 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003818 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003819 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003820 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003821 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003822}
3823
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003824mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003825 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003826 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003827 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003828 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003829 source += " from ";
3830 source += dex_cache->GetLocation()->ToModifiedUtf8();
3831 }
3832 LOG(INFO) << "Loaded class " << descriptor << source;
3833 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003834 {
3835 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003836 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003837 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003838 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003839 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003840 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003841 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003842 VerifyObject(klass);
3843 class_table->InsertWithHash(klass, hash);
3844 if (class_loader != nullptr) {
3845 // This is necessary because we need to have the card dirtied for remembered sets.
3846 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3847 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003848 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003849 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003850 }
3851 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003852 if (kIsDebugBuild) {
3853 // Test that copied methods correctly can find their holder.
3854 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3855 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3856 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003857 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003858 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003859}
3860
Vladimir Marko1998cd02017-01-13 13:02:58 +00003861void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003862 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3863 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3864 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3865 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003866 }
3867}
3868
Alex Lighte64300b2015-12-15 15:02:47 -08003869// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003870void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003871 LengthPrefixedArray<ArtMethod>* new_methods) {
3872 klass->SetMethodsPtrUnchecked(new_methods,
3873 klass->NumDirectMethods(),
3874 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003875 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003876 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003877}
3878
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003879mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003880 const char* descriptor,
3881 ObjPtr<mirror::ClassLoader> class_loader) {
3882 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3883}
3884
3885mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003886 const char* descriptor,
3887 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003888 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003889 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3890 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3891 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003892 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003893 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003894 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003895 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003896 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003897 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003898}
3899
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003900class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3901 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08003902 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003903
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003904 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003905 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003906 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003907 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003908 if (class_table != nullptr) {
3909 class_table->FreezeSnapshot();
3910 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003911 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003912};
3913
3914void ClassLinker::MoveClassTableToPreZygote() {
3915 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003916 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003917 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003918 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003919}
3920
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003921// Look up classes by hash and descriptor and put all matching ones in the result array.
3922class LookupClassesVisitor : public ClassLoaderVisitor {
3923 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003924 LookupClassesVisitor(const char* descriptor,
3925 size_t hash,
3926 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003927 : descriptor_(descriptor),
3928 hash_(hash),
3929 result_(result) {}
3930
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003931 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003932 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003933 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003934 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003935 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3936 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003937 result_->push_back(klass);
3938 }
3939 }
3940
3941 private:
3942 const char* const descriptor_;
3943 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003944 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003945};
3946
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003947void ClassLinker::LookupClasses(const char* descriptor,
3948 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003949 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003950 Thread* const self = Thread::Current();
3951 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003952 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003953 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003954 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003955 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003956 result.push_back(klass);
3957 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003958 LookupClassesVisitor visitor(descriptor, hash, &result);
3959 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003960}
3961
Alex Lightf1f10492015-10-07 16:08:36 -07003962bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3963 Handle<mirror::Class> klass,
3964 Handle<mirror::Class> supertype) {
3965 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003966 DCHECK(klass != nullptr);
3967 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003968
Alex Lightf1f10492015-10-07 16:08:36 -07003969 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3970 VerifyClass(self, supertype);
3971 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003972
3973 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3974 // The supertype is either verified, or we soft failed at AOT time.
3975 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003976 return true;
3977 }
3978 // If we got this far then we have a hard failure.
3979 std::string error_msg =
3980 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003981 klass->PrettyDescriptor().c_str(),
3982 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003983 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003984 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003985 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003986 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003987 // Set during VerifyClass call (if at all).
3988 self->ClearException();
3989 }
3990 // Change into a verify error.
3991 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003992 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003993 self->GetException()->SetCause(cause.Get());
3994 }
3995 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3996 if (Runtime::Current()->IsAotCompiler()) {
3997 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3998 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003999 // Need to grab the lock to change status.
4000 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004001 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004002 return false;
4003}
4004
Andreas Gampecc1b5352016-12-01 16:58:38 -08004005// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
4006// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
4007// before.
4008static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
4009 REQUIRES_SHARED(Locks::mutator_lock_) {
4010 if (!klass->WasVerificationAttempted()) {
4011 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
4012 klass->SetVerificationAttempted();
4013 }
4014}
4015
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004016verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004017 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004018 {
4019 // TODO: assert that the monitor on the Class is held
4020 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004021
Andreas Gampe884f3b82016-03-30 19:52:58 -07004022 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004023 ClassStatus old_status = klass->GetStatus();
4024 while (old_status == ClassStatus::kVerifying ||
4025 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004026 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004027 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4028 // case we may see the same status again. b/62912904. This is why the check is
4029 // greater or equal.
4030 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004031 << "Class '" << klass->PrettyClass()
4032 << "' performed an illegal verification state transition from " << old_status
4033 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004034 old_status = klass->GetStatus();
4035 }
jeffhao98eacac2011-09-14 16:11:53 -07004036
Andreas Gampe884f3b82016-03-30 19:52:58 -07004037 // The class might already be erroneous, for example at compile time if we attempted to verify
4038 // this class as a parent to another.
4039 if (klass->IsErroneous()) {
4040 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004041 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004042 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004043
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004044 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004045 if (klass->IsVerified()) {
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 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004049
4050 // For AOT, don't attempt to re-verify if we have already found we should
4051 // verify at runtime.
4052 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004053 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004054 }
jeffhao98eacac2011-09-14 16:11:53 -07004055
Vladimir Marko2c64a832018-01-04 11:31:56 +00004056 if (klass->GetStatus() == ClassStatus::kResolved) {
4057 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004058 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004059 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004060 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004061 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004062 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004063 }
4064
4065 // Skip verification if disabled.
4066 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004067 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004068 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004069 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004070 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004071 }
4072
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004073 VLOG(class_linker) << "Beginning verification for class: "
4074 << klass->PrettyDescriptor()
4075 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4076
Ian Rogers9ffb0392012-09-10 11:56:50 -07004077 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004078 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004079 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4080 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004081 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004082 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004083 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004084 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004085
Alex Lightf1f10492015-10-07 16:08:36 -07004086 // Verify all default super-interfaces.
4087 //
4088 // (1) Don't bother if the superclass has already had a soft verification failure.
4089 //
4090 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4091 // recursive initialization by themselves. This is because when an interface is initialized
4092 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4093 // but choose not to for an optimization. If the interfaces is being verified due to a class
4094 // initialization (which would need all the default interfaces to be verified) the class code
4095 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004096 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004097 && !klass->IsInterface()) { // See (2)
4098 int32_t iftable_count = klass->GetIfTableCount();
4099 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4100 // Loop through all interfaces this class has defined. It doesn't matter the order.
4101 for (int32_t i = 0; i < iftable_count; i++) {
4102 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004103 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004104 // We only care if we have default interfaces and can skip if we are already verified...
4105 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4106 continue;
4107 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4108 // We had a hard failure while verifying this interface. Just return immediately.
4109 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004110 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004111 } else if (UNLIKELY(!iface->IsVerified())) {
4112 // We softly failed to verify the iface. Stop checking and clean up.
4113 // Put the iface into the supertype handle so we know what caused us to fail.
4114 supertype.Assign(iface.Get());
4115 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004116 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004117 }
4118 }
4119
Alex Lightf1f10492015-10-07 16:08:36 -07004120 // At this point if verification failed, then supertype is the "first" supertype that failed
4121 // verification (without a specific order). If verification succeeded, then supertype is either
4122 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004123 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004124 supertype.Get() == klass->GetSuperClass() ||
4125 !supertype->IsVerified());
4126
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004127 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004128 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004129 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004130 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004131
4132 VLOG(class_linker) << "Class preverified status for class "
4133 << klass->PrettyDescriptor()
4134 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4135 << ": "
4136 << preverified;
4137
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004138 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4139 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004140 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4141 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004142
Ian Rogers62d6c772013-02-27 08:32:07 -08004143 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004144 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004145 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004146 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004147 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004148
4149 // Verification is done, grab the lock again.
4150 ObjectLock<mirror::Class> lock(self, klass);
4151
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004152 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4153 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004154 VLOG(class_linker) << "Soft verification failure in class "
4155 << klass->PrettyDescriptor()
4156 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4157 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004158 }
Ian Rogers1f539342012-10-03 21:09:42 -07004159 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004160 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004161 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004162 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004163 // Even though there were no verifier failures we need to respect whether the super-class and
4164 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004165 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004166 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004167 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004168 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4169 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004170 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004171 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004172 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004173 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004174 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004175 // Soft failures at compile time should be retried at runtime. Soft
4176 // failures at runtime will be handled by slow paths in the generated
4177 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004178 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004179 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004180 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004181 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004182 // As this is a fake verified status, make sure the methods are _not_ marked
4183 // kAccSkipAccessChecks later.
4184 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004185 }
4186 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004187 } else {
David Sehr709b0702016-10-13 09:12:37 -07004188 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004189 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4190 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004191 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004192 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004193 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004194 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004195 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004196 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004197 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004198 // method.
4199 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004200 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004201 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004202
4203 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4204 // Never skip access checks if the verification soft fail is forced.
4205 // Mark the class as having a verification attempt to avoid re-running the verifier.
4206 klass->SetVerificationAttempted();
4207 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004208 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004209 }
Andreas Gampe48498592014-09-10 19:48:05 -07004210 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004211 // Done verifying. Notify the compiler about the verification status, in case the class
4212 // was verified implicitly (eg super class of a compiled class).
4213 if (Runtime::Current()->IsAotCompiler()) {
4214 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4215 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4216 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004217 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004218}
4219
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004220verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4221 Handle<mirror::Class> klass,
4222 verifier::HardFailLogMode log_level,
4223 std::string* error_msg) {
4224 Runtime* const runtime = Runtime::Current();
4225 return verifier::MethodVerifier::VerifyClass(self,
4226 klass.Get(),
4227 runtime->GetCompilerCallbacks(),
4228 runtime->IsAotCompiler(),
4229 log_level,
4230 error_msg);
4231}
4232
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004233bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004234 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004235 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004236 // If we're compiling, we can only verify the class using the oat file if
4237 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004238 // the compilation unit (app - dependencies). We will let the compiler callback
4239 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004240 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004241 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004242 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004243 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004244 return false;
4245 }
4246 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004247 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004248 return false;
4249 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004250 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004251
Richard Uhler07b3c232015-03-31 15:57:54 -07004252 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004253 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004254 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004255 return false;
4256 }
4257
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004258 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004259 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004260 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004261 return true;
4262 }
4263 // If we only verified a subset of the classes at compile time, we can end up with classes that
4264 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004265 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004266 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004267 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004268 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004269 // Compile time verification failed with a soft error. Compile time verification can fail
4270 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004271 // class ... {
4272 // Foo x;
4273 // .... () {
4274 // if (...) {
4275 // v1 gets assigned a type of resolved class Foo
4276 // } else {
4277 // v1 gets assigned a type of unresolved class Bar
4278 // }
4279 // iput x = v1
4280 // } }
4281 // when we merge v1 following the if-the-else it results in Conflict
4282 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4283 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4284 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4285 // at compile time).
4286 return false;
4287 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004288 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004289 // Compile time verification failed with a hard error. This is caused by invalid instructions
4290 // in the class. These errors are unrecoverable.
4291 return false;
4292 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004293 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004294 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4295 // not loading the class.
4296 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4297 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004298 return false;
4299 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004300 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004301 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004302 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004303 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004304 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004305}
4306
Alex Light5a559862016-01-29 12:24:48 -08004307void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004308 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004309 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004310 }
4311}
4312
Alex Light5a559862016-01-29 12:24:48 -08004313void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004314 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004315 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004316 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004317 return; // native or abstract method
4318 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004319 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004320 return; // nothing to process
4321 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004322 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004323 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004324 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4325 CatchHandlerIterator iterator(handlers_ptr);
4326 for (; iterator.HasNext(); iterator.Next()) {
4327 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4328 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004329 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004330 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004331 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004332 DCHECK(Thread::Current()->IsExceptionPending());
4333 Thread::Current()->ClearException();
4334 }
4335 }
4336 }
4337 handlers_ptr = iterator.EndDataPointer();
4338 }
4339}
4340
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004341mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4342 jstring name,
4343 jobjectArray interfaces,
4344 jobject loader,
4345 jobjectArray methods,
4346 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004347 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004348 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004349 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004350 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004351 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004352 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004353 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004354 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004355 DCHECK(temp_klass->GetClass() != nullptr);
4356 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004357 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4358 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004359 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4360 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4361 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4362 temp_klass->SetName(soa.Decode<mirror::String>(name));
4363 temp_klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004364 // Object has an empty iftable, copy it for that reason.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004365 temp_klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004366 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004367 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004368 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004369
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004370 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004371 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004372
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004373 // Insert the class before loading the fields as the field roots
4374 // (ArtField::declaring_class_) are only visited from the class
4375 // table. There can't be any suspend points between inserting the
4376 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004377 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004378 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004379
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004380 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004381 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004382 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004383 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004384
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004385 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4386 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004387 ArtField& interfaces_sfield = sfields->At(0);
4388 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004389 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004390 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004391
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004392 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004393 ArtField& throws_sfield = sfields->At(1);
4394 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004395 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004396 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004397
Ian Rogers466bb252011-10-14 03:29:56 -07004398 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004399 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004400
Alex Lighte64300b2015-12-15 15:02:47 -08004401 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004402 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004403 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004404 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004405 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004406
4407 // Create the methods array.
4408 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4409 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004410 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4411 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004412 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004413 self->AssertPendingOOMException();
4414 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004415 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004416 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004417
4418 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004419 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004420
4421 // Create virtual method using specified prototypes.
4422 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004423 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004424 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004425 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004426 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004427 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4428 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004429 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004430
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004431 // The super class is java.lang.reflect.Proxy
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004432 temp_klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004433 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004434 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004435 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004436
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004437 // At this point the class is loaded. Publish a ClassLoad event.
4438 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4439 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4440
4441 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004442 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004443 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004444 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004445 // Link the fields and virtual methods, creating vtable and iftables.
4446 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004447 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004448 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004449 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004450 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004451 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004452 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004453 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004454 CHECK(temp_klass->IsRetired());
4455 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004456
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004457 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004458 interfaces_sfield.SetObject<false>(
4459 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004460 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004461 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4462 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004463 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004464 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004465
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004466 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4467
Vladimir Marko305c38b2018-02-14 11:50:07 +00004468 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4469 // See also ClassLinker::EnsureInitialized().
4470 if (kBitstringSubtypeCheckEnabled) {
4471 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4472 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4473 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4474 }
4475
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004476 {
4477 // Lock on klass is released. Lock new class object.
4478 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004479 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004480 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004481
4482 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004483 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004484 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004485 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4486
Ian Rogersc2b44472011-12-14 21:17:17 -08004487 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004488 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4489 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004490 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004491 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004492
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004493 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004494 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004495 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004496 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004497 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004498
4499 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004500 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004501 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004502
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004503 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004504 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004505 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004506 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004507 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004508 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004509}
4510
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004511std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004512 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004513 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004514 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004515 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4516}
4517
Mathieu Chartiere401d142015-04-22 13:56:20 -07004518void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4519 // Create constructor for Proxy that must initialize the method.
Neil Fullerd12c3b02017-11-30 18:03:15 +00004520 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004521
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004522 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4523 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markoba118822017-06-12 15:41:56 +01004524 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->FindConstructor(
4525 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004526 DCHECK(proxy_constructor != nullptr)
4527 << "Could not find <init> method in java.lang.reflect.Proxy";
4528
Jeff Haodb8a6642014-08-14 17:18:52 -07004529 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4530 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004531 DCHECK(out != nullptr);
4532 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004533 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004534 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004535 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004536 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4537 kAccPublic |
4538 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004539 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004540
4541 // Set the original constructor method.
4542 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004543}
4544
Mathieu Chartiere401d142015-04-22 13:56:20 -07004545void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004546 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004547 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4548 CHECK_STREQ(np->GetName(), "<init>");
4549 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004550 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004551}
4552
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004553void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004554 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004555 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004556 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004557 DCHECK(out != nullptr);
4558 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004559
Alex Lighte9dd04f2016-03-16 16:09:45 -07004560 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004561 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004562 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4563 // preference to the invocation handler.
4564 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4565 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004566 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4567 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004568 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4569
4570 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4571 // method they copy might (if it's a default method).
4572 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004573
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004574 // Set the original interface method.
4575 out->SetDataPtrSize(prototype, image_pointer_size_);
4576
Ian Rogers466bb252011-10-14 03:29:56 -07004577 // At runtime the method looks like a reference and argument saving method, clone the code
4578 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004579 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004580}
Jesse Wilson95caa792011-10-12 18:14:17 -04004581
Mathieu Chartiere401d142015-04-22 13:56:20 -07004582void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004583 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004584 CHECK(!prototype->IsFinal());
4585 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004586 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004587
4588 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4589 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004590 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004591 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004592}
4593
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004594bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004595 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004596 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004597 return true;
4598 }
4599 if (!can_init_statics) {
4600 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004601 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004602 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004603 return false;
4604 }
4605 // Check if there are encoded static values needing initialization.
4606 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004607 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004608 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004609 if (dex_class_def->static_values_off_ != 0) {
4610 return false;
4611 }
4612 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004613 // If we are a class we need to initialize all interfaces with default methods when we are
4614 // initialized. Check all of them.
4615 if (!klass->IsInterface()) {
4616 size_t num_interfaces = klass->GetIfTableCount();
4617 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004618 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004619 if (iface->HasDefaultMethods() &&
4620 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4621 return false;
4622 }
4623 }
4624 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004625 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004626 if (klass->IsInterface() || !klass->HasSuperClass()) {
4627 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004628 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004629 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004630 if (!can_init_parents && !super_class->IsInitialized()) {
4631 return false;
4632 }
4633 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004634}
4635
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004636bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4637 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004638 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4639
4640 // Are we already initialized and therefore done?
4641 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4642 // an initialized class will never change its state.
4643 if (klass->IsInitialized()) {
4644 return true;
4645 }
4646
4647 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004648 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004649 return false;
4650 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004651
Ian Rogers7b078e82014-09-10 14:44:24 -07004652 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004653 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004654 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004655 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004656
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004657 // Re-check under the lock in case another thread initialized ahead of us.
4658 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004659 return true;
4660 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004661
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004662 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004663 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004664 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004665 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004666 return false;
4667 }
4668
Vladimir Marko72ab6842017-01-20 19:32:50 +00004669 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4670 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004671
4672 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004673 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004674 if (!klass->IsVerified()) {
4675 // We failed to verify, expect either the klass to be erroneous or verification failed at
4676 // compile time.
4677 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004678 // The class is erroneous. This may be a verifier error, or another thread attempted
4679 // verification and/or initialization and failed. We can distinguish those cases by
4680 // whether an exception is already pending.
4681 if (self->IsExceptionPending()) {
4682 // Check that it's a VerifyError.
4683 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004684 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004685 } else {
4686 // Check that another thread attempted initialization.
4687 DCHECK_NE(0, klass->GetClinitThreadId());
4688 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4689 // Need to rethrow the previous failure now.
4690 ThrowEarlierClassFailure(klass.Get(), true);
4691 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004692 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004693 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004694 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004695 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004696 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004697 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004698 } else {
4699 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004700 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004701
4702 // A separate thread could have moved us all the way to initialized. A "simple" example
4703 // involves a subclass of the current class being initialized at the same time (which
4704 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004705 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004706 if (klass->IsInitialized()) {
4707 return true;
4708 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004709 }
4710
Vladimir Marko2c64a832018-01-04 11:31:56 +00004711 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07004712 // initializing higher up the stack or another thread has beat us
4713 // to initializing and we need to wait. Either way, this
4714 // invocation of InitializeClass will not be responsible for
4715 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004716 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004717 // Could have got an exception during verification.
4718 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004719 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004720 return false;
4721 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004722 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004723 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004724 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004725 return true;
4726 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004727 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004728 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004729 }
4730
Jeff Haoe2e40342017-07-19 10:45:18 -07004731 // Try to get the oat class's status for this class if the oat file is present. The compiler
4732 // tries to validate superclass descriptors, and writes the result into the oat file.
4733 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4734 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4735 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004736 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004737 const Runtime* runtime = Runtime::Current();
4738 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4739 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4740 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004741 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07004742 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004743 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004744 return false;
4745 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004746 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004747
Vladimir Marko2c64a832018-01-04 11:31:56 +00004748 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004749 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004750
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004751 // From here out other threads may observe that we're initializing and so changes of state
4752 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004753 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004754 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004755
4756 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004757 }
4758
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004759 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004760 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004761 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004762 if (!super_class->IsInitialized()) {
4763 CHECK(!super_class->IsInterface());
4764 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004765 StackHandleScope<1> hs(self);
4766 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004767 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004768 if (!super_initialized) {
4769 // The super class was verified ahead of entering initializing, we should only be here if
4770 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004771 // For the case of aot compiler, the super class might also be initializing but we don't
4772 // want to process circular dependencies in pre-compile.
4773 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004774 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004775 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004776 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004777 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004778 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004779 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004780 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004781 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004782 return false;
4783 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004784 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004785 }
4786
Alex Lighteb7c1442015-08-31 13:17:42 -07004787 if (!klass->IsInterface()) {
4788 // Initialize interfaces with default methods for the JLS.
4789 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004790 // Only setup the (expensive) handle scope if we actually need to.
4791 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004792 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004793 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4794 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004795 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004796 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004797 CHECK(handle_scope_iface->IsInterface());
4798 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4799 // We have already done this for this interface. Skip it.
4800 continue;
4801 }
4802 // We cannot just call initialize class directly because we need to ensure that ALL
4803 // interfaces with default methods are initialized. Non-default interface initialization
4804 // will not affect other non-default super-interfaces.
4805 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4806 handle_scope_iface,
4807 can_init_statics,
4808 can_init_parents);
4809 if (!iface_initialized) {
4810 ObjectLock<mirror::Class> lock(self, klass);
4811 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004812 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004813 return false;
4814 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004815 }
4816 }
4817 }
4818
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004819 const size_t num_static_fields = klass->NumStaticFields();
4820 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004821 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004822 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004823 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004824 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004825 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004826
4827 // Eagerly fill in static fields so that the we don't have to do as many expensive
4828 // Class::FindStaticField in ResolveField.
4829 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004830 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004831 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004832 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004833 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004834 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004835 } else {
4836 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004837 }
4838 }
4839
Vladimir Markoe11dd502017-12-08 14:09:45 +00004840 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
4841 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07004842 this,
4843 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00004844 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers13735952014-10-08 12:43:28 -07004845 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004846 ClassDataItemIterator field_it(dex_file, class_data);
4847 if (value_it.HasNext()) {
4848 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004849 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004850 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004851 ArtField* field = ResolveField(
Vladimir Markoe11dd502017-12-08 14:09:45 +00004852 field_it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004853 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004854 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004855 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004856 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004857 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004858 if (self->IsExceptionPending()) {
4859 break;
4860 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004861 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004862 }
4863 }
4864 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004865
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004866
Mathieu Chartierda595be2016-08-10 13:57:39 -07004867 if (!self->IsExceptionPending()) {
4868 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4869 if (clinit != nullptr) {
4870 CHECK(can_init_statics);
4871 JValue result;
4872 clinit->Invoke(self, nullptr, 0, &result, "V");
4873 }
4874 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004875 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004876 uint64_t t1 = NanoTime();
4877
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004878 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004879 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004880 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004881
4882 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004883 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004884 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004885 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004886 } else if (Runtime::Current()->IsTransactionAborted()) {
4887 // The exception thrown when the transaction aborted has been caught and cleared
4888 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004889 VLOG(compiler) << "Return from class initializer of "
4890 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004891 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004892 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004893 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004894 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004895 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004896 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4897 RuntimeStats* thread_stats = self->GetStats();
4898 ++global_stats->class_init_count;
4899 ++thread_stats->class_init_count;
4900 global_stats->class_init_time_ns += (t1 - t0);
4901 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004902 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004903 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004904 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004905 std::string temp;
4906 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004907 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004908 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004909 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004910 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004911 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004912 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004913 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004914}
4915
Alex Lighteb7c1442015-08-31 13:17:42 -07004916// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4917// and perform the initialization only on those interfaces that contain default methods.
4918bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4919 Handle<mirror::Class> iface,
4920 bool can_init_statics,
4921 bool can_init_parents) {
4922 CHECK(iface->IsInterface());
4923 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004924 // Only create the (expensive) handle scope if we need it.
4925 if (UNLIKELY(num_direct_ifaces > 0)) {
4926 StackHandleScope<1> hs(self);
4927 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4928 // First we initialize all of iface's super-interfaces recursively.
4929 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004930 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004931 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004932 if (!super_iface->HasBeenRecursivelyInitialized()) {
4933 // Recursive step
4934 handle_super_iface.Assign(super_iface);
4935 if (!InitializeDefaultInterfaceRecursive(self,
4936 handle_super_iface,
4937 can_init_statics,
4938 can_init_parents)) {
4939 return false;
4940 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004941 }
4942 }
4943 }
4944
4945 bool result = true;
4946 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4947 // initialize if we don't have default methods.
4948 if (iface->HasDefaultMethods()) {
4949 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4950 }
4951
4952 // Mark that this interface has undergone recursive default interface initialization so we know we
4953 // can skip it on any later class initializations. We do this even if we are not a default
4954 // interface since we can still avoid the traversal. This is purely a performance optimization.
4955 if (result) {
4956 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08004957 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
4958 // interface. It is bad (Java) style, but not impossible. Marking the recursive
4959 // initialization is a performance optimization (to avoid another idempotent visit
4960 // for other implementing classes/interfaces), and can be revisited later.
4961 ObjectTryLock<mirror::Class> lock(self, iface);
4962 if (lock.Acquired()) {
4963 iface->SetRecursivelyInitialized();
4964 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004965 }
4966 return result;
4967}
4968
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004969bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4970 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004971 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004972 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004973 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004974 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004975 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004976 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004977
4978 // When we wake up, repeat the test for init-in-progress. If
4979 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004980 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004981 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004982 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004983 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004984 return false;
4985 }
4986 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004987 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004988 continue;
4989 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004990 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004991 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004992 // Compile time initialization failed.
4993 return false;
4994 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004995 if (klass->IsErroneous()) {
4996 // The caller wants an exception, but it was thrown in a
4997 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004998 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004999 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005000 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005001 return false;
5002 }
5003 if (klass->IsInitialized()) {
5004 return true;
5005 }
David Sehr709b0702016-10-13 09:12:37 -07005006 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005007 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005008 }
Ian Rogers07140832014-09-30 15:43:59 -07005009 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005010}
5011
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005012static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5013 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005014 ArtMethod* method,
5015 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005016 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005017 DCHECK(Thread::Current()->IsExceptionPending());
5018 DCHECK(!m->IsProxyMethod());
5019 const DexFile* dex_file = m->GetDexFile();
5020 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5021 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005022 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005023 std::string return_type = dex_file->PrettyType(return_type_idx);
5024 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005025 ThrowWrappedLinkageError(klass.Get(),
5026 "While checking class %s method %s signature against %s %s: "
5027 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005028 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5029 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005030 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005031 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005032 return_type.c_str(), class_loader.c_str());
5033}
5034
5035static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5036 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005037 ArtMethod* method,
5038 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005039 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005040 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005041 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005042 DCHECK(Thread::Current()->IsExceptionPending());
5043 DCHECK(!m->IsProxyMethod());
5044 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005045 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5046 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005047 ThrowWrappedLinkageError(klass.Get(),
5048 "While checking class %s method %s signature against %s %s: "
5049 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005050 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5051 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005052 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005053 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005054 index, arg_type.c_str(), class_loader.c_str());
5055}
5056
5057static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5058 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005059 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005060 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005061 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005062 ThrowLinkageError(klass.Get(),
5063 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005064 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5065 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005066 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005067 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005068 error_msg.c_str());
5069}
5070
Ian Rogersb5fb2072014-12-02 17:22:02 -08005071static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005072 Handle<mirror::Class> klass,
5073 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005074 ArtMethod* method1,
5075 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005076 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005077 {
5078 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005079 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005080 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005081 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005082 return false;
5083 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005084 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005085 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005086 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005087 return false;
5088 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005089 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005090 ThrowSignatureMismatch(klass, super_klass, method1,
5091 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005092 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005093 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005094 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005095 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005096 return false;
5097 }
5098 }
5099 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5100 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5101 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005102 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005103 ThrowSignatureMismatch(klass, super_klass, method1,
5104 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005105 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005106 return false;
5107 }
5108 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005109 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005110 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005111 ThrowSignatureMismatch(klass, super_klass, method1,
5112 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005113 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005114 return false;
5115 }
5116 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005117 }
5118 uint32_t num_types = types1->Size();
5119 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005120 ThrowSignatureMismatch(klass, super_klass, method1,
5121 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005122 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005123 return false;
5124 }
5125 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005126 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005127 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005128 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005129 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005130 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005131 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005132 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005133 return false;
5134 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005135 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005136 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005137 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005138 if (UNLIKELY(other_param_type == nullptr)) {
5139 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005140 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005141 return false;
5142 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005143 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005144 ThrowSignatureMismatch(klass, super_klass, method1,
5145 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5146 i,
David Sehr709b0702016-10-13 09:12:37 -07005147 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005148 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005149 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005150 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005151 return false;
5152 }
5153 }
5154 return true;
5155}
5156
5157
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005158bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005159 if (klass->IsInterface()) {
5160 return true;
5161 }
Ian Rogers151f2212014-05-06 11:27:27 -07005162 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005163 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005164 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005165 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005166 if (klass->HasSuperClass() &&
5167 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005168 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005169 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005170 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5171 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5172 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005173 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5174 klass,
5175 super_klass,
5176 m,
5177 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005178 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005179 return false;
5180 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005181 }
5182 }
5183 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005184 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005185 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5186 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5187 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005188 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005189 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5190 j, image_pointer_size_);
5191 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5192 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005193 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5194 klass,
5195 super_klass,
5196 m,
5197 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005198 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005199 return false;
5200 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201 }
5202 }
5203 }
5204 }
5205 return true;
5206}
5207
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005208bool ClassLinker::EnsureInitialized(Thread* self,
5209 Handle<mirror::Class> c,
5210 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005211 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005212 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005213
Mathieu Chartier524507a2014-08-27 15:28:28 -07005214 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005215 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005216 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005217 return true;
5218 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005219 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5220 //
5221 // Ensure the bitstring is initialized before any of the class initialization
5222 // logic occurs. Once a class initializer starts running, objects can
5223 // escape into the heap and use the subtype checking code.
5224 //
5225 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5226 // can be used as a source for the IsSubClass check, and that all ancestors
5227 // of the class are Assigned (can be used as a target for IsSubClass check)
5228 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005229 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005230 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005231 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005232 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5233 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005234 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005235 if (!success) {
5236 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005237 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005238 }
5239 } else {
5240 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005241 }
5242 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005243}
5244
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005245void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5246 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005247 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005248 for (ArtField& field : new_class->GetIFields()) {
5249 if (field.GetDeclaringClass() == temp_class) {
5250 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005251 }
5252 }
5253
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005254 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005255 for (ArtField& field : new_class->GetSFields()) {
5256 if (field.GetDeclaringClass() == temp_class) {
5257 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005258 }
5259 }
5260
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005261 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005262 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005263 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005264 if (method.GetDeclaringClass() == temp_class) {
5265 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005266 }
5267 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005268
5269 // Make sure the remembered set and mod-union tables know that we updated some of the native
5270 // roots.
5271 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005272}
5273
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005274void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005275 CHECK(class_loader->GetAllocator() == nullptr);
5276 CHECK(class_loader->GetClassTable() == nullptr);
5277 Thread* const self = Thread::Current();
5278 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005279 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005280 // Create and set the class table.
5281 data.class_table = new ClassTable;
5282 class_loader->SetClassTable(data.class_table);
5283 // Create and set the linear allocator.
5284 data.allocator = Runtime::Current()->CreateLinearAlloc();
5285 class_loader->SetAllocator(data.allocator);
5286 // Add to the list so that we know to free the data later.
5287 class_loaders_.push_back(data);
5288}
5289
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005290ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005291 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005292 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005293 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005294 ClassTable* class_table = class_loader->GetClassTable();
5295 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005296 RegisterClassLoader(class_loader);
5297 class_table = class_loader->GetClassTable();
5298 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005299 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005300 return class_table;
5301}
5302
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005303ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005304 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005305}
5306
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005307static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005308 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005309 while (klass->HasSuperClass()) {
5310 klass = klass->GetSuperClass();
5311 if (klass->ShouldHaveImt()) {
5312 return klass->GetImt(pointer_size);
5313 }
5314 }
5315 return nullptr;
5316}
5317
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005318bool ClassLinker::LinkClass(Thread* self,
5319 const char* descriptor,
5320 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005321 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005322 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005323 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005324
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005325 if (!LinkSuperClass(klass)) {
5326 return false;
5327 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005328 ArtMethod* imt_data[ImTable::kSize];
5329 // If there are any new conflicts compared to super class.
5330 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005331 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005332 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005333 return false;
5334 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005335 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005336 return false;
5337 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005338 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005339 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005340 return false;
5341 }
5342 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005343 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005344
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005345 ImTable* imt = nullptr;
5346 if (klass->ShouldHaveImt()) {
5347 // If there are any new conflicts compared to the super class we can not make a copy. There
5348 // can be cases where both will have a conflict method at the same slot without having the same
5349 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5350 // will possibly create a table that is incorrect for either of the classes.
5351 // Same IMT with new_conflict does not happen very often.
5352 if (!new_conflict) {
5353 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5354 if (super_imt != nullptr) {
5355 bool imt_equals = true;
5356 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5357 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5358 }
5359 if (imt_equals) {
5360 imt = super_imt;
5361 }
5362 }
5363 }
5364 if (imt == nullptr) {
5365 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5366 imt = reinterpret_cast<ImTable*>(
5367 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5368 if (imt == nullptr) {
5369 return false;
5370 }
5371 imt->Populate(imt_data, image_pointer_size_);
5372 }
5373 }
5374
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005375 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5376 // We don't need to retire this class as it has no embedded tables or it was created the
5377 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005378 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005379
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005380 if (klass->ShouldHaveEmbeddedVTable()) {
5381 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005382 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005383 if (klass->ShouldHaveImt()) {
5384 klass->SetImt(imt, image_pointer_size_);
5385 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005386
5387 // Update CHA info based on whether we override methods.
5388 // Have to do this before setting the class as resolved which allows
5389 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005390 if (cha_ != nullptr) {
5391 cha_->UpdateAfterLoadingOf(klass);
5392 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005393
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005394 // This will notify waiters on klass that saw the not yet resolved
5395 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005396 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005397 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005398 } else {
5399 CHECK(!klass->IsResolved());
5400 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005401 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005402 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005403 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5404 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5405 // may not see any references to the target space and clean the card for a class if another
5406 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005407 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005408 klass->SetSFieldsPtrUnchecked(nullptr);
5409 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005410 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005411 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005412 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005413 return false;
5414 }
5415
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005416 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5417 ObjectLock<mirror::Class> lock(self, h_new_class);
5418 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005419
5420 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005421 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005422 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005423 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005424 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005425 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005426 if (class_loader != nullptr) {
5427 // We updated the class in the class table, perform the write barrier so that the GC knows
5428 // about the change.
5429 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5430 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005431 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005432 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005433 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5434 }
5435 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005436
Mingyao Yang063fc772016-08-02 11:02:54 -07005437 // Update CHA info based on whether we override methods.
5438 // Have to do this before setting the class as resolved which allows
5439 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005440 if (cha_ != nullptr) {
5441 cha_->UpdateAfterLoadingOf(h_new_class);
5442 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005443
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005444 // This will notify waiters on temp class that saw the not yet resolved class in the
5445 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005446 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005447
Vladimir Marko2c64a832018-01-04 11:31:56 +00005448 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005449 // This will notify waiters on new_class that saw the not yet resolved
5450 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005451 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005452 // Return the new class.
5453 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005454 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005455 return true;
5456}
5457
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005458bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005459 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005460 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005461 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5462 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005463 // Check that a class does not inherit from itself directly.
5464 //
5465 // TODO: This is a cheap check to detect the straightforward case
5466 // of a class extending itself (b/28685551), but we should do a
5467 // proper cycle detection on loaded classes, to detect all cases
5468 // of class circularity errors (b/28830038).
5469 if (super_class_idx == class_def.class_idx_) {
5470 ThrowClassCircularityError(klass.Get(),
5471 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005472 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005473 return false;
5474 }
5475
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005476 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005477 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005478 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005479 return false;
5480 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005481 // Verify
5482 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005483 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005484 super_class->PrettyDescriptor().c_str(),
5485 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005486 return false;
5487 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005488 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005489 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005490 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005491 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005492 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005493 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005494 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005495 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005496 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005497 DCHECK(Thread::Current()->IsExceptionPending());
5498 return false;
5499 }
5500 // Verify
5501 if (!klass->CanAccess(interface)) {
5502 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005503 ThrowIllegalAccessError(klass.Get(),
5504 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005505 interface->PrettyDescriptor().c_str(),
5506 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005507 return false;
5508 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005509 }
5510 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005511 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005512 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005513 return true;
5514}
5515
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005516bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005517 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005518 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005519 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005520 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005521 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005522 return false;
5523 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005524 return true;
5525 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005526 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005527 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005528 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005529 return false;
5530 }
5531 // Verify
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005532 if (klass->IsInterface() && super != GetClassRoot(kJavaLangObject)) {
5533 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5534 return false;
5535 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005536 if (super->IsFinal()) {
5537 ThrowVerifyError(klass.Get(),
5538 "Superclass %s of %s is declared final",
5539 super->PrettyDescriptor().c_str(),
5540 klass->PrettyDescriptor().c_str());
5541 return false;
5542 }
5543 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005544 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005545 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005546 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005547 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005548 return false;
5549 }
5550 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005551 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005552 super->PrettyDescriptor().c_str(),
5553 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005554 return false;
5555 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005556
Brian Carlstromf3632832014-05-20 15:36:53 -07005557 // Inherit kAccClassIsFinalizable from the superclass in case this
5558 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005559 if (super->IsFinalizable()) {
5560 klass->SetFinalizable();
5561 }
5562
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005563 // Inherit class loader flag form super class.
5564 if (super->IsClassLoaderClass()) {
5565 klass->SetClassLoaderClass();
5566 }
5567
Elliott Hughes2da50362011-10-10 16:57:08 -07005568 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005569 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005570 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005571 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005572 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005573 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005574 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005575 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005576 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005577 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005578 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005579 return false;
5580 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005581
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005582 if (kIsDebugBuild) {
5583 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005584 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005585 CHECK(super->IsResolved());
5586 super = super->GetSuperClass();
5587 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005588 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005589 return true;
5590}
5591
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005592// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005593bool ClassLinker::LinkMethods(Thread* self,
5594 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005595 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005596 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005597 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005598 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005599 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5600 // need to have default methods be in the virtuals array of each class but we don't set that up
5601 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005602 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005603 // Link virtual methods then interface methods.
5604 // We set up the interface lookup table first because we need it to determine if we need to update
5605 // any vtable entries with new default method implementations.
5606 return SetupInterfaceLookupTable(self, klass, interfaces)
5607 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005608 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005609}
5610
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005611// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5612// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5613// caches in the implementation below.
5614class MethodNameAndSignatureComparator FINAL : public ValueObject {
5615 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005616 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005617 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005618 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5619 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005620 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005621 }
5622
5623 const char* GetName() {
5624 if (name_ == nullptr) {
5625 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5626 }
5627 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005628 }
5629
Mathieu Chartiere401d142015-04-22 13:56:20 -07005630 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005631 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005632 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005633 const DexFile* other_dex_file = other->GetDexFile();
5634 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5635 if (dex_file_ == other_dex_file) {
5636 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5637 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005638 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005639 uint32_t other_name_len;
5640 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5641 &other_name_len);
5642 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5643 return false;
5644 }
5645 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5646 }
5647
5648 private:
5649 // Dex file for the method to compare against.
5650 const DexFile* const dex_file_;
5651 // MethodId for the method to compare against.
5652 const DexFile::MethodId* const mid_;
5653 // Lazily computed name from the dex file's strings.
5654 const char* name_;
5655 // Lazily computed name length.
5656 uint32_t name_len_;
5657};
5658
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005659class LinkVirtualHashTable {
5660 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005661 LinkVirtualHashTable(Handle<mirror::Class> klass,
5662 size_t hash_size,
5663 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005664 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005665 : klass_(klass),
5666 hash_size_(hash_size),
5667 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005668 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005669 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5670 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005671
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005672 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005673 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5674 virtual_method_index, image_pointer_size_);
5675 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005676 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005677 uint32_t index = hash % hash_size_;
5678 // Linear probe until we have an empty slot.
5679 while (hash_table_[index] != invalid_index_) {
5680 if (++index == hash_size_) {
5681 index = 0;
5682 }
5683 }
5684 hash_table_[index] = virtual_method_index;
5685 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005686
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005687 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005688 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005689 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005690 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005691 size_t index = hash % hash_size_;
5692 while (true) {
5693 const uint32_t value = hash_table_[index];
5694 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5695 // the block and can safely assume not found.
5696 if (value == invalid_index_) {
5697 break;
5698 }
5699 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005700 ArtMethod* virtual_method =
5701 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5702 if (comparator->HasSameNameAndSignature(
5703 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005704 hash_table_[index] = removed_index_;
5705 return value;
5706 }
5707 }
5708 if (++index == hash_size_) {
5709 index = 0;
5710 }
5711 }
5712 return GetNotFoundIndex();
5713 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005714
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005715 static uint32_t GetNotFoundIndex() {
5716 return invalid_index_;
5717 }
5718
5719 private:
5720 static const uint32_t invalid_index_;
5721 static const uint32_t removed_index_;
5722
5723 Handle<mirror::Class> klass_;
5724 const size_t hash_size_;
5725 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005726 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005727};
5728
5729const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5730const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5731
Stephen Hines1ddd9132017-02-08 01:51:18 -08005732bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005733 Thread* self,
5734 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005735 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005736 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005737 if (klass->IsInterface()) {
5738 // No vtable.
5739 if (!IsUint<16>(num_virtual_methods)) {
5740 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5741 return false;
5742 }
5743 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005744 // Assign each method an IMT index and set the default flag.
5745 for (size_t i = 0; i < num_virtual_methods; ++i) {
5746 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5747 m->SetMethodIndex(i);
5748 if (!m->IsAbstract()) {
5749 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5750 has_defaults = true;
5751 }
5752 }
5753 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5754 // during initialization. This is a performance optimization. We could simply traverse the
5755 // virtual_methods_ array again during initialization.
5756 if (has_defaults) {
5757 klass->SetHasDefaultMethods();
5758 }
5759 return true;
5760 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005761 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5762 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005763 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005764 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005765 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005766 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005767 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005768 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005769 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005770 return false;
5771 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005772 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005773 vtable->SetElementPtrSize(
5774 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005775 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005776 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5777 // might give us new default methods). If no new interfaces then we can skip the rest since
5778 // the class cannot override any of the super-class's methods. This is required for
5779 // correctness since without it we might not update overridden default method vtable entries
5780 // correctly.
5781 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005782 klass->SetVTable(vtable.Get());
5783 return true;
5784 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005785 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005786 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005787 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005788 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005789 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5790 // might give us new default methods). See comment above.
5791 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005792 klass->SetVTable(super_vtable);
5793 return true;
5794 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005795 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5796 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005797 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005798 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005799 return false;
5800 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005801 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005802 // How the algorithm works:
5803 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5804 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5805 // method which has not been matched to a vtable method, and j if the virtual method at the
5806 // index overrode the super virtual method at index j.
5807 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5808 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5809 // the need for the initial vtable which we later shrink back down).
5810 // 3. Add non overridden methods to the end of the vtable.
5811 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005812 // + 1 so that even if we only have new default methods we will still be able to use this hash
5813 // table (i.e. it will never have 0 size).
5814 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005815 uint32_t* hash_table_ptr;
5816 std::unique_ptr<uint32_t[]> hash_heap_storage;
5817 if (hash_table_size <= kMaxStackHash) {
5818 hash_table_ptr = reinterpret_cast<uint32_t*>(
5819 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5820 } else {
5821 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5822 hash_table_ptr = hash_heap_storage.get();
5823 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005824 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005825 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005826 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005827 DCHECK(klass->GetVirtualMethodDuringLinking(
5828 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005829 hash_table.Add(i);
5830 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005831 // 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 -07005832 // the hash table.
5833 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005834 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005835 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005836 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5837 super_method->GetAccessFlags())) {
5838 // Continue on to the next method since this one is package private and canot be overridden.
5839 // Before Android 4.1, the package-private method super_method might have been incorrectly
5840 // overridden.
5841 continue;
5842 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005843 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005844 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005845 // We remove the method so that subsequent lookups will be faster by making the hash-map
5846 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005847 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5848 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005849 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5850 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005851 if (super_method->IsFinal()) {
5852 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5853 virtual_method->PrettyMethod().c_str(),
5854 super_method->GetDeclaringClassDescriptor());
5855 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005856 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005857 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5858 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005859 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005860 // We didn't directly override this method but we might through default methods...
5861 // Check for default method update.
5862 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005863 switch (FindDefaultMethodImplementation(self,
5864 super_method,
5865 klass,
5866 /*out*/&default_method)) {
5867 case DefaultMethodSearchResult::kDefaultConflict: {
5868 // A conflict was found looking for default methods. Note this (assuming it wasn't
5869 // pre-existing) in the translations map.
5870 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5871 // Don't generate another conflict method to reduce memory use as an optimization.
5872 default_translations->insert(
5873 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5874 }
5875 break;
5876 }
5877 case DefaultMethodSearchResult::kAbstractFound: {
5878 // No conflict but method is abstract.
5879 // We note that this vtable entry must be made abstract.
5880 if (UNLIKELY(!super_method->IsAbstract())) {
5881 default_translations->insert(
5882 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5883 }
5884 break;
5885 }
5886 case DefaultMethodSearchResult::kDefaultFound: {
5887 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5888 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5889 // Found a default method implementation that is new.
5890 // TODO Refactor this add default methods to virtuals here and not in
5891 // LinkInterfaceMethods maybe.
5892 // The problem is default methods might override previously present
5893 // default-method or miranda-method vtable entries from the superclass.
5894 // Unfortunately we need these to be entries in this class's virtuals. We do not
5895 // give these entries there until LinkInterfaceMethods so we pass this map around
5896 // to let it know which vtable entries need to be updated.
5897 // Make a note that vtable entry j must be updated, store what it needs to be updated
5898 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5899 // then.
5900 default_translations->insert(
5901 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005902 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5903 << " overridden by default "
5904 << default_method->PrettyMethod()
5905 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005906 }
5907 break;
5908 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005909 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005910 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005911 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005912 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005913 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005914 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005915 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005916 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5917 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005918 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005919 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005920 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005921 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005922 local_method->SetMethodIndex(actual_count);
5923 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005924 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005925 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005926 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005927 return false;
5928 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005929 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005930 CHECK_LE(actual_count, max_count);
5931 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005932 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005933 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005934 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005935 return false;
5936 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005937 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005938 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005939 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005940 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005941 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005942 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5943 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005944 return false;
5945 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005946 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005947 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005948 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005949 return false;
5950 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005951 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005952 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5953 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005954 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005955 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005956 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005957 }
5958 return true;
5959}
5960
Alex Light9139e002015-10-09 15:59:48 -07005961// Determine if the given iface has any subinterface in the given list that declares the method
5962// specified by 'target'.
5963//
5964// Arguments
5965// - self: The thread we are running on
5966// - target: A comparator that will match any method that overrides the method we are checking for
5967// - iftable: The iftable we are searching for an overriding method on.
5968// - ifstart: The index of the interface we are checking to see if anything overrides
5969// - iface: The interface we are checking to see if anything overrides.
5970// - image_pointer_size:
5971// The image pointer size.
5972//
5973// Returns
5974// - True: There is some method that matches the target comparator defined in an interface that
5975// is a subtype of iface.
5976// - False: There is no method that matches the target comparator in any interface that is a subtype
5977// of iface.
5978static bool ContainsOverridingMethodOf(Thread* self,
5979 MethodNameAndSignatureComparator& target,
5980 Handle<mirror::IfTable> iftable,
5981 size_t ifstart,
5982 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005983 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005984 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005985 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005986 DCHECK(iface != nullptr);
5987 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07005988 DCHECK_GE(ifstart, 0u);
5989 DCHECK_LT(ifstart, iftable->Count());
5990 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5991 DCHECK(iface->IsInterface());
5992
5993 size_t iftable_count = iftable->Count();
5994 StackHandleScope<1> hs(self);
5995 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5996 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5997 // Skip ifstart since our current interface obviously cannot override itself.
5998 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005999 // Iterate through every method on this interface. The order does not matter.
6000 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006001 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006002 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006003 // Check if the i'th interface is a subtype of this one.
6004 if (iface->IsAssignableFrom(current_iface.Get())) {
6005 return true;
6006 }
6007 break;
6008 }
6009 }
6010 }
6011 return false;
6012}
6013
Alex Lighteb7c1442015-08-31 13:17:42 -07006014// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006015// out_default_method and returns kDefaultFound on success. If no default method was found return
6016// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6017// default_method conflict) it will return kDefaultConflict.
6018ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6019 Thread* self,
6020 ArtMethod* target_method,
6021 Handle<mirror::Class> klass,
6022 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006023 DCHECK(self != nullptr);
6024 DCHECK(target_method != nullptr);
6025 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006026
6027 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006028
6029 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6030 // table. This lets us walk the table backwards when searching for default methods. The first one
6031 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6032 // track of it and then continue checking all other interfaces, since we need to throw an error if
6033 // we encounter conflicting default method implementations (one is not a subtype of the other).
6034 //
6035 // The order of unrelated interfaces does not matter and is not defined.
6036 size_t iftable_count = klass->GetIfTableCount();
6037 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006038 // No interfaces. We have already reset out to null so just return kAbstractFound.
6039 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006040 }
6041
Alex Light9139e002015-10-09 15:59:48 -07006042 StackHandleScope<3> hs(self);
6043 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006044 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006045 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006046 MethodNameAndSignatureComparator target_name_comparator(
6047 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6048 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006049 for (size_t k = iftable_count; k != 0; ) {
6050 --k;
6051
Alex Lighteb7c1442015-08-31 13:17:42 -07006052 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006053
6054 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006055 // Iterate through every declared method on this interface. The order does not matter.
6056 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6057 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006058 // Skip abstract methods and methods with different names.
6059 if (current_method->IsAbstract() ||
6060 !target_name_comparator.HasSameNameAndSignature(
6061 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6062 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006063 } else if (!current_method->IsPublic()) {
6064 // The verifier should have caught the non-public method for dex version 37. Just warn and
6065 // skip it since this is from before default-methods so we don't really need to care that it
6066 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006067 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6068 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006069 << "This will be a fatal error in subsequent versions of android. "
6070 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006071 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006072 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006073 // We have multiple default impls of the same method. This is a potential default conflict.
6074 // We need to check if this possibly conflicting method is either a superclass of the chosen
6075 // default implementation or is overridden by a non-default interface method. In either case
6076 // there is no conflict.
6077 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6078 !ContainsOverridingMethodOf(self,
6079 target_name_comparator,
6080 iftable,
6081 k,
6082 iface,
6083 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006084 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006085 << current_method->PrettyMethod() << " and "
6086 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6087 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006088 *out_default_method = nullptr;
6089 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006090 } else {
6091 break; // Continue checking at the next interface.
6092 }
6093 } else {
Alex Light9139e002015-10-09 15:59:48 -07006094 // chosen_iface == null
6095 if (!ContainsOverridingMethodOf(self,
6096 target_name_comparator,
6097 iftable,
6098 k,
6099 iface,
6100 image_pointer_size_)) {
6101 // Don't set this as the chosen interface if something else is overriding it (because that
6102 // other interface would be potentially chosen instead if it was default). If the other
6103 // interface was abstract then we wouldn't select this interface as chosen anyway since
6104 // the abstract method masks it.
6105 *out_default_method = current_method;
6106 chosen_iface.Assign(iface.Get());
6107 // We should now finish traversing the graph to find if we have default methods that
6108 // conflict.
6109 } else {
David Sehr709b0702016-10-13 09:12:37 -07006110 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6111 << "' was "
6112 << "skipped because it was overridden by an abstract method in a "
6113 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006114 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006115 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006116 break;
6117 }
6118 }
Alex Light9139e002015-10-09 15:59:48 -07006119 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006120 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6121 << "' selected "
6122 << "as the implementation for '" << target_method->PrettyMethod()
6123 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006124 return DefaultMethodSearchResult::kDefaultFound;
6125 } else {
6126 return DefaultMethodSearchResult::kAbstractFound;
6127 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006128}
6129
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006130ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006131 ArtMethod* conflict_method,
6132 ArtMethod* interface_method,
6133 ArtMethod* method,
6134 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006135 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006136 Runtime* const runtime = Runtime::Current();
6137 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6138 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6139
6140 // Create a new entry if the existing one is the shared conflict method.
6141 ArtMethod* new_conflict_method = new_entry
6142 ? runtime->CreateImtConflictMethod(linear_alloc)
6143 : conflict_method;
6144
6145 // Allocate a new table. Note that we will leak this table at the next conflict,
6146 // but that's a tradeoff compared to making the table fixed size.
6147 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006148 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6149 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006150 if (data == nullptr) {
6151 LOG(ERROR) << "Failed to allocate conflict table";
6152 return conflict_method;
6153 }
6154 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6155 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006156 method,
6157 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006158
6159 // Do a fence to ensure threads see the data in the table before it is assigned
6160 // to the conflict method.
6161 // Note that there is a race in the presence of multiple threads and we may leak
6162 // memory from the LinearAlloc, but that's a tradeoff compared to using
6163 // atomic operations.
6164 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006165 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006166 return new_conflict_method;
6167}
6168
Vladimir Marko921094a2017-01-12 18:37:06 +00006169bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6170 Handle<mirror::Class> klass,
6171 Handle<mirror::IfTable> iftable) {
6172 DCHECK(!klass->IsInterface());
6173 const bool has_superclass = klass->HasSuperClass();
6174 const bool extend_super_iftable = has_superclass;
6175 const size_t ifcount = klass->GetIfTableCount();
6176 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6177 for (size_t i = 0; i < ifcount; ++i) {
6178 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6179 if (num_methods > 0) {
6180 const bool is_super = i < super_ifcount;
6181 // This is an interface implemented by a super-class. Therefore we can just copy the method
6182 // array from the superclass.
6183 const bool super_interface = is_super && extend_super_iftable;
6184 ObjPtr<mirror::PointerArray> method_array;
6185 if (super_interface) {
6186 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6187 DCHECK(if_table != nullptr);
6188 DCHECK(if_table->GetMethodArray(i) != nullptr);
6189 // If we are working on a super interface, try extending the existing method array.
6190 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6191 } else {
6192 method_array = AllocPointerArray(self, num_methods);
6193 }
6194 if (UNLIKELY(method_array == nullptr)) {
6195 self->AssertPendingOOMException();
6196 return false;
6197 }
6198 iftable->SetMethodArray(i, method_array);
6199 }
6200 }
6201 return true;
6202}
6203
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006204void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6205 ArtMethod* imt_conflict_method,
6206 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006207 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006208 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006209 // Place method in imt if entry is empty, place conflict otherwise.
6210 if (*imt_ref == unimplemented_method) {
6211 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006212 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006213 // If we are not a conflict and we have the same signature and name as the imt
6214 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006215 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6216 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006217 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006218 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006219 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006220 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006221 *imt_ref = current_method;
6222 } else {
Alex Light9139e002015-10-09 15:59:48 -07006223 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006224 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006225 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006226 } else {
6227 // Place the default conflict method. Note that there may be an existing conflict
6228 // method in the IMT, but it could be one tailored to the super class, with a
6229 // specific ImtConflictTable.
6230 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006231 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006232 }
6233}
6234
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006235void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006236 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6237 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006238 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006239 Runtime* const runtime = Runtime::Current();
6240 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6241 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006242 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006243 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006244 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006245 FillIMTFromIfTable(klass->GetIfTable(),
6246 unimplemented_method,
6247 conflict_method,
6248 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006249 /*create_conflict_tables*/true,
6250 /*ignore_copied_methods*/false,
6251 &new_conflict,
6252 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006253 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006254 if (!klass->ShouldHaveImt()) {
6255 return;
6256 }
6257 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6258 // we can just use the same pointer.
6259 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006260 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006261 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6262 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6263 bool same = true;
6264 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6265 ArtMethod* method = imt_data[i];
6266 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6267 if (method != super_method) {
6268 bool is_conflict_table = method->IsRuntimeMethod() &&
6269 method != unimplemented_method &&
6270 method != conflict_method;
6271 // Verify conflict contents.
6272 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6273 super_method != unimplemented_method &&
6274 super_method != conflict_method;
6275 if (!is_conflict_table || !super_conflict_table) {
6276 same = false;
6277 } else {
6278 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6279 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6280 same = same && table1->Equals(table2, image_pointer_size_);
6281 }
6282 }
6283 }
6284 if (same) {
6285 imt = super_imt;
6286 }
6287 }
6288 if (imt == nullptr) {
6289 imt = klass->GetImt(image_pointer_size_);
6290 DCHECK(imt != nullptr);
6291 imt->Populate(imt_data, image_pointer_size_);
6292 } else {
6293 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006294 }
6295}
6296
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006297ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6298 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006299 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006300 void* data = linear_alloc->Alloc(Thread::Current(),
6301 ImtConflictTable::ComputeSize(count,
6302 image_pointer_size));
6303 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6304}
6305
6306ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6307 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6308}
6309
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006310void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006311 ArtMethod* unimplemented_method,
6312 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006313 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006314 bool create_conflict_tables,
6315 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006316 /*out*/bool* new_conflict,
6317 /*out*/ArtMethod** imt) {
6318 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006319 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006320 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006321 const size_t num_virtuals = interface->NumVirtualMethods();
6322 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6323 // Virtual methods can be larger than the if table methods if there are default methods.
6324 DCHECK_GE(num_virtuals, method_array_count);
6325 if (kIsDebugBuild) {
6326 if (klass->IsInterface()) {
6327 DCHECK_EQ(method_array_count, 0u);
6328 } else {
6329 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6330 }
6331 }
6332 if (method_array_count == 0) {
6333 continue;
6334 }
6335 auto* method_array = if_table->GetMethodArray(i);
6336 for (size_t j = 0; j < method_array_count; ++j) {
6337 ArtMethod* implementation_method =
6338 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6339 if (ignore_copied_methods && implementation_method->IsCopied()) {
6340 continue;
6341 }
6342 DCHECK(implementation_method != nullptr);
6343 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6344 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6345 // or interface methods in the IMT here they will not create extra conflicts since we compare
6346 // names and signatures in SetIMTRef.
6347 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006348 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006349
6350 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6351 // the same implementation method, keep track of this to avoid creating a conflict table in
6352 // this case.
6353
6354 // Conflict table size for each IMT slot.
6355 ++conflict_counts[imt_index];
6356
6357 SetIMTRef(unimplemented_method,
6358 imt_conflict_method,
6359 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006360 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006361 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006362 }
6363 }
6364
6365 if (create_conflict_tables) {
6366 // Create the conflict tables.
6367 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006368 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006369 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006370 if (imt[i] == imt_conflict_method) {
6371 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6372 if (new_table != nullptr) {
6373 ArtMethod* new_conflict_method =
6374 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6375 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6376 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006377 } else {
6378 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006379 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006380 }
6381 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006382 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006383 }
6384 }
6385
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006386 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006387 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006388 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6389 // Virtual methods can be larger than the if table methods if there are default methods.
6390 if (method_array_count == 0) {
6391 continue;
6392 }
6393 auto* method_array = if_table->GetMethodArray(i);
6394 for (size_t j = 0; j < method_array_count; ++j) {
6395 ArtMethod* implementation_method =
6396 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6397 if (ignore_copied_methods && implementation_method->IsCopied()) {
6398 continue;
6399 }
6400 DCHECK(implementation_method != nullptr);
6401 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006402 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006403 if (!imt[imt_index]->IsRuntimeMethod() ||
6404 imt[imt_index] == unimplemented_method ||
6405 imt[imt_index] == imt_conflict_method) {
6406 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006407 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006408 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6409 const size_t num_entries = table->NumEntries(image_pointer_size_);
6410 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6411 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006412 }
6413 }
6414 }
6415}
6416
Alex Lighteb7c1442015-08-31 13:17:42 -07006417// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6418// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006419static bool NotSubinterfaceOfAny(
6420 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6421 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006422 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006423 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006424 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006425 for (ObjPtr<mirror::Class> c : classes) {
6426 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006427 return false;
6428 }
6429 }
6430 return true;
6431}
6432
6433// Fills in and flattens the interface inheritance hierarchy.
6434//
6435// By the end of this function all interfaces in the transitive closure of to_process are added to
6436// the iftable and every interface precedes all of its sub-interfaces in this list.
6437//
6438// all I, J: Interface | I <: J implies J precedes I
6439//
6440// (note A <: B means that A is a subtype of B)
6441//
6442// This returns the total number of items in the iftable. The iftable might be resized down after
6443// this call.
6444//
6445// We order this backwards so that we do not need to reorder superclass interfaces when new
6446// interfaces are added in subclass's interface tables.
6447//
6448// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6449// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6450// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6451// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006452static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 size_t super_ifcount,
6454 std::vector<mirror::Class*> to_process)
6455 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006456 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006457 // This is the set of all class's already in the iftable. Used to make checking if a class has
6458 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006459 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006460 // The first super_ifcount elements are from the superclass. We note that they are already added.
6461 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006462 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006463 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6464 classes_in_iftable.insert(iface);
6465 }
6466 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006467 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006468 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6469 // At this point in the loop current-iface-list has the invariant that:
6470 // for every pair of interfaces I,J within it:
6471 // if index_of(I) < index_of(J) then I is not a subtype of J
6472
6473 // If we have already seen this element then all of its super-interfaces must already be in the
6474 // current-iface-list so we can skip adding it.
6475 if (!ContainsElement(classes_in_iftable, interface)) {
6476 // We haven't seen this interface so add all of its super-interfaces onto the
6477 // current-iface-list, skipping those already on it.
6478 int32_t ifcount = interface->GetIfTableCount();
6479 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006480 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006481 if (!ContainsElement(classes_in_iftable, super_interface)) {
6482 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6483 classes_in_iftable.insert(super_interface);
6484 iftable->SetInterface(filled_ifcount, super_interface);
6485 filled_ifcount++;
6486 }
6487 }
6488 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6489 // Place this interface onto the current-iface-list after all of its super-interfaces.
6490 classes_in_iftable.insert(interface);
6491 iftable->SetInterface(filled_ifcount, interface);
6492 filled_ifcount++;
6493 } else if (kIsDebugBuild) {
6494 // Check all super-interfaces are already in the list.
6495 int32_t ifcount = interface->GetIfTableCount();
6496 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006497 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006498 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006499 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6500 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006501 }
6502 }
6503 }
6504 if (kIsDebugBuild) {
6505 // Check that the iftable is ordered correctly.
6506 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006507 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006508 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006509 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006510 // !(if_a <: if_b)
6511 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006512 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6513 << ") extends "
6514 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006515 << "interface list.";
6516 }
6517 }
6518 }
6519 return filled_ifcount;
6520}
6521
6522bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6523 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6524 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006525 const bool has_superclass = klass->HasSuperClass();
6526 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006527 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006528 const size_t num_interfaces =
6529 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006530 if (num_interfaces == 0) {
6531 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006532 if (LIKELY(has_superclass)) {
6533 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6534 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006535 // Class implements no interfaces.
6536 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006537 return true;
6538 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006539 // Class implements same interfaces as parent, are any of these not marker interfaces?
6540 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006541 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006542 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006543 if (super_iftable->GetMethodArrayCount(i) > 0) {
6544 has_non_marker_interface = true;
6545 break;
6546 }
6547 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006548 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006549 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006550 klass->SetIfTable(super_iftable);
6551 return true;
6552 }
6553 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006554 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006555 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006556 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006557 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006558 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006559 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006560 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006561 if (UNLIKELY(!interface->IsInterface())) {
6562 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006563 ThrowIncompatibleClassChangeError(klass.Get(),
6564 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006565 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006566 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6567 return false;
6568 }
6569 ifcount += interface->GetIfTableCount();
6570 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006571 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006572 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006573 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006574 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006575 return false;
6576 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006577 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006578 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006579 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006580 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006581 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006582 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006584 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006585
6586 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6587 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6588 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006589 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006590
6591 size_t new_ifcount;
6592 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006593 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006594 std::vector<mirror::Class*> to_add;
6595 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006596 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006597 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006598 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006599 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006600
6601 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006602 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006603
Ian Rogers7b078e82014-09-10 14:44:24 -07006604 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006605
Ian Rogersb52b01a2012-01-12 17:01:38 -08006606 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006607 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006608 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006609 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006610 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006611 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006612 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006613 return false;
6614 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006615 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006616 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006617 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006618 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006619 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006620 return true;
6621}
6622
Alex Light1f3925d2016-09-07 12:04:20 -07006623// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6624// of methods must be unique.
6625static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6626 return nullptr;
6627}
6628
6629template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006630static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006631 const ScopedArenaVector<ArtMethod*>& list,
6632 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006633 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006634 for (ArtMethod* method : list) {
6635 if (cmp.HasSameNameAndSignature(method)) {
6636 return method;
6637 }
6638 }
Alex Light1f3925d2016-09-07 12:04:20 -07006639 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006640}
6641
Alex Light1f3925d2016-09-07 12:04:20 -07006642// Check that all vtable entries are present in this class's virtuals or are the same as a
6643// superclasses vtable entry.
6644static void CheckClassOwnsVTableEntries(Thread* self,
6645 Handle<mirror::Class> klass,
6646 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006647 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006648 StackHandleScope<2> hs(self);
6649 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006650 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006651 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006652 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006653 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6654 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6655 CHECK(m != nullptr);
6656
Alex Lighta41a30782017-03-29 11:33:19 -07006657 if (m->GetMethodIndexDuringLinking() != i) {
6658 LOG(WARNING) << m->PrettyMethod()
6659 << " has an unexpected method index for its spot in the vtable for class"
6660 << klass->PrettyClass();
6661 }
Alex Lighte64300b2015-12-15 15:02:47 -08006662 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6663 auto is_same_method = [m] (const ArtMethod& meth) {
6664 return &meth == m;
6665 };
Alex Light3f980532017-03-17 15:10:32 -07006666 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6667 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6668 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6669 << klass->PrettyClass() << " or any of its superclasses!";
6670 }
Alex Lighte64300b2015-12-15 15:02:47 -08006671 }
6672}
6673
Alex Light1f3925d2016-09-07 12:04:20 -07006674// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6675// method is overridden in a subclass.
6676static void CheckVTableHasNoDuplicates(Thread* self,
6677 Handle<mirror::Class> klass,
6678 PointerSize pointer_size)
6679 REQUIRES_SHARED(Locks::mutator_lock_) {
6680 StackHandleScope<1> hs(self);
6681 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6682 int32_t num_entries = vtable->GetLength();
6683 for (int32_t i = 0; i < num_entries; i++) {
6684 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6685 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6686 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6687 vtable_entry->GetAccessFlags())) {
6688 continue;
6689 }
6690 MethodNameAndSignatureComparator name_comparator(
6691 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006692 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006693 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006694 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6695 other_entry->GetAccessFlags())) {
6696 continue;
6697 }
Alex Light3f980532017-03-17 15:10:32 -07006698 if (vtable_entry == other_entry ||
6699 name_comparator.HasSameNameAndSignature(
6700 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6701 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6702 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6703 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6704 << other_entry->PrettyMethod() << " (0x" << std::hex
6705 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6706 }
Alex Light1f3925d2016-09-07 12:04:20 -07006707 }
6708 }
6709}
6710
6711static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6712 REQUIRES_SHARED(Locks::mutator_lock_) {
6713 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6714 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6715}
6716
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006717void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6718 ArtMethod* unimplemented_method,
6719 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006720 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006721 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006722 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006723 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006724 if (super_class->ShouldHaveImt()) {
6725 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6726 for (size_t i = 0; i < ImTable::kSize; ++i) {
6727 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006728 }
6729 } else {
6730 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006731 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006732 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006733 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006734 FillIMTFromIfTable(if_table,
6735 unimplemented_method,
6736 imt_conflict_method,
6737 klass.Get(),
6738 /*create_conflict_table*/false,
6739 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006740 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006741 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006742 }
6743 }
6744}
6745
Vladimir Marko921094a2017-01-12 18:37:06 +00006746class ClassLinker::LinkInterfaceMethodsHelper {
6747 public:
6748 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6749 Handle<mirror::Class> klass,
6750 Thread* self,
6751 Runtime* runtime)
6752 : class_linker_(class_linker),
6753 klass_(klass),
6754 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6755 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6756 self_(self),
6757 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6758 allocator_(&stack_),
6759 default_conflict_methods_(allocator_.Adapter()),
6760 overriding_default_conflict_methods_(allocator_.Adapter()),
6761 miranda_methods_(allocator_.Adapter()),
6762 default_methods_(allocator_.Adapter()),
6763 overriding_default_methods_(allocator_.Adapter()),
6764 move_table_(allocator_.Adapter()) {
6765 }
6766
6767 ArtMethod* FindMethod(ArtMethod* interface_method,
6768 MethodNameAndSignatureComparator& interface_name_comparator,
6769 ArtMethod* vtable_impl)
6770 REQUIRES_SHARED(Locks::mutator_lock_);
6771
6772 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6773 MethodNameAndSignatureComparator& interface_name_comparator)
6774 REQUIRES_SHARED(Locks::mutator_lock_);
6775
6776 bool HasNewVirtuals() const {
6777 return !(miranda_methods_.empty() &&
6778 default_methods_.empty() &&
6779 overriding_default_methods_.empty() &&
6780 overriding_default_conflict_methods_.empty() &&
6781 default_conflict_methods_.empty());
6782 }
6783
6784 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6785
6786 ObjPtr<mirror::PointerArray> UpdateVtable(
6787 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6788 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6789
6790 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6791
6792 void UpdateIMT(ArtMethod** out_imt);
6793
6794 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6795 if (kIsDebugBuild) {
6796 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6797 // Check that there are no stale methods are in the dex cache array.
6798 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6799 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006800 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6801 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006802 CHECK(move_table_.find(m) == move_table_.end() ||
6803 // The original versions of copied methods will still be present so allow those too.
6804 // Note that if the first check passes this might fail to GetDeclaringClass().
6805 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6806 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6807 [m] (ArtMethod& meth) {
6808 return &meth == m;
6809 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6810 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6811 }
6812 }
6813 }
6814
6815 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6816 LengthPrefixedArray<ArtMethod>* methods) {
6817 if (kIsDebugBuild) {
6818 CHECK(methods != nullptr);
6819 // Put some random garbage in old methods to help find stale pointers.
6820 if (methods != old_methods && old_methods != nullptr) {
6821 // Need to make sure the GC is not running since it could be scanning the methods we are
6822 // about to overwrite.
6823 ScopedThreadStateChange tsc(self_, kSuspended);
6824 gc::ScopedGCCriticalSection gcs(self_,
6825 gc::kGcCauseClassLinker,
6826 gc::kCollectorTypeClassLinker);
6827 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6828 method_size_,
6829 method_alignment_);
6830 memset(old_methods, 0xFEu, old_size);
6831 }
6832 }
6833 }
6834
6835 private:
6836 size_t NumberOfNewVirtuals() const {
6837 return miranda_methods_.size() +
6838 default_methods_.size() +
6839 overriding_default_conflict_methods_.size() +
6840 overriding_default_methods_.size() +
6841 default_conflict_methods_.size();
6842 }
6843
6844 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6845 return !klass_->IsInterface();
6846 }
6847
6848 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6849 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6850 << "Interfaces should only have default-conflict methods appended to them.";
6851 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6852 << miranda_methods_.size()
6853 << " default_methods=" << default_methods_.size()
6854 << " overriding_default_methods=" << overriding_default_methods_.size()
6855 << " default_conflict_methods=" << default_conflict_methods_.size()
6856 << " overriding_default_conflict_methods="
6857 << overriding_default_conflict_methods_.size();
6858 }
6859
6860 ClassLinker* class_linker_;
6861 Handle<mirror::Class> klass_;
6862 size_t method_alignment_;
6863 size_t method_size_;
6864 Thread* const self_;
6865
6866 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6867 // the virtual methods array.
6868 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6869 // during cross compilation.
6870 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6871 ArenaStack stack_;
6872 ScopedArenaAllocator allocator_;
6873
6874 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6875 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6876 ScopedArenaVector<ArtMethod*> miranda_methods_;
6877 ScopedArenaVector<ArtMethod*> default_methods_;
6878 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6879
6880 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6881};
6882
6883ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6884 ArtMethod* interface_method,
6885 MethodNameAndSignatureComparator& interface_name_comparator,
6886 ArtMethod* vtable_impl) {
6887 ArtMethod* current_method = nullptr;
6888 switch (class_linker_->FindDefaultMethodImplementation(self_,
6889 interface_method,
6890 klass_,
6891 /*out*/&current_method)) {
6892 case DefaultMethodSearchResult::kDefaultConflict: {
6893 // Default method conflict.
6894 DCHECK(current_method == nullptr);
6895 ArtMethod* default_conflict_method = nullptr;
6896 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6897 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6898 default_conflict_method = vtable_impl;
6899 } else {
6900 // See if we already have a conflict method for this method.
6901 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6902 interface_name_comparator,
6903 default_conflict_methods_,
6904 overriding_default_conflict_methods_);
6905 if (LIKELY(preexisting_conflict != nullptr)) {
6906 // We already have another conflict we can reuse.
6907 default_conflict_method = preexisting_conflict;
6908 } else {
6909 // Note that we do this even if we are an interface since we need to create this and
6910 // cannot reuse another classes.
6911 // Create a new conflict method for this to use.
6912 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6913 new(default_conflict_method) ArtMethod(interface_method,
6914 class_linker_->GetImagePointerSize());
6915 if (vtable_impl == nullptr) {
6916 // Save the conflict method. We need to add it to the vtable.
6917 default_conflict_methods_.push_back(default_conflict_method);
6918 } else {
6919 // Save the conflict method but it is already in the vtable.
6920 overriding_default_conflict_methods_.push_back(default_conflict_method);
6921 }
6922 }
6923 }
6924 current_method = default_conflict_method;
6925 break;
6926 } // case kDefaultConflict
6927 case DefaultMethodSearchResult::kDefaultFound: {
6928 DCHECK(current_method != nullptr);
6929 // Found a default method.
6930 if (vtable_impl != nullptr &&
6931 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6932 // We found a default method but it was the same one we already have from our
6933 // superclass. Don't bother adding it to our vtable again.
6934 current_method = vtable_impl;
6935 } else if (LIKELY(FillTables())) {
6936 // Interfaces don't need to copy default methods since they don't have vtables.
6937 // Only record this default method if it is new to save space.
6938 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6939 // would make lookup for interface super much faster. (We would only need to scan
6940 // the iftable to find if there is a NSME or AME.)
6941 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6942 default_methods_,
6943 overriding_default_methods_);
6944 if (old == nullptr) {
6945 // We found a default method implementation and there were no conflicts.
6946 if (vtable_impl == nullptr) {
6947 // Save the default method. We need to add it to the vtable.
6948 default_methods_.push_back(current_method);
6949 } else {
6950 // Save the default method but it is already in the vtable.
6951 overriding_default_methods_.push_back(current_method);
6952 }
6953 } else {
6954 CHECK(old == current_method) << "Multiple default implementations selected!";
6955 }
6956 }
6957 break;
6958 } // case kDefaultFound
6959 case DefaultMethodSearchResult::kAbstractFound: {
6960 DCHECK(current_method == nullptr);
6961 // Abstract method masks all defaults.
6962 if (vtable_impl != nullptr &&
6963 vtable_impl->IsAbstract() &&
6964 !vtable_impl->IsDefaultConflicting()) {
6965 // We need to make this an abstract method but the version in the vtable already is so
6966 // don't do anything.
6967 current_method = vtable_impl;
6968 }
6969 break;
6970 } // case kAbstractFound
6971 }
6972 return current_method;
6973}
6974
6975ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
6976 ArtMethod* interface_method,
6977 MethodNameAndSignatureComparator& interface_name_comparator) {
6978 // Find out if there is already a miranda method we can use.
6979 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6980 miranda_methods_);
6981 if (miranda_method == nullptr) {
6982 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
6983 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6984 CHECK(miranda_method != nullptr);
6985 // Point the interface table at a phantom slot.
6986 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
6987 miranda_methods_.push_back(miranda_method);
6988 }
6989 return miranda_method;
6990}
6991
6992void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
6993 LogNewVirtuals();
6994
6995 const size_t old_method_count = klass_->NumMethods();
6996 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
6997 DCHECK_NE(old_method_count, new_method_count);
6998
6999 // Attempt to realloc to save RAM if possible.
7000 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7001 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7002 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7003 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7004 // CopyFrom has internal read barriers.
7005 //
7006 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7007 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7008 method_size_,
7009 method_alignment_);
7010 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7011 method_size_,
7012 method_alignment_);
7013 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7014 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007015 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007016 self_, old_methods, old_methods_ptr_size, new_size));
7017 CHECK(methods != nullptr); // Native allocation failure aborts.
7018
7019 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7020 if (methods != old_methods) {
7021 // Maps from heap allocated miranda method to linear alloc miranda method.
7022 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7023 // Copy over the old methods.
7024 for (auto& m : klass_->GetMethods(pointer_size)) {
7025 move_table_.emplace(&m, &*out);
7026 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7027 // barriers when it copies.
7028 out->CopyFrom(&m, pointer_size);
7029 ++out;
7030 }
7031 }
7032 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7033 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7034 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007035 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7036 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007037 ArtMethod& new_method = *out;
7038 new_method.CopyFrom(mir_method, pointer_size);
7039 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7040 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7041 << "Miranda method should be abstract!";
7042 move_table_.emplace(mir_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 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007048 ++out;
7049 }
7050 // We need to copy the default methods into our own method table since the runtime requires that
7051 // every method on a class's vtable be in that respective class's virtual method table.
7052 // NOTE This means that two classes might have the same implementation of a method from the same
7053 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7054 // default method found on a class with one found on the declaring interface directly and must
7055 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007056 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7057 &overriding_default_methods_}) {
7058 for (size_t i = 0; i < methods_vec->size(); ++i) {
7059 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007060 ArtMethod& new_method = *out;
7061 new_method.CopyFrom(def_method, pointer_size);
7062 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7063 // verified yet it shouldn't have methods that are skipping access checks.
7064 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7065 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007066 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007067 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7068 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7069 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7070 move_table_.emplace(def_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 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007079 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7080 &overriding_default_conflict_methods_}) {
7081 for (size_t i = 0; i < methods_vec->size(); ++i) {
7082 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007083 ArtMethod& new_method = *out;
7084 new_method.CopyFrom(conf_method, pointer_size);
7085 // This is a type of default method (there are default method impls, just a conflict) so
7086 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7087 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7088 // methods that are skipping access checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007089 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007090 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7091 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7092 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7093 DCHECK(new_method.IsDefaultConflicting());
7094 // The actual method might or might not be marked abstract since we just copied it from a
7095 // (possibly default) interface method. We need to set it entry point to be the bridge so
7096 // that the compiler will not invoke the implementation of whatever method we copied from.
7097 EnsureThrowsInvocationError(class_linker_, &new_method);
7098 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007099 // Update the entry in the method array, as the array will be used for future lookups,
7100 // where thread suspension is allowed.
7101 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7102 // would not see them.
7103 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007104 ++out;
7105 }
7106 }
7107 methods->SetSize(new_method_count);
7108 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7109}
7110
7111ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7112 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7113 ObjPtr<mirror::PointerArray> old_vtable) {
7114 // Update the vtable to the new method structures. We can skip this for interfaces since they
7115 // do not have vtables.
7116 const size_t old_vtable_count = old_vtable->GetLength();
7117 const size_t new_vtable_count = old_vtable_count +
7118 miranda_methods_.size() +
7119 default_methods_.size() +
7120 default_conflict_methods_.size();
7121
7122 ObjPtr<mirror::PointerArray> vtable =
7123 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7124 if (UNLIKELY(vtable == nullptr)) {
7125 self_->AssertPendingOOMException();
7126 return nullptr;
7127 }
7128
7129 size_t vtable_pos = old_vtable_count;
7130 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7131 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7132 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7133 default_conflict_methods_,
7134 miranda_methods_}) {
7135 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007136 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007137 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7138 // fields are references into the dex file the method was defined in. Since the ArtMethod
7139 // does not store that information it uses declaring_class_->dex_cache_.
7140 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7141 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7142 ++vtable_pos;
7143 }
7144 }
7145 DCHECK_EQ(vtable_pos, new_vtable_count);
7146
7147 // Update old vtable methods. We use the default_translations map to figure out what each
7148 // vtable entry should be updated to, if they need to be at all.
7149 for (size_t i = 0; i < old_vtable_count; ++i) {
7150 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7151 // Try and find what we need to change this method to.
7152 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007153 if (translation_it != default_translations.end()) {
7154 if (translation_it->second.IsInConflict()) {
7155 // Find which conflict method we are to use for this method.
7156 MethodNameAndSignatureComparator old_method_comparator(
7157 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7158 // We only need to look through overriding_default_conflict_methods since this is an
7159 // overridden method we are fixing up here.
7160 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7161 old_method_comparator, overriding_default_conflict_methods_);
7162 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7163 translated_method = new_conflict_method;
7164 } else if (translation_it->second.IsAbstract()) {
7165 // Find which miranda method we are to use for this method.
7166 MethodNameAndSignatureComparator old_method_comparator(
7167 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7168 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7169 miranda_methods_);
7170 DCHECK(miranda_method != nullptr);
7171 translated_method = miranda_method;
7172 } else {
7173 // Normal default method (changed from an older default or abstract interface method).
7174 DCHECK(translation_it->second.IsTranslation());
7175 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007176 auto it = move_table_.find(translated_method);
7177 DCHECK(it != move_table_.end());
7178 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007179 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007180 } else {
7181 auto it = move_table_.find(translated_method);
7182 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007183 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007184
7185 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007186 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007187 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007188 if (kIsDebugBuild) {
7189 auto* methods = klass_->GetMethodsPtr();
7190 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007191 reinterpret_cast<uintptr_t>(translated_method));
7192 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007193 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7194 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007195 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007196 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007197 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007198 }
7199 }
7200 klass_->SetVTable(vtable.Ptr());
7201 return vtable;
7202}
7203
7204void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7205 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7206 const size_t ifcount = klass_->GetIfTableCount();
7207 // Go fix up all the stale iftable pointers.
7208 for (size_t i = 0; i < ifcount; ++i) {
7209 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7210 auto* method_array = iftable->GetMethodArray(i);
7211 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7212 DCHECK(m != nullptr) << klass_->PrettyClass();
7213 auto it = move_table_.find(m);
7214 if (it != move_table_.end()) {
7215 auto* new_m = it->second;
7216 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7217 method_array->SetElementPtrSize(j, new_m, pointer_size);
7218 }
7219 }
7220 }
7221}
7222
7223void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7224 // Fix up IMT next.
7225 for (size_t i = 0; i < ImTable::kSize; ++i) {
7226 auto it = move_table_.find(out_imt[i]);
7227 if (it != move_table_.end()) {
7228 out_imt[i] = it->second;
7229 }
7230 }
7231}
7232
Alex Light705ad492015-09-21 11:36:30 -07007233// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007234bool ClassLinker::LinkInterfaceMethods(
7235 Thread* self,
7236 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007237 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007238 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007239 ArtMethod** out_imt) {
7240 StackHandleScope<3> hs(self);
7241 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007242
7243 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007244 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007245 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007246 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007247 const size_t ifcount = klass->GetIfTableCount();
7248
Vladimir Marko921094a2017-01-12 18:37:06 +00007249 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007250
7251 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7252 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007253 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007254 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007255 const bool extend_super_iftable = has_superclass;
7256 if (has_superclass && fill_tables) {
7257 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007258 unimplemented_method,
7259 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007260 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007261 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007262 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007263 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7264 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007265 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007266 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7267 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007268 }
7269 }
7270
Vladimir Marko921094a2017-01-12 18:37:06 +00007271 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7272
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007273 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007274 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007275 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7276 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7277 // they will already be null. This has the additional benefit that the declarer of a miranda
7278 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007279 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007280 --i;
Alex Light9139e002015-10-09 15:59:48 -07007281 DCHECK_LT(i, ifcount);
7282
Alex Light705ad492015-09-21 11:36:30 -07007283 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007284 if (num_methods > 0) {
7285 StackHandleScope<2> hs2(self);
7286 const bool is_super = i < super_ifcount;
7287 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007288 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7289 // conflict methods. Just set this as nullptr in those cases.
7290 Handle<mirror::PointerArray> method_array(fill_tables
7291 ? hs2.NewHandle(iftable->GetMethodArray(i))
7292 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007293
Alex Lighte64300b2015-12-15 15:02:47 -08007294 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007295 ScopedNullHandle<mirror::PointerArray> null_handle;
7296 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007297 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007298
Alex Light9139e002015-10-09 15:59:48 -07007299 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7300 // and confusing. Default methods should always look through all the superclasses
7301 // because they are the last choice of an implementation. We get around this by looking
7302 // at the super-classes iftable methods (copied into method_array previously) when we are
7303 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007304 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007305 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007306 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007307 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007308 using_virtuals = true;
7309 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7310 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007311 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007312 // For a new interface, however, we need the whole vtable in case a new
7313 // interface method is implemented in the whole superclass.
7314 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007315 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007316 input_vtable_array = vtable;
7317 input_array_length = input_vtable_array->GetLength();
7318 }
Alex Lighte64300b2015-12-15 15:02:47 -08007319
Alex Lighteb7c1442015-08-31 13:17:42 -07007320 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007321 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007322 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007323 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007324 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007325 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007326 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007327 // For each method listed in the interface's method list, find the
7328 // matching method in our class's method list. We want to favor the
7329 // subclass over the superclass, which just requires walking
7330 // back from the end of the vtable. (This only matters if the
7331 // superclass defines a private method and this class redefines
7332 // it -- otherwise it would use the same vtable slot. In .dex files
7333 // those don't end up in the virtual method table, so it shouldn't
7334 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007335 //
7336 // To find defaults we need to do the same but also go over interfaces.
7337 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007338 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007339 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007340 ArtMethod* vtable_method = using_virtuals ?
7341 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007342 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7343 ArtMethod* vtable_method_for_name_comparison =
7344 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007345 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007346 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007347 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007348 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7349 // allocations.
7350 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007351 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007352 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007353 vtable_method->PrettyMethod().c_str(),
7354 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007355 return false;
Alex Light9139e002015-10-09 15:59:48 -07007356 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007357 // We might have a newer, better, default method for this, so we just skip it. If we
7358 // are still using this we will select it again when scanning for default methods. To
7359 // obviate the need to copy the method again we will make a note that we already found
7360 // a default here.
7361 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007362 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007363 break;
7364 } else {
7365 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007366 if (LIKELY(fill_tables)) {
7367 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7368 // Place method in imt if entry is empty, place conflict otherwise.
7369 SetIMTRef(unimplemented_method,
7370 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007371 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007372 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007373 /*out*/imt_ptr);
7374 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007375 break;
7376 }
7377 }
Alex Light9139e002015-10-09 15:59:48 -07007378 }
7379 // Continue on to the next method if we are done.
7380 if (LIKELY(found_impl)) {
7381 continue;
7382 } else if (LIKELY(super_interface)) {
7383 // Don't look for a default implementation when the super-method is implemented directly
7384 // by the class.
7385 //
7386 // See if we can use the superclasses method and skip searching everything else.
7387 // Note: !found_impl && super_interface
7388 CHECK(extend_super_iftable);
7389 // If this is a super_interface method it is possible we shouldn't override it because a
7390 // superclass could have implemented it directly. We get the method the superclass used
7391 // to implement this to know if we can override it with a default method. Doing this is
7392 // safe since we know that the super_iftable is filled in so we can simply pull it from
7393 // there. We don't bother if this is not a super-classes interface since in that case we
7394 // have scanned the entire vtable anyway and would have found it.
7395 // TODO This is rather dirty but it is faster than searching through the entire vtable
7396 // every time.
7397 ArtMethod* supers_method =
7398 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7399 DCHECK(supers_method != nullptr);
7400 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007401 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007402 // The method is not overridable by a default method (i.e. it is directly implemented
7403 // in some class). Therefore move onto the next interface method.
7404 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007405 } else {
7406 // If the super-classes method is override-able by a default method we need to keep
7407 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7408 // 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 -07007409 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7410 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7411 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007412 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007413 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7414 << " and not 'nullptr' or "
7415 << supers_method->PrettyMethod()
7416 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007417 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007418 }
7419 }
7420 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007421 ArtMethod* current_method = helper.FindMethod(interface_method,
7422 interface_name_comparator,
7423 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007424 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007425 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007426 // We could not find an implementation for this method and since it is a brand new
7427 // interface we searched the entire vtable (and all default methods) for an
7428 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007429 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7430 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007431 }
7432
7433 if (current_method != nullptr) {
7434 // We found a default method implementation. Record it in the iftable and IMT.
7435 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7436 SetIMTRef(unimplemented_method,
7437 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007438 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007439 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007440 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007441 }
7442 }
Alex Light705ad492015-09-21 11:36:30 -07007443 } // For each method in interface end.
7444 } // if (num_methods > 0)
7445 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007446 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007447 if (helper.HasNewVirtuals()) {
7448 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7449 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7450 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7451
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007452 // 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 -07007453 // suspension assert.
7454 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007455
Alex Light705ad492015-09-21 11:36:30 -07007456 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007457 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007458 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007459 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007460 return false;
7461 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007462 helper.UpdateIfTable(iftable);
7463 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007464 }
Alex Light705ad492015-09-21 11:36:30 -07007465
Vladimir Marko921094a2017-01-12 18:37:06 +00007466 helper.CheckNoStaleMethodsInDexCache();
7467 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007468 } else {
7469 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007470 }
Alex Light705ad492015-09-21 11:36:30 -07007471 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007472 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007473 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007474 return true;
7475}
7476
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007477bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007478 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007479 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007480}
7481
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007482bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007483 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007484 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007485}
7486
Brian Carlstromdbc05252011-09-09 01:59:59 -07007487struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007488 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007489 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007490 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007491 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007492 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007493 // 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 -07007494 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7495 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007496 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007497 if (type1 == Primitive::kPrimNot) {
7498 // Reference always goes first.
7499 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007500 }
Vladimir Markod5777482014-11-12 17:02:02 +00007501 if (type2 == Primitive::kPrimNot) {
7502 // Reference always goes first.
7503 return false;
7504 }
7505 size_t size1 = Primitive::ComponentSize(type1);
7506 size_t size2 = Primitive::ComponentSize(type2);
7507 if (size1 != size2) {
7508 // Larger primitive types go first.
7509 return size1 > size2;
7510 }
7511 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7512 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007513 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007514 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7515 // by name and for equal names by type id index.
7516 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7517 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007518 }
7519};
7520
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007521bool ClassLinker::LinkFields(Thread* self,
7522 Handle<mirror::Class> klass,
7523 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007524 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007525 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007526 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007527 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7528 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007529
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007530 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007531 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007532 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007533 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007534 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007535 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007536 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007537 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007538 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007539 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007540 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007541 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007542
David Sehr709b0702016-10-13 09:12:37 -07007543 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007544
Brian Carlstromdbc05252011-09-09 01:59:59 -07007545 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007546 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007547 //
7548 // The overall sort order order is:
7549 // 1) All object reference fields, sorted alphabetically.
7550 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7551 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7552 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7553 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7554 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7555 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7556 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7557 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7558 //
7559 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7560 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007561 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007562 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007563 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007564 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007565 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007566 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007567 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7568 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007569
Fred Shih381e4ca2014-08-25 17:24:27 -07007570 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007571 size_t current_field = 0;
7572 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007573 FieldGaps gaps;
7574
Brian Carlstromdbc05252011-09-09 01:59:59 -07007575 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007576 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007577 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007578 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007579 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007580 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007581 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007582 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7583 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007584 MemberOffset old_offset = field_offset;
7585 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7586 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7587 }
Roland Levillain14d90572015-07-16 10:52:26 +01007588 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007589 grouped_and_sorted_fields.pop_front();
7590 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007591 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007592 field_offset = MemberOffset(field_offset.Uint32Value() +
7593 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007594 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007595 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7596 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007597 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7598 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7599 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7600 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007601 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7602 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007603 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007604
Elliott Hughesadb460d2011-10-05 17:02:34 -07007605 // 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 -07007606 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007607 // We know there are no non-reference fields in the Reference classes, and we know
7608 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007609 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007610 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007611 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007612 --num_reference_fields;
7613 }
7614
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007615 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007616 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007617 if (is_static) {
7618 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007619 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007620 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007621 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007622 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007623 if (num_reference_fields == 0 || super_class == nullptr) {
7624 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007625 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007626 if (super_class == nullptr ||
7627 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7628 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007629 }
7630 }
7631 if (kIsDebugBuild) {
7632 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7633 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007634 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007635 while (cur_super != nullptr) {
7636 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7637 cur_super = cur_super->GetSuperClass();
7638 }
7639 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007640 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007641 } else {
7642 // Check that there is at least num_reference_fields other than Object.class.
7643 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007644 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007645 }
7646 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007647 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007648 std::string temp;
7649 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7650 size_t previous_size = klass->GetObjectSize();
7651 if (previous_size != 0) {
7652 // Make sure that we didn't originally have an incorrect size.
7653 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007654 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007655 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007656 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007657 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007658
7659 if (kIsDebugBuild) {
7660 // Make sure that the fields array is ordered by name but all reference
7661 // offsets are at the beginning as far as alignment allows.
7662 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007663 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007664 : klass->GetFirstReferenceInstanceFieldOffset();
7665 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7666 num_reference_fields *
7667 sizeof(mirror::HeapReference<mirror::Object>));
7668 MemberOffset current_ref_offset = start_ref_offset;
7669 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007670 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007671 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007672 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7673 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007674 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007675 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007676 // NOTE: The field names can be the same. This is not possible in the Java language
7677 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007678 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007679 }
7680 Primitive::Type type = field->GetTypeAsPrimitiveType();
7681 bool is_primitive = type != Primitive::kPrimNot;
7682 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7683 strcmp("referent", field->GetName()) == 0) {
7684 is_primitive = true; // We lied above, so we have to expect a lie here.
7685 }
7686 MemberOffset offset = field->GetOffsetDuringLinking();
7687 if (is_primitive) {
7688 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7689 // Shuffled before references.
7690 size_t type_size = Primitive::ComponentSize(type);
7691 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7692 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7693 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7694 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7695 }
7696 } else {
7697 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7698 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7699 sizeof(mirror::HeapReference<mirror::Object>));
7700 }
7701 }
7702 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7703 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007704 return true;
7705}
7706
Vladimir Marko76649e82014-11-10 18:32:59 +00007707// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007708void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007709 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007710 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007711 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007712 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007713 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007714 // Compute reference offsets unless our superclass overflowed.
7715 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7716 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007717 if (num_reference_fields != 0u) {
7718 // All of the fields that contain object references are guaranteed be grouped in memory
7719 // starting at an appropriately aligned address after super class object data.
7720 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7721 sizeof(mirror::HeapReference<mirror::Object>));
7722 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007723 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007724 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007725 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007726 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007727 reference_offsets |= (0xffffffffu << start_bit) &
7728 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007729 }
7730 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007731 }
7732 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007733 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007734}
7735
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007736ObjPtr<mirror::String> ClassLinker::ResolveString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007737 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007738 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007739 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007740 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007741 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007742 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007743 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007744 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07007745 uint32_t utf16_length;
7746 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007747 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007748 if (string != nullptr) {
7749 dex_cache->SetResolvedString(string_idx, string);
7750 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007751 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007752}
7753
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007754ObjPtr<mirror::String> ClassLinker::LookupString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007755 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007756 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007757 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007758 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007759 return resolved;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007760 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007761 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007762 uint32_t utf16_length;
7763 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007764 ObjPtr<mirror::String> string =
7765 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007766 if (string != nullptr) {
7767 dex_cache->SetResolvedString(string_idx, string);
7768 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007769 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007770}
7771
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007772ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
7773 ObjPtr<mirror::DexCache> dex_cache,
7774 ObjPtr<mirror::ClassLoader> class_loader) {
7775 const DexFile& dex_file = *dex_cache->GetDexFile();
7776 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7777 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7778 ObjPtr<mirror::Class> type = nullptr;
7779 if (descriptor[1] == '\0') {
7780 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7781 // for primitive classes that aren't backed by dex files.
7782 type = FindPrimitiveClass(descriptor[0]);
7783 } else {
7784 Thread* const self = Thread::Current();
7785 DCHECK(self != nullptr);
7786 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7787 // Find the class in the loaded classes table.
7788 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
7789 }
7790 if (type != nullptr) {
7791 if (type->IsResolved()) {
7792 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07007793 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007794 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007795 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007796 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007797 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007798}
7799
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007800ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
7801 Handle<mirror::DexCache> dex_cache,
7802 Handle<mirror::ClassLoader> class_loader) {
7803 Thread* self = Thread::Current();
7804 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
7805 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
7806 if (resolved != nullptr) {
7807 // TODO: we used to throw here if resolved's class loader was not the
7808 // boot class loader. This was to permit different classes with the
7809 // same name to be loaded simultaneously by different loaders
7810 dex_cache->SetResolvedType(type_idx, resolved);
7811 } else {
7812 CHECK(self->IsExceptionPending())
7813 << "Expected pending exception for failed resolution of: " << descriptor;
7814 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7815 StackHandleScope<1> hs(self);
7816 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
7817 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
7818 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7819 self->ClearException();
7820 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7821 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007822 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007823 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007824 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007825 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00007826 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007827}
7828
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007829std::string DescribeSpace(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
7830 std::ostringstream oss;
7831 gc::Heap* heap = Runtime::Current()->GetHeap();
7832 gc::space::ContinuousSpace* cs = heap->FindContinuousSpaceFromAddress(klass.Ptr());
7833 if (cs != nullptr) {
7834 if (cs->IsImageSpace()) {
7835 oss << "image;" << cs->GetName() << ";" << cs->AsImageSpace()->GetImageFilename();
7836 } else {
7837 oss << "continuous;" << cs->GetName();
7838 }
7839 } else {
7840 gc::space::DiscontinuousSpace* ds =
7841 heap->FindDiscontinuousSpaceFromObject(klass, /* fail_ok */ true);
7842 if (ds != nullptr) {
7843 oss << "discontinuous;" << ds->GetName();
7844 } else {
7845 oss << "invalid";
7846 }
7847 }
7848 return oss.str();
7849}
7850
7851std::string DescribeLoaders(ObjPtr<mirror::ClassLoader> loader, const char* class_descriptor)
7852 REQUIRES_SHARED(Locks::mutator_lock_) {
7853 std::ostringstream oss;
7854 uint32_t hash = ComputeModifiedUtf8Hash(class_descriptor);
7855 ObjPtr<mirror::Class> path_class_loader =
7856 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_PathClassLoader);
7857 ObjPtr<mirror::Class> dex_class_loader =
7858 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexClassLoader);
7859 ObjPtr<mirror::Class> delegate_last_class_loader =
7860 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DelegateLastClassLoader);
7861
7862 // Print the class loader chain.
7863 bool found_class = false;
7864 const char* loader_separator = "";
7865 if (loader == nullptr) {
7866 oss << "BootClassLoader"; // This would be unexpected.
7867 }
7868 for (; loader != nullptr; loader = loader->GetParent()) {
7869 oss << loader_separator << loader->GetClass()->PrettyDescriptor();
7870 loader_separator = ";";
7871 // If we didn't find the interface yet, try to find it in the current class loader.
7872 if (!found_class) {
7873 ClassTable* table = Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(loader);
7874 ObjPtr<mirror::Class> klass =
7875 (table != nullptr) ? table->Lookup(class_descriptor, hash) : nullptr;
7876 if (klass != nullptr) {
7877 found_class = true;
7878 oss << "[hit:" << DescribeSpace(klass) << "]";
7879 }
7880 }
7881
7882 // For PathClassLoader, DexClassLoader or DelegateLastClassLoader
7883 // also dump the dex file locations.
7884 if (loader->GetClass() == path_class_loader ||
7885 loader->GetClass() == dex_class_loader ||
7886 loader->GetClass() == delegate_last_class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08007887 oss << "(";
7888 ScopedObjectAccessUnchecked soa(Thread::Current());
7889 StackHandleScope<1> hs(soa.Self());
7890 Handle<mirror::ClassLoader> handle(hs.NewHandle(loader));
7891 const char* path_separator = "";
7892 VisitClassLoaderDexFiles(soa,
7893 handle,
7894 [&](const DexFile* dex_file) {
7895 oss << path_separator << dex_file->GetLocation();
7896 path_separator = ":";
7897 return true; // Continue with the next DexFile.
7898 });
7899 oss << ")";
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007900 }
7901 }
7902
7903 return oss.str();
7904}
7905
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007906ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
7907 ObjPtr<mirror::DexCache> dex_cache,
7908 ObjPtr<mirror::ClassLoader> class_loader,
7909 uint32_t method_idx) {
7910 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7911 // functions can optimize the search if the dex_cache is the same as the DexCache
7912 // of the class, with fall-back to name and signature search otherwise.
7913 ArtMethod* resolved = nullptr;
7914 if (klass->IsInterface()) {
7915 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7916 } else {
7917 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7918 }
7919 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7920 if (resolved != nullptr) {
7921 // In case of jmvti, the dex file gets verified before being registered, so first
7922 // check if it's registered before checking class tables.
7923 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007924 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
7925 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007926 << "DexFile referrer: " << dex_file.GetLocation()
7927 << " ClassLoader: " << DescribeLoaders(class_loader, "");
7928 // Be a good citizen and update the dex cache to speed subsequent calls.
7929 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007930 // Disable the following invariant check as the verifier breaks it. b/73760543
7931 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7932 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
7933 // << "Method: " << resolved->PrettyMethod() << ", "
7934 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
7935 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007936 }
7937 return resolved;
7938}
7939
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007940template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00007941ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007942 Handle<mirror::DexCache> dex_cache,
7943 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007944 ArtMethod* referrer,
7945 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007946 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007947 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007948 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007949 PointerSize pointer_size = image_pointer_size_;
7950 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007951 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007952 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7953 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007954 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7955 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007956 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007957 return resolved;
7958 }
Vladimir Marko89011192017-12-11 13:45:05 +00007959 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007960 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007961 ObjPtr<mirror::Class> klass = nullptr;
7962 if (valid_dex_cache_method) {
7963 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7964 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007965 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007966 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007967 // We normaly should not end up here. However the verifier currently doesn't guarantee
7968 // the invariant of having the klass in the class table. b/73760543
7969 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007970 }
Vladimir Markoba118822017-06-12 15:41:56 +01007971 } else {
7972 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007973 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01007974 if (klass == nullptr) {
7975 DCHECK(Thread::Current()->IsExceptionPending());
7976 return nullptr;
7977 }
7978 }
7979
7980 // Check if the invoke type matches the class type.
7981 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
7982 CheckInvokeClassMismatch</* kThrow */ true>(
7983 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007984 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007985 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007986 }
Vladimir Markoba118822017-06-12 15:41:56 +01007987
7988 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007989 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007990 }
Vladimir Markoba118822017-06-12 15:41:56 +01007991
7992 // Note: We can check for IllegalAccessError only if we have a referrer.
7993 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
7994 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
7995 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
7996 if (!referring_class->CheckResolvedMethodAccess(methods_class,
7997 resolved,
7998 dex_cache.Get(),
7999 method_idx,
8000 type)) {
8001 DCHECK(Thread::Current()->IsExceptionPending());
8002 return nullptr;
8003 }
8004 }
8005
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008006 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008007 if (LIKELY(resolved != nullptr) &&
8008 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8009 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008010 return resolved;
8011 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008012 // If we had a method, or if we can find one with another lookup type,
8013 // it's an incompatible-class-change error.
8014 if (resolved == nullptr) {
8015 if (klass->IsInterface()) {
8016 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, pointer_size);
8017 } else {
8018 // If there was an interface method with the same signature,
8019 // we would have found it also in the "copied" methods.
8020 DCHECK(klass->FindInterfaceMethod(dex_cache.Get(), method_idx, pointer_size) == nullptr);
8021 }
8022 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008023 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008024 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008025 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008026 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008027 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8028 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008029 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008030 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008031 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008032 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008033 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008034}
8035
Vladimir Marko89011192017-12-11 13:45:05 +00008036ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008037 Handle<mirror::DexCache> dex_cache,
8038 Handle<mirror::ClassLoader> class_loader) {
8039 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008040 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008041 if (resolved != nullptr) {
8042 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008043 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8044 return resolved;
8045 }
8046 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008047 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
8048 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008049 if (klass == nullptr) {
8050 Thread::Current()->AssertPendingException();
8051 return nullptr;
8052 }
8053 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008054 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8055 } else {
8056 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008057 }
8058
8059 return resolved;
8060}
8061
Vladimir Markof44d36c2017-03-14 14:18:46 +00008062ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8063 ObjPtr<mirror::DexCache> dex_cache,
8064 ObjPtr<mirror::ClassLoader> class_loader,
8065 bool is_static) {
8066 const DexFile& dex_file = *dex_cache->GetDexFile();
8067 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8068 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8069 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008070 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008071 }
8072 if (klass == nullptr) {
8073 // The class has not been resolved yet, so the field is also unresolved.
8074 return nullptr;
8075 }
8076 DCHECK(klass->IsResolved());
8077 Thread* self = is_static ? Thread::Current() : nullptr;
8078
8079 // First try to find a field declared directly by `klass` by the field index.
8080 ArtField* resolved_field = is_static
8081 ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8082 : klass->FindInstanceField(dex_cache, field_idx);
8083
8084 if (resolved_field == nullptr) {
8085 // If not found in `klass` by field index, search the class hierarchy using the name and type.
8086 const char* name = dex_file.GetFieldName(field_id);
8087 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8088 resolved_field = is_static
8089 ? mirror::Class::FindStaticField(self, klass, name, type)
8090 : klass->FindInstanceField(name, type);
8091 }
8092
8093 if (resolved_field != nullptr) {
8094 dex_cache->SetResolvedField(field_idx, resolved_field, image_pointer_size_);
8095 }
8096 return resolved_field;
8097}
8098
Vladimir Markoe11dd502017-12-08 14:09:45 +00008099ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008100 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008101 Handle<mirror::ClassLoader> class_loader,
8102 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008103 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008104 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008105 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008106 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008107 return resolved;
8108 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008109 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008110 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008111 Thread* const self = Thread::Current();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008112 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008113 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008114 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008115 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008116 }
8117
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008118 if (is_static) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008119 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008120 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07008121 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008122 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008123
Andreas Gampe58a5af82014-07-31 16:23:49 -07008124 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008125 const char* name = dex_file.GetFieldName(field_id);
8126 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8127 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07008128 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008129 } else {
8130 resolved = klass->FindInstanceField(name, type);
8131 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07008132 if (resolved == nullptr) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008133 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008134 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008135 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008136 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07008137 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008138 return resolved;
8139}
8140
Vladimir Markoe11dd502017-12-08 14:09:45 +00008141ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008142 Handle<mirror::DexCache> dex_cache,
8143 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008144 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008145 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008146 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008147 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008148 return resolved;
8149 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008150 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008151 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008152 Thread* self = Thread::Current();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008153 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008154 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008155 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008156 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008157 }
8158
Vladimir Markof44d36c2017-03-14 14:18:46 +00008159 StringPiece name(dex_file.GetFieldName(field_id));
8160 StringPiece type(dex_file.GetFieldTypeDescriptor(field_id));
Mathieu Chartierf8322842014-05-16 10:59:25 -07008161 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008162 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008163 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008164 } else {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008165 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008166 }
8167 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008168}
8169
Vladimir Markoaf940202017-12-08 15:01:18 +00008170ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8171 Thread* self,
8172 uint32_t proto_idx,
8173 Handle<mirror::DexCache> dex_cache,
8174 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008175 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008176 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008177
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008178 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008179 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008180 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008181 }
8182
Narayan Kamath25352fc2016-08-03 12:46:58 +01008183 StackHandleScope<4> hs(self);
8184
8185 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008186 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008187 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8188 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008189 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008190 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008191 DCHECK(self->IsExceptionPending());
8192 return nullptr;
8193 }
8194
8195 // Then resolve the argument types.
8196 //
8197 // TODO: Is there a better way to figure out the number of method arguments
8198 // other than by looking at the shorty ?
8199 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8200
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008201 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008202 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008203 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8204 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008205 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008206 DCHECK(self->IsExceptionPending());
8207 return nullptr;
8208 }
8209
8210 DexFileParameterIterator it(dex_file, proto_id);
8211 int32_t i = 0;
8212 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8213 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008214 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008215 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008216 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008217 DCHECK(self->IsExceptionPending());
8218 return nullptr;
8219 }
8220
8221 method_params->Set(i++, param_class.Get());
8222 }
8223
8224 DCHECK(!it.HasNext());
8225
8226 Handle<mirror::MethodType> type = hs.NewHandle(
8227 mirror::MethodType::Create(self, return_type, method_params));
8228 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8229
8230 return type.Get();
8231}
8232
Vladimir Markoaf940202017-12-08 15:01:18 +00008233ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
8234 uint32_t proto_idx,
8235 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008236 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008237 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8238 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008239 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008240}
8241
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008242mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8243 Thread* self,
8244 const DexFile::MethodHandleItem& method_handle,
8245 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008246 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008247 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8248 mirror::MethodHandle::Kind kind;
8249 bool is_static;
8250 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008251 switch (handle_type) {
8252 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008253 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008254 is_static = true;
8255 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008256 break;
8257 }
8258 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008259 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008260 is_static = true;
8261 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008262 break;
8263 }
8264 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008265 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008266 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008267 num_params = 2;
8268 break;
8269 }
8270 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008271 kind = mirror::MethodHandle::Kind::kInstanceGet;
8272 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008273 num_params = 1;
8274 break;
8275 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008276 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008277 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008278 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008279 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008280 case DexFile::MethodHandleType::kInvokeInterface:
8281 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008282 }
8283
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008284 ArtField* target_field =
8285 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8286 if (LIKELY(target_field != nullptr)) {
8287 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8288 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8289 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8290 ThrowIllegalAccessErrorField(referring_class, target_field);
8291 return nullptr;
8292 }
8293 } else {
8294 DCHECK(Thread::Current()->IsExceptionPending());
8295 return nullptr;
8296 }
8297
8298 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008299 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8300 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8301 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8302 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008303 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008304 DCHECK(self->IsExceptionPending());
8305 return nullptr;
8306 }
8307
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008308 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008309 Handle<mirror::Class> return_type;
8310 switch (handle_type) {
8311 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008312 method_params->Set(0, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008313 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8314 break;
8315 }
8316 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008317 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008318 break;
8319 }
8320 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008321 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008322 method_params->Set(1, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008323 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8324 break;
8325 }
8326 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008327 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008328 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008329 break;
8330 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008331 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008332 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008333 case DexFile::MethodHandleType::kInvokeConstructor:
8334 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008335 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008336 UNREACHABLE();
8337 }
8338
8339 for (int32_t i = 0; i < num_params; ++i) {
8340 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8341 DCHECK(self->IsExceptionPending());
8342 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008343 }
8344 }
8345
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008346 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008347 DCHECK(self->IsExceptionPending());
8348 return nullptr;
8349 }
8350
8351 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008352 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8353 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008354 DCHECK(self->IsExceptionPending());
8355 return nullptr;
8356 }
Orion Hodson631827d2017-04-10 14:53:47 +01008357
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008358 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8359 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8360}
8361
8362mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8363 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008364 const DexFile::MethodHandleItem& method_handle,
8365 ArtMethod* referrer) {
8366 DexFile::MethodHandleType handle_type =
8367 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8368 mirror::MethodHandle::Kind kind;
8369 uint32_t receiver_count = 0;
8370 ArtMethod* target_method = nullptr;
8371 switch (handle_type) {
8372 case DexFile::MethodHandleType::kStaticPut:
8373 case DexFile::MethodHandleType::kStaticGet:
8374 case DexFile::MethodHandleType::kInstancePut:
8375 case DexFile::MethodHandleType::kInstanceGet:
8376 UNREACHABLE();
8377 case DexFile::MethodHandleType::kInvokeStatic: {
8378 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8379 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008380 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8381 method_handle.field_or_method_idx_,
8382 referrer,
8383 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008384 break;
8385 }
8386 case DexFile::MethodHandleType::kInvokeInstance: {
8387 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8388 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008389 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8390 method_handle.field_or_method_idx_,
8391 referrer,
8392 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008393 break;
8394 }
8395 case DexFile::MethodHandleType::kInvokeConstructor: {
8396 // Constructors are currently implemented as a transform. They
8397 // are special cased later in this method.
8398 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8399 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008400 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8401 method_handle.field_or_method_idx_,
8402 referrer,
8403 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008404 break;
8405 }
8406 case DexFile::MethodHandleType::kInvokeDirect: {
8407 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8408 receiver_count = 1;
8409 StackHandleScope<2> hs(self);
8410 // A constant method handle with type kInvokeDirect can refer to
8411 // a method that is private or to a method in a super class. To
8412 // disambiguate the two options, we resolve the method ignoring
8413 // the invocation type to determine if the method is private. We
8414 // then resolve again specifying the intended invocation type to
8415 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008416 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008417 hs.NewHandle(referrer->GetDexCache()),
8418 hs.NewHandle(referrer->GetClassLoader()));
8419 if (UNLIKELY(target_method == nullptr)) {
8420 break;
8421 }
8422
8423 if (target_method->IsPrivate()) {
8424 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008425 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8426 method_handle.field_or_method_idx_,
8427 referrer,
8428 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008429 } else {
8430 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008431 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8432 method_handle.field_or_method_idx_,
8433 referrer,
8434 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008435 if (UNLIKELY(target_method == nullptr)) {
8436 break;
8437 }
8438 // Find the method specified in the parent in referring class
8439 // so invoke-super invokes the method in the parent of the
8440 // referrer.
8441 target_method =
8442 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8443 kRuntimePointerSize);
8444 }
8445 break;
8446 }
8447 case DexFile::MethodHandleType::kInvokeInterface: {
8448 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8449 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008450 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8451 method_handle.field_or_method_idx_,
8452 referrer,
8453 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008454 break;
8455 }
Orion Hodson631827d2017-04-10 14:53:47 +01008456 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008457
8458 if (UNLIKELY(target_method == nullptr)) {
8459 DCHECK(Thread::Current()->IsExceptionPending());
8460 return nullptr;
8461 }
8462
8463 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8464 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8465 uint32_t access_flags = target_method->GetAccessFlags();
8466 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8467 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8468 return nullptr;
8469 }
8470
8471 // Calculate the number of parameters from the method shorty. We add the
8472 // receiver count (0 or 1) and deduct one for the return value.
8473 uint32_t shorty_length;
8474 target_method->GetShorty(&shorty_length);
8475 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8476
8477 StackHandleScope<7> hs(self);
8478 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8479 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8480 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8481 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8482 if (method_params.Get() == nullptr) {
8483 DCHECK(self->IsExceptionPending());
8484 return nullptr;
8485 }
8486
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008487 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008488 if (receiver_count != 0) {
8489 // Insert receiver
8490 method_params->Set(index++, target_method->GetDeclaringClass());
8491 }
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008492 DexFileParameterIterator it(*target_method->GetDexFile(), target_method->GetPrototype());
8493 Handle<mirror::DexCache> target_method_dex_cache(hs.NewHandle(target_method->GetDexCache()));
8494 Handle<mirror::ClassLoader> target_method_class_loader(hs.NewHandle(target_method->GetClassLoader()));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008495 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008496 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008497 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008498 ObjPtr<mirror::Class> klass = ResolveType(type_idx,
8499 target_method_dex_cache,
8500 target_method_class_loader);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008501 if (nullptr == klass) {
8502 DCHECK(self->IsExceptionPending());
8503 return nullptr;
8504 }
8505 method_params->Set(index++, klass);
8506 it.Next();
8507 }
8508
Vladimir Markob45528c2017-07-27 14:14:28 +01008509 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008510 if (UNLIKELY(return_type.IsNull())) {
8511 DCHECK(self->IsExceptionPending());
8512 return nullptr;
8513 }
8514
8515 Handle<mirror::MethodType>
8516 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8517 if (UNLIKELY(method_type.IsNull())) {
8518 DCHECK(self->IsExceptionPending());
8519 return nullptr;
8520 }
8521
8522 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8523 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8524 Handle<mirror::MethodHandlesLookup> lookup =
8525 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8526 return lookup->FindConstructor(self, constructor_class, method_type);
8527 }
8528
8529 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8530 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8531}
8532
Vladimir Markoaf940202017-12-08 15:01:18 +00008533ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8534 uint32_t method_handle_idx,
8535 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008536 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008537 const DexFile* const dex_file = referrer->GetDexFile();
8538 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8539 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8540 case DexFile::MethodHandleType::kStaticPut:
8541 case DexFile::MethodHandleType::kStaticGet:
8542 case DexFile::MethodHandleType::kInstancePut:
8543 case DexFile::MethodHandleType::kInstanceGet:
8544 return ResolveMethodHandleForField(self, method_handle, referrer);
8545 case DexFile::MethodHandleType::kInvokeStatic:
8546 case DexFile::MethodHandleType::kInvokeInstance:
8547 case DexFile::MethodHandleType::kInvokeConstructor:
8548 case DexFile::MethodHandleType::kInvokeDirect:
8549 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008550 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008551 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008552}
8553
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008554bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8555 return (entry_point == GetQuickResolutionStub()) ||
8556 (quick_resolution_trampoline_ == entry_point);
8557}
8558
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008559bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8560 return (entry_point == GetQuickToInterpreterBridge()) ||
8561 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8562}
8563
8564bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8565 return (entry_point == GetQuickGenericJniStub()) ||
8566 (quick_generic_jni_trampoline_ == entry_point);
8567}
8568
David Sehra49e0532017-08-25 08:05:29 -07008569bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8570 return entry_point == GetJniDlsymLookupStub();
8571}
8572
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008573const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8574 return GetQuickGenericJniStub();
8575}
8576
Mathieu Chartiere401d142015-04-22 13:56:20 -07008577void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008578 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008579 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8580 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008581 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008582 }
8583}
8584
Alex Lightdb01a092017-04-03 15:39:55 -07008585void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8586 DCHECK(method->IsObsolete());
8587 // We cannot mess with the entrypoints of native methods because they are used to determine how
8588 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8589 if (!method->IsNative()) {
8590 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8591 }
8592}
8593
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008594void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008595 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008596 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008597 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8598 << NumNonZygoteClasses() << "\n";
8599}
8600
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008601class CountClassesVisitor : public ClassLoaderVisitor {
8602 public:
8603 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8604
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008605 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008606 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008607 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008608 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008609 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8610 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008611 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008612 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008613
8614 size_t num_zygote_classes;
8615 size_t num_non_zygote_classes;
8616};
8617
8618size_t ClassLinker::NumZygoteClasses() const {
8619 CountClassesVisitor visitor;
8620 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008621 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008622}
8623
8624size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008625 CountClassesVisitor visitor;
8626 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008627 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008628}
8629
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008630size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008631 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008632 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008633 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008634}
8635
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008636pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008637 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008638}
8639
8640pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008641 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008642}
8643
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008644void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008645 DCHECK(!init_done_);
8646
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008647 DCHECK(klass != nullptr);
8648 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008649
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008650 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008651 DCHECK(class_roots != nullptr);
8652 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008653 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008654}
8655
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008656const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8657 static const char* class_roots_descriptors[] = {
8658 "Ljava/lang/Class;",
8659 "Ljava/lang/Object;",
8660 "[Ljava/lang/Class;",
8661 "[Ljava/lang/Object;",
8662 "Ljava/lang/String;",
8663 "Ljava/lang/DexCache;",
8664 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008665 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008666 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008667 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008668 "Ljava/lang/reflect/Proxy;",
8669 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008670 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008671 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008672 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008673 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008674 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008675 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008676 "Ljava/lang/invoke/MethodType;",
Orion Hodson005ac512017-10-24 15:43:43 +01008677 "Ljava/lang/invoke/VarHandle;",
8678 "Ljava/lang/invoke/FieldVarHandle;",
8679 "Ljava/lang/invoke/ArrayElementVarHandle;",
8680 "Ljava/lang/invoke/ByteArrayViewVarHandle;",
8681 "Ljava/lang/invoke/ByteBufferViewVarHandle;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008682 "Ljava/lang/ClassLoader;",
8683 "Ljava/lang/Throwable;",
8684 "Ljava/lang/ClassNotFoundException;",
8685 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008686 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008687 "Z",
8688 "B",
8689 "C",
8690 "D",
8691 "F",
8692 "I",
8693 "J",
8694 "S",
8695 "V",
8696 "[Z",
8697 "[B",
8698 "[C",
8699 "[D",
8700 "[F",
8701 "[I",
8702 "[J",
8703 "[S",
8704 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008705 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008706 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008707 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8708 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008709
8710 const char* descriptor = class_roots_descriptors[class_root];
8711 CHECK(descriptor != nullptr);
8712 return descriptor;
8713}
8714
Calin Juravle7865ac72017-06-28 11:03:12 -07008715jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
Andreas Gampe473191c2017-12-28 16:55:31 -08008716 const std::vector<const DexFile*>& dex_files,
8717 jclass loader_class,
8718 jobject parent_loader) {
Calin Juravle7865ac72017-06-28 11:03:12 -07008719 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8720 WellKnownClasses::dalvik_system_PathClassLoader) ||
8721 self->GetJniEnv()->IsSameObject(loader_class,
8722 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8723
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008724 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8725 // We could move the jobject to the callers, but all call-sites do this...
8726 ScopedObjectAccessUnchecked soa(self);
8727
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008728 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008729 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008730
Mathieu Chartierc7853442015-03-27 14:35:38 -07008731 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008732 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008733
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008734 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008735 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008736 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008737 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008738 mirror::ObjectArray<mirror::Object>::Alloc(self,
8739 dex_elements_class.Get(),
8740 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008741 Handle<mirror::Class> h_dex_element_class =
8742 hs.NewHandle(dex_elements_class->GetComponentType());
8743
Mathieu Chartierc7853442015-03-27 14:35:38 -07008744 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008745 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008746 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008747
Andreas Gampe08883de2016-11-08 13:20:52 -08008748 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00008749 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008750
Andreas Gampe08883de2016-11-08 13:20:52 -08008751 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00008752 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008753
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008754 // Fill the elements array.
8755 int32_t index = 0;
8756 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008757 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008758
Calin Juravle7865ac72017-06-28 11:03:12 -07008759 // CreateWellKnownClassLoader is only used by gtests and compiler.
8760 // 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 -07008761 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8762 self,
8763 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008764 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008765 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008766
Mathieu Chartier3738e982017-05-12 16:07:28 -07008767 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8768 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008769 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008770 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008771 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008772 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008773
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008774 Handle<mirror::String> h_file_name = hs2.NewHandle(
8775 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008776 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008777 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8778
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008779 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008780 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008781 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008782
8783 h_dex_elements->Set(index, h_element.Get());
8784 index++;
8785 }
8786 DCHECK_EQ(index, h_dex_elements->GetLength());
8787
8788 // Create DexPathList.
8789 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008790 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008791 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008792 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008793 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08008794 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
8795 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
8796 // elements.
8797 {
8798 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
8799 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
8800 DCHECK(native_lib_dirs != nullptr);
8801 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
8802 DCHECK(list_class != nullptr);
8803 {
8804 StackHandleScope<1> h_list_scope(self);
8805 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
8806 bool list_init = EnsureInitialized(self, h_list_class, true, true);
8807 DCHECK(list_init);
8808 list_class = h_list_class.Get();
8809 }
8810 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
8811 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
8812 // is fine for testing. While it violates a Java-code invariant (the elementData field is
8813 // normally never null), as long as one does not try to add elements, this will still
8814 // work.
8815 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
8816 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008817
Calin Juravle7865ac72017-06-28 11:03:12 -07008818 // Create the class loader..
8819 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8820 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8821 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008822 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008823 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008824 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008825 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008826 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008827
8828 // Make a pretend boot-classpath.
8829 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008830 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008831 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008832 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008833 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008834 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008835 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008836
8837 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8838 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8839 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8840 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008841
8842 // Make it a global ref and return.
8843 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008844 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008845 return soa.Env()->NewGlobalRef(local_ref.get());
8846}
8847
Calin Juravle7865ac72017-06-28 11:03:12 -07008848jobject ClassLinker::CreatePathClassLoader(Thread* self,
8849 const std::vector<const DexFile*>& dex_files) {
8850 return CreateWellKnownClassLoader(self,
8851 dex_files,
8852 WellKnownClasses::dalvik_system_PathClassLoader,
8853 nullptr);
8854}
8855
Andreas Gampe8ac75952015-06-02 21:01:45 -07008856void ClassLinker::DropFindArrayClassCache() {
8857 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8858 find_array_class_cache_next_victim_ = 0;
8859}
8860
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008861void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008862 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008863 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008864 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008865 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8866 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008867 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008868 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008869 }
8870 }
8871}
8872
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008873void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8874 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008875 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008876 Thread* const self = Thread::Current();
8877 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008878 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008879 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008880 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008881 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8882 // class table was modified.
8883 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8884 }
8885}
8886
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008887void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008888 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008889 std::vector<ClassLoaderData> to_delete;
8890 // Do the delete outside the lock to avoid lock violation in jit code cache.
8891 {
8892 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8893 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8894 const ClassLoaderData& data = *it;
8895 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008896 ObjPtr<mirror::ClassLoader> class_loader =
8897 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008898 if (class_loader != nullptr) {
8899 ++it;
8900 } else {
8901 VLOG(class_linker) << "Freeing class loader";
8902 to_delete.push_back(data);
8903 it = class_loaders_.erase(it);
8904 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008905 }
8906 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008907 for (ClassLoaderData& data : to_delete) {
8908 DeleteClassLoader(self, data);
8909 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008910}
8911
Vladimir Marko21300532017-01-24 18:06:55 +00008912class GetResolvedClassesVisitor : public ClassVisitor {
8913 public:
8914 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8915 : result_(result),
8916 ignore_boot_classes_(ignore_boot_classes),
8917 last_resolved_classes_(result->end()),
8918 last_dex_file_(nullptr),
8919 vlog_is_on_(VLOG_IS_ON(class_linker)),
8920 extra_stats_(),
8921 last_extra_stats_(extra_stats_.end()) { }
8922
8923 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8924 if (!klass->IsProxyClass() &&
8925 !klass->IsArrayClass() &&
8926 klass->IsResolved() &&
8927 !klass->IsErroneousResolved() &&
8928 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8929 const DexFile& dex_file = klass->GetDexFile();
8930 if (&dex_file != last_dex_file_) {
8931 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008932 DexCacheResolvedClasses resolved_classes(
8933 dex_file.GetLocation(),
8934 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8935 dex_file.GetLocationChecksum(),
8936 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008937 last_resolved_classes_ = result_->find(resolved_classes);
8938 if (last_resolved_classes_ == result_->end()) {
8939 last_resolved_classes_ = result_->insert(resolved_classes).first;
8940 }
8941 }
8942 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8943 if (UNLIKELY(vlog_is_on_) && added) {
8944 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8945 if (last_extra_stats_ == extra_stats_.end() ||
8946 last_extra_stats_->first != resolved_classes) {
8947 last_extra_stats_ = extra_stats_.find(resolved_classes);
8948 if (last_extra_stats_ == extra_stats_.end()) {
8949 last_extra_stats_ =
8950 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8951 }
8952 }
8953 }
8954 }
8955 return true;
8956 }
8957
8958 void PrintStatistics() const {
8959 if (vlog_is_on_) {
8960 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8961 auto it = extra_stats_.find(std::addressof(resolved_classes));
8962 DCHECK(it != extra_stats_.end());
8963 const ExtraStats& extra_stats = it->second;
8964 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8965 << " has " << resolved_classes.GetClasses().size() << " / "
8966 << extra_stats.number_of_class_defs_ << " resolved classes";
8967 }
8968 }
8969 }
8970
8971 private:
8972 struct ExtraStats {
8973 explicit ExtraStats(uint32_t number_of_class_defs)
8974 : number_of_class_defs_(number_of_class_defs) {}
8975 uint32_t number_of_class_defs_;
8976 };
8977
8978 std::set<DexCacheResolvedClasses>* result_;
8979 bool ignore_boot_classes_;
8980 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8981 const DexFile* last_dex_file_;
8982
8983 // Statistics.
8984 bool vlog_is_on_;
8985 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8986 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8987};
8988
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008989std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008990 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008991 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008992 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008993 std::set<DexCacheResolvedClasses> ret;
8994 VLOG(class_linker) << "Collecting resolved classes";
8995 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008996 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8997 VisitClasses(&visitor);
8998 if (VLOG_IS_ON(class_linker)) {
8999 visitor.PrintStatistics();
9000 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009001 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009002 return ret;
9003}
9004
Mathieu Chartier65975772016-08-05 10:46:36 -07009005class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9006 public:
9007 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9008 : method_(method),
9009 pointer_size_(pointer_size) {}
9010
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009011 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07009012 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9013 holder_ = klass;
9014 }
9015 // Return false to stop searching if holder_ is not null.
9016 return holder_ == nullptr;
9017 }
9018
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009019 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009020 const ArtMethod* const method_;
9021 const PointerSize pointer_size_;
9022};
9023
9024mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
9025 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9026 CHECK(method->IsCopied());
9027 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9028 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009029 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07009030}
9031
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009032mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9033 return down_cast<mirror::IfTable*>(
9034 mirror::IfTable::Alloc(self,
9035 GetClassRoot(kObjectArrayClass),
9036 ifcount * mirror::IfTable::kMax));
9037}
9038
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009039// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009040template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009041 uint32_t method_idx,
9042 Handle<mirror::DexCache> dex_cache,
9043 Handle<mirror::ClassLoader> class_loader,
9044 ArtMethod* referrer,
9045 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009046template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009047 uint32_t method_idx,
9048 Handle<mirror::DexCache> dex_cache,
9049 Handle<mirror::ClassLoader> class_loader,
9050 ArtMethod* referrer,
9051 InvokeType type);
9052
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009053} // namespace art