blob: 50b5357524aacfec0088e3ee5e8df366d5be9b9c [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>
Vladimir Markobf121912019-06-04 13:49:05 +010023#include <forward_list>
Ian Rogerscf7f1912014-10-22 22:06:39 -070024#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000025#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070027#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070028#include <string>
Andreas Gampe9f3928f2019-02-04 11:19:31 -080029#include <string_view>
Alex Lighteb7c1442015-08-31 13:17:42 -070030#include <tuple>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070032#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070033
Andreas Gampe46ee31b2016-12-14 10:11:49 -080034#include "android-base/stringprintf.h"
35
Mathieu Chartierc7853442015-03-27 14:35:38 -070036#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "art_method-inl.h"
Vladimir Markobf121912019-06-04 13:49:05 +010038#include "barrier.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080040#include "base/casts.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070041#include "base/file_utils.h"
Vladimir Marko782fb712020-12-23 12:47:31 +000042#include "base/hash_map.h"
43#include "base/hash_set.h"
David Sehr67bf42e2018-02-26 16:43:04 -080044#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080045#include "base/logging.h"
Eric Holk74584e62021-02-18 14:39:17 -080046#include "base/metrics/metrics.h"
Vladimir Markobf121912019-06-04 13:49:05 +010047#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080048#include "base/os.h"
49#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070050#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010051#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080052#include "base/stl_util.h"
Vladimir Markob9c29f62019-03-20 14:22:51 +000053#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080054#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010055#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080056#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080057#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070058#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070059#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070061#include "class_loader_utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010062#include "class_root-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070063#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000064#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010065#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080066#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070067#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080068#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080069#include "dex/dex_file-inl.h"
70#include "dex/dex_file_exception_helpers.h"
71#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080072#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000073#include "dex/utf.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010074#include "entrypoints/entrypoint_utils-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070075#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070076#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070077#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080078#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000079#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070080#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070081#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070082#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070083#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000084#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070085#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070086#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070087#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080088#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070089#include "imt_conflict_table.h"
90#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070091#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070092#include "interpreter/interpreter.h"
Nicolas Geoffray0315efa2020-06-26 11:42:39 +010093#include "interpreter/mterp/nterp.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000094#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080095#include "jit/jit.h"
96#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010097#include "jni/java_vm_ext.h"
98#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070099#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -0700100#include "mirror/array-alloc-inl.h"
101#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000102#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -0700103#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700105#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -0700106#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800107#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700108#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700109#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100110#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700111#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800112#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700113#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100114#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000115#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700116#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800117#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000118#include "mirror/object-refvisitor-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -0800119#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700120#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700121#include "mirror/object_array-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000122#include "mirror/object_array.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700123#include "mirror/object_reference.h"
124#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800125#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700126#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800127#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700128#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000129#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100130#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700131#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700132#include "nativehelper/scoped_local_ref.h"
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000133#include "nterp_helpers.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700134#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700135#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700136#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700137#include "oat_file_assistant.h"
138#include "oat_file_manager.h"
139#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700140#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700141#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800142#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700143#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700144#include "thread-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000145#include "thread.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700146#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700147#include "trace.h"
Vladimir Markob68bb7a2020-03-17 10:55:25 +0000148#include "transaction.h"
Nicolas Geoffray6df45112021-02-07 21:51:58 +0000149#include "vdex_file.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700150#include "verifier/class_verifier.h"
Nicolas Geoffray80789962021-04-30 16:50:39 +0100151#include "verifier/verifier_deps.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700152#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700153
Nicolas Geoffray00391822019-12-10 10:17:23 +0000154#include "interpreter/interpreter_mterp_impl.h"
155
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700156namespace art {
157
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800158using android::base::StringPrintf;
159
Orion Hodson5880c772020-07-28 20:12:08 +0100160static constexpr bool kCheckImageObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700161static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700162
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163static void ThrowNoClassDefFoundError(const char* fmt, ...)
164 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700165 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700166static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700167 va_list args;
168 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800169 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000170 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800171 va_end(args);
172}
173
Andreas Gampe99babb62015-11-02 16:20:00 -0800174static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700175 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700176 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700177 StackHandleScope<1> hs(self);
178 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700179 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700180 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700181
182 if (exception_class == nullptr) {
183 // No exc class ~ no <init>-with-string.
184 CHECK(self->IsExceptionPending());
185 self->ClearException();
186 return false;
187 }
188
Vladimir Markoba118822017-06-12 15:41:56 +0100189 ArtMethod* exception_init_method = exception_class->FindConstructor(
190 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700191 return exception_init_method != nullptr;
192}
193
Vladimir Markobb206de2019-03-28 10:30:32 +0000194static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700195 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700196 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
197 if (ext == nullptr) {
198 return nullptr;
199 } else {
200 return ext->GetVerifyError();
201 }
202}
203
204// Helper for ThrowEarlierClassFailure. Throws the stored error.
205static void HandleEarlierVerifyError(Thread* self,
206 ClassLinker* class_linker,
207 ObjPtr<mirror::Class> c)
208 REQUIRES_SHARED(Locks::mutator_lock_) {
209 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800210 DCHECK(obj != nullptr);
211 self->AssertNoPendingException();
212 if (obj->IsClass()) {
213 // Previous error has been stored as class. Create a new exception of that type.
214
215 // It's possible the exception doesn't have a <init>(String).
216 std::string temp;
217 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
218
219 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700220 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800221 } else {
222 self->ThrowNewException(descriptor, nullptr);
223 }
224 } else {
225 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100226 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700227 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800228 CHECK(throwable_class->IsAssignableFrom(error_class));
229 self->SetException(obj->AsThrowable());
230 }
231 self->AssertPendingException();
232}
233
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000234static void ChangeInterpreterBridgeToNterp(ArtMethod* method, ClassLinker* class_linker)
235 REQUIRES_SHARED(Locks::mutator_lock_) {
236 Runtime* runtime = Runtime::Current();
237 if (class_linker->IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode()) &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000238 CanMethodUseNterp(method)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000239 if (method->GetDeclaringClass()->IsVisiblyInitialized() ||
240 !NeedsClinitCheckBeforeCall(method)) {
241 runtime->GetInstrumentation()->UpdateMethodsCode(method, interpreter::GetNterpEntryPoint());
242 } else {
243 // Put the resolution stub, which will initialize the class and then
244 // call the method with nterp.
245 runtime->GetInstrumentation()->UpdateMethodsCode(method, GetQuickResolutionStub());
246 }
247 }
248}
249
Andreas Gampe5b20b352018-10-11 19:03:20 -0700250// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
251// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
252// before.
Andreas Gampe5b20b352018-10-11 19:03:20 -0700253static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
254 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000255 Runtime* runtime = Runtime::Current();
256 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampe5b20b352018-10-11 19:03:20 -0700257 if (!klass->WasVerificationAttempted()) {
258 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
259 klass->SetVerificationAttempted();
Nicolas Geoffray00391822019-12-10 10:17:23 +0000260 // Now that the class has passed verification, try to set nterp entrypoints
261 // to methods that currently use the switch interpreter.
262 if (interpreter::CanRuntimeUseNterp()) {
263 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000264 ChangeInterpreterBridgeToNterp(&m, class_linker);
Nicolas Geoffray00391822019-12-10 10:17:23 +0000265 }
266 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700267 }
268}
269
Vladimir Markobf121912019-06-04 13:49:05 +0100270// Callback responsible for making a batch of classes visibly initialized
271// after all threads have called it from a checkpoint, ensuring visibility.
272class ClassLinker::VisiblyInitializedCallback final
273 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
274 public:
275 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
276 : class_linker_(class_linker),
277 num_classes_(0u),
278 thread_visibility_counter_(0),
279 barriers_() {
280 std::fill_n(classes_, kMaxClasses, nullptr);
281 }
282
283 bool IsEmpty() const {
284 DCHECK_LE(num_classes_, kMaxClasses);
285 return num_classes_ == 0u;
286 }
287
288 bool IsFull() const {
289 DCHECK_LE(num_classes_, kMaxClasses);
290 return num_classes_ == kMaxClasses;
291 }
292
293 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
294 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
295 DCHECK(!IsFull());
296 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
297 ++num_classes_;
298 }
299
300 void AddBarrier(Barrier* barrier) {
301 barriers_.push_front(barrier);
302 }
303
304 std::forward_list<Barrier*> GetAndClearBarriers() {
305 std::forward_list<Barrier*> result;
306 result.swap(barriers_);
307 result.reverse(); // Return barriers in insertion order.
308 return result;
309 }
310
311 void MakeVisible(Thread* self) {
312 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
313 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
314 AdjustThreadVisibilityCounter(self, count);
315 }
316
317 void Run(Thread* self) override {
318 self->ClearMakeVisiblyInitializedCounter();
319 AdjustThreadVisibilityCounter(self, -1);
320 }
321
322 private:
323 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
324 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
325 if (old + adjustment == 0) {
326 // All threads passed the checkpoint. Mark classes as visibly initialized.
327 {
328 ScopedObjectAccess soa(self);
329 StackHandleScope<1u> hs(self);
330 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
331 JavaVMExt* vm = self->GetJniEnv()->GetVm();
332 for (size_t i = 0, num = num_classes_; i != num; ++i) {
333 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
334 vm->DeleteWeakGlobalRef(self, classes_[i]);
335 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100336 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100337 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100338 }
339 }
340 num_classes_ = 0u;
341 }
342 class_linker_->VisiblyInitializedCallbackDone(self, this);
343 }
344 }
345
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100346 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100347
348 ClassLinker* const class_linker_;
349 size_t num_classes_;
350 jweak classes_[kMaxClasses];
351
352 // The thread visibility counter starts at 0 and it is incremented by the number of
353 // threads that need to run this callback (by the thread that request the callback
354 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
355 // whether after the increment or after a decrement, we know that `Run()` was executed
356 // for all threads and therefore we can mark the classes as visibly initialized.
357 std::atomic<ssize_t> thread_visibility_counter_;
358
359 // List of barries to `Pass()` for threads that wait for the callback to complete.
360 std::forward_list<Barrier*> barriers_;
361};
362
363void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
364 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
365 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
366 }
367 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
368 if (wait) {
369 maybe_barrier.emplace(0);
370 }
371 int wait_count = 0;
372 VisiblyInitializedCallback* callback = nullptr;
373 {
374 MutexLock lock(self, visibly_initialized_callback_lock_);
375 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
376 callback = visibly_initialized_callback_.release();
377 running_visibly_initialized_callbacks_.push_front(*callback);
378 }
379 if (wait) {
380 DCHECK(maybe_barrier.has_value());
381 Barrier* barrier = std::addressof(*maybe_barrier);
382 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
383 cb.AddBarrier(barrier);
384 ++wait_count;
385 }
386 }
387 }
388 if (callback != nullptr) {
389 callback->MakeVisible(self);
390 }
391 if (wait_count != 0) {
392 DCHECK(maybe_barrier.has_value());
393 maybe_barrier->Increment(self, wait_count);
394 }
395}
396
397void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
398 VisiblyInitializedCallback* callback) {
399 MutexLock lock(self, visibly_initialized_callback_lock_);
400 // Pass the barriers if requested.
401 for (Barrier* barrier : callback->GetAndClearBarriers()) {
402 barrier->Pass(self);
403 }
404 // Remove the callback from the list of running callbacks.
405 auto before = running_visibly_initialized_callbacks_.before_begin();
406 auto it = running_visibly_initialized_callbacks_.begin();
407 DCHECK(it != running_visibly_initialized_callbacks_.end());
408 while (std::addressof(*it) != callback) {
409 before = it;
410 ++it;
411 DCHECK(it != running_visibly_initialized_callbacks_.end());
412 }
413 running_visibly_initialized_callbacks_.erase_after(before);
414 // Reuse or destroy the callback object.
415 if (visibly_initialized_callback_ == nullptr) {
416 visibly_initialized_callback_.reset(callback);
417 } else {
418 delete callback;
419 }
420}
421
Alex Lightfb119572019-09-18 15:04:53 -0700422void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
423 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
424 if (cb != nullptr) {
425 cb->MakeVisible(self);
426 }
427 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
428 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
429}
430
Vladimir Markobf121912019-06-04 13:49:05 +0100431ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
432 Thread* self, Handle<mirror::Class> klass) {
433 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
434 // Thanks to the x86 memory model, we do not need any memory fences and
435 // we can immediately mark the class as visibly initialized.
436 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100437 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100438 return nullptr;
439 }
440 if (Runtime::Current()->IsActiveTransaction()) {
441 // Transactions are single-threaded, so we can mark the class as visibly intialized.
442 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
443 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100444 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100445 return nullptr;
446 }
447 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
448 MutexLock lock(self, visibly_initialized_callback_lock_);
449 if (visibly_initialized_callback_ == nullptr) {
450 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
451 }
452 DCHECK(!visibly_initialized_callback_->IsFull());
453 visibly_initialized_callback_->AddClass(self, klass.Get());
454
455 if (visibly_initialized_callback_->IsFull()) {
456 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
457 running_visibly_initialized_callbacks_.push_front(*callback);
458 return callback;
459 } else {
460 return nullptr;
461 }
462}
463
Vladimir Marko86c87522020-05-11 16:55:55 +0100464const void* ClassLinker::RegisterNative(
465 Thread* self, ArtMethod* method, const void* native_method) {
466 CHECK(method->IsNative()) << method->PrettyMethod();
467 CHECK(native_method != nullptr) << method->PrettyMethod();
468 void* new_native_method = nullptr;
469 Runtime* runtime = Runtime::Current();
470 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
471 native_method,
472 /*out*/&new_native_method);
473 if (method->IsCriticalNative()) {
474 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
475 // Remove old registered method if any.
476 auto it = critical_native_code_with_clinit_check_.find(method);
477 if (it != critical_native_code_with_clinit_check_.end()) {
478 critical_native_code_with_clinit_check_.erase(it);
479 }
480 // To ensure correct memory visibility, we need the class to be visibly
481 // initialized before we can set the JNI entrypoint.
482 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
483 method->SetEntryPointFromJni(new_native_method);
484 } else {
485 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
486 }
487 } else {
488 method->SetEntryPointFromJni(new_native_method);
489 }
490 return new_native_method;
491}
492
493void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
494 CHECK(method->IsNative()) << method->PrettyMethod();
495 // Restore stub to lookup native pointer via dlsym.
496 if (method->IsCriticalNative()) {
497 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
498 auto it = critical_native_code_with_clinit_check_.find(method);
499 if (it != critical_native_code_with_clinit_check_.end()) {
500 critical_native_code_with_clinit_check_.erase(it);
501 }
502 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
503 } else {
504 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
505 }
506}
507
508const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
509 if (method->IsCriticalNative()) {
510 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
511 auto it = critical_native_code_with_clinit_check_.find(method);
512 if (it != critical_native_code_with_clinit_check_.end()) {
513 return it->second;
514 }
515 const void* native_code = method->GetEntryPointFromJni();
516 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
517 } else {
518 const void* native_code = method->GetEntryPointFromJni();
519 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
520 }
521}
522
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800523void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
524 bool wrap_in_no_class_def,
525 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700526 // The class failed to initialize on a previous attempt, so we want to throw
527 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
528 // failed in verification, in which case v2 5.4.1 says we need to re-throw
529 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800530 Runtime* const runtime = Runtime::Current();
531 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700532 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000533 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
534 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800535 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700536 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800537 } else {
538 extra = verify_error->AsThrowable()->Dump();
539 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700540 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800541 if (log) {
542 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
543 << ": " << extra;
544 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700545 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700546
David Sehr709b0702016-10-13 09:12:37 -0700547 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800548 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800549 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700550 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700551 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000552 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700553 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000554 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
555 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800556 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800557 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800558 }
Alex Lightd6251582016-10-31 11:12:30 -0700559 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
560 // might have meant to go down the earlier if statement with the original error but it got
561 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000562 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800563 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
564 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
565 // exception will be a cause.
566 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700567 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700568 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700569 }
570}
571
Brian Carlstromb23eab12014-10-08 17:55:21 -0700572static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700573 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700574 if (VLOG_IS_ON(class_linker)) {
575 std::string temp;
576 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000577 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700578 }
579}
580
581static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700582 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700583 Thread* self = Thread::Current();
584 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700585
586 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700587 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700588
David Srbecky346fd962020-07-27 16:51:00 +0100589 // Boot classpath classes should not fail initialization. This is a consistency debug check.
590 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800591 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800592 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800593 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
594 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
595 // could have caused the error.
596 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
597 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
598 << " failed initialization: "
599 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800600 }
601
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700602 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700603 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
604 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700605
Elliott Hughesa4f94742012-05-29 16:28:38 -0700606 // We only wrap non-Error exceptions; an Error can just be used as-is.
607 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000608 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700609 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700610 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700611}
612
Andreas Gampe87658f32019-04-18 18:39:02 +0000613ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700614 : boot_class_table_(new ClassTable()),
615 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800616 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800617 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700618 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000619 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700620 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000621 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000622 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000623 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800624 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800625 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100626 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800627 quick_to_interpreter_bridge_trampoline_(nullptr),
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000628 nterp_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700629 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100630 visibly_initialized_callback_lock_("visibly initialized callback lock"),
631 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100632 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
633 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700634 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
635 // For CHA disabled during Aot, see b/34193647.
636
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700637 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700638 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
639 "Array cache size wrong.");
640 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700641}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700642
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800643void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700644 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800645 if (c2 == nullptr) {
646 LOG(FATAL) << "Could not find class " << descriptor;
647 UNREACHABLE();
648 }
649 if (c1.Get() != c2) {
650 std::ostringstream os1, os2;
651 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
652 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
653 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
654 << ". This is most likely the result of a broken build. Make sure that "
655 << "libcore and art projects match.\n\n"
656 << os1.str() << "\n\n" << os2.str();
657 UNREACHABLE();
658 }
659}
660
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800661bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
662 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800663 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700664
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 Thread* const self = Thread::Current();
666 Runtime* const runtime = Runtime::Current();
667 gc::Heap* const heap = runtime->GetHeap();
668
Jeff Haodcdc85b2015-12-04 14:06:18 -0800669 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700670 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700671
Mathieu Chartiere401d142015-04-22 13:56:20 -0700672 // Use the pointer size from the runtime since we are probably creating the image.
673 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
674
Elliott Hughes30646832011-10-13 16:59:46 -0700675 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700676 // 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 -0800677 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700678 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700679 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700680 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
681 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000682 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100683 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800684 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100685 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700686 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700687 if (kUseBakerReadBarrier) {
688 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800689 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700690 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700691 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800692 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700693 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700694
Elliott Hughes418d20f2011-09-22 14:00:39 -0700695 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700696 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700697 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700698 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700699 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700700
Ian Rogers23435d02012-09-24 11:23:12 -0700701 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700702 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700703 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800704 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700705 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000707 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700708
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700709 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800710 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
711 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100712 runtime->SetSentinel(heap->AllocNonMovableObject(self,
713 java_lang_Object.Get(),
714 java_lang_Object->GetObjectSize(),
715 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700716
Igor Murashkin86083f72017-10-27 10:59:04 -0700717 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000718 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700719 // It might seem the lock here is unnecessary, however all the SubtypeCheck
720 // functions are annotated to require locks all the way down.
721 //
722 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
723 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000724 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
725 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700726 }
727
Ian Rogers23435d02012-09-24 11:23:12 -0700728 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700729 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700730 AllocClass(self, java_lang_Class.Get(),
731 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700732 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700733
Roland Levillain0e840272018-08-23 19:55:30 +0100734 // Setup java.lang.String.
735 //
736 // We make this class non-movable for the unlikely case where it were to be
737 // moved by a sticky-bit (minor) collection when using the Generational
738 // Concurrent Copying (CC) collector, potentially creating a stale reference
739 // in the `klass_` field of one of its instances allocated in the Large-Object
740 // Space (LOS) -- see the comment about the dirty card scanning logic in
741 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700742 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700743 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100744 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700745 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000746 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400747
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700748 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700749 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700750 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700751 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000752 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700753
Ian Rogers23435d02012-09-24 11:23:12 -0700754 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700755 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100756 mirror::ObjectArray<mirror::Class>::Alloc(self,
757 object_array_class.Get(),
758 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700759 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100760 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
761 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
762 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
763 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100764 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
765 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700766
Mathieu Chartier6beced42016-11-15 15:51:31 -0800767 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
768 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
769
Vladimir Marko02610552018-06-04 14:38:00 +0100770 // Create array interface entries to populate once we can load system classes.
771 object_array_class->SetIfTable(AllocIfTable(self, 2));
772 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
773
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700774 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100775 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
776 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
777 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
778 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
779 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
780 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
781 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
782 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
783 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700784
Vladimir Marko70e2a762019-07-12 16:49:00 +0100785 // Allocate the primitive array classes. We need only the native pointer
786 // array at this point (int[] or long[], depending on architecture) but
787 // we shall perform the same setup steps for all primitive array classes.
788 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
789 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
790 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
791 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
792 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
793 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
794 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
795 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700796
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700797 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700798
Ian Rogers52813c92012-10-11 11:50:38 -0700799 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700800 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700801 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100802 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100803 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700804 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000805 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806
Alex Lightd6251582016-10-31 11:12:30 -0700807
808 // Setup dalvik.system.ClassExt
809 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
810 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100811 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000812 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700813
Mathieu Chartier66f19252012-09-18 08:57:04 -0700814 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700815 Handle<mirror::Class> object_array_string(hs.NewHandle(
816 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700817 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700818 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700820
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000821 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700822 // Create runtime resolution and imt conflict methods.
823 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000824 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
825 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700826
Ian Rogers23435d02012-09-24 11:23:12 -0700827 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
828 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
829 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800830 if (boot_class_path.empty()) {
831 *error_msg = "Boot classpath is empty.";
832 return false;
833 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800834 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800835 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800836 *error_msg = "Null dex file.";
837 return false;
838 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800839 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800840 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700841 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700842
843 // now we can use FindSystemClass
844
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700845 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
846 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700847 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800848 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700849 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000850 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000851 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700852 quick_resolution_trampoline_ = GetQuickResolutionStub();
853 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000854 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700855 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000856 nterp_trampoline_ = interpreter::GetNterpEntryPoint();
Alex Light64ad14d2014-08-19 14:23:13 -0700857 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700858
Alex Lightd6251582016-10-31 11:12:30 -0700859 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000860 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800861 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700862 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000863 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800864 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000865 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800866 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700867 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000868 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700869 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
870 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700871
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800872 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
873 // in class_table_.
874 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700875
Vladimir Marko70e2a762019-07-12 16:49:00 +0100876 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
877 // arrays - can't be done until Object has a vtable and component classes are loaded.
878 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
879 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
880 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
881 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
882 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
883 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
884 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
885 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
886 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
887 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
888 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889
Ian Rogers23435d02012-09-24 11:23:12 -0700890 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700891 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800892 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700893 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800894 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700895 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
896 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100897 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
898 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700899
David Srbecky346fd962020-07-27 16:51:00 +0100900 // Check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread suspension.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700901 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000902 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700903 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000904 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700905 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000906 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700907 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000908 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700909
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700910 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100911 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700912
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800913 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700914
Ian Rogers23435d02012-09-24 11:23:12 -0700915 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100916 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
917 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700918
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700919 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100920 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700921 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100922 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700923
924 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700925 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
926 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100927 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700928
929 // Create java.lang.reflect.Constructor.class root and array root.
930 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
931 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100932 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700933 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
934 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100935 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700936
937 // Create java.lang.reflect.Method.class root and array root.
938 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
939 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100940 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700941 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
942 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100943 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700944
Orion Hodson005ac512017-10-24 15:43:43 +0100945 // Create java.lang.invoke.CallSite.class root
946 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
947 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100948 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100949
Narayan Kamathafa48272016-08-03 12:46:58 +0100950 // Create java.lang.invoke.MethodType.class root
951 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
952 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100953 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100954
955 // Create java.lang.invoke.MethodHandleImpl.class root
956 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
957 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100958 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100959 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100960
Orion Hodsonc069a302017-01-18 09:23:12 +0000961 // Create java.lang.invoke.MethodHandles.Lookup.class root
962 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
963 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100964 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000965
Orion Hodson005ac512017-10-24 15:43:43 +0100966 // Create java.lang.invoke.VarHandle.class root
967 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000968 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100969 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100970
971 // Create java.lang.invoke.FieldVarHandle.class root
972 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
973 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100974 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100975
976 // Create java.lang.invoke.ArrayElementVarHandle.class root
977 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
978 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100979 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100980
981 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
982 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
983 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100984 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100985
986 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
987 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
988 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100989 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000990
Narayan Kamath000e1882016-10-24 17:14:25 +0100991 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
992 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100993 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100994
Brian Carlstrom1f870082011-08-23 16:02:11 -0700995 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700996 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000997 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800998 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700999 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001000 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
1001 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001002 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001003 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001004 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001005 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001006 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001007 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001008 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001009 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001010 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001011 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001012 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001013 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001014
Ian Rogers23435d02012-09-24 11:23:12 -07001015 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001016 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001017 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001018 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001019 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001020
jeffhao8cd6dda2012-02-22 10:15:34 -08001021 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001022 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001023 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001024 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001025 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001026 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1027 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1028 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001029 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001030 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1031 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001032
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001033 // Create conflict tables that depend on the class linker.
1034 runtime->FixupConflictTables();
1035
Ian Rogers98379392014-02-24 16:53:16 -08001036 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001037
Brian Carlstroma004aa92012-02-08 18:05:09 -08001038 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001039
1040 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001041}
1042
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001043static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1044 REQUIRES_SHARED(Locks::mutator_lock_) {
1045 // Find String.<init> -> StringFactory bindings.
1046 ObjPtr<mirror::Class> string_factory_class =
1047 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1048 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001049 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001050 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1051 // Update the primordial thread.
1052 self->InitStringEntryPoints();
1053}
1054
Ian Rogers98379392014-02-24 16:53:16 -08001055void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001056 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001057
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001058 CreateStringInitBindings(self, this);
1059
Brian Carlstrom16192862011-09-12 17:50:06 -07001060 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001061 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001062 // as the types of the field can't be resolved prior to the runtime being
1063 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001064 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001065 Handle<mirror::Class> java_lang_ref_Reference =
1066 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001067 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1068 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001069
Mathieu Chartierc7853442015-03-27 14:35:38 -07001070 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001071 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1072 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001073
Mathieu Chartierc7853442015-03-27 14:35:38 -07001074 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001075 CHECK_STREQ(queue->GetName(), "queue");
1076 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001077
Mathieu Chartierc7853442015-03-27 14:35:38 -07001078 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001079 CHECK_STREQ(queueNext->GetName(), "queueNext");
1080 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001081
Mathieu Chartierc7853442015-03-27 14:35:38 -07001082 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001083 CHECK_STREQ(referent->GetName(), "referent");
1084 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001085
Mathieu Chartierc7853442015-03-27 14:35:38 -07001086 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001087 CHECK_STREQ(zombie->GetName(), "zombie");
1088 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001089
Brian Carlstroma663ea52011-08-19 23:33:41 -07001090 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001091 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001092 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001093 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001094 CHECK(klass != nullptr);
1095 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001096 // note SetClassRoot does additional validation.
1097 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001098 }
1099
Vladimir Marko02610552018-06-04 14:38:00 +01001100 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001101
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001102 // disable the slow paths in FindClass and CreatePrimitiveClass now
1103 // that Object, Class, and Object[] are setup
1104 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001105
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001106 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1107 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1108 // ensure that the class will be initialized.
1109 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001110 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001111
1112 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1113 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1114 // Strange, but don't crash.
1115 LOG(WARNING) << "Could not prepare StackOverflowError.";
1116 self->ClearException();
1117 }
1118 }
1119
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001120 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001121}
1122
Vladimir Markodcfcce42018-06-27 10:00:28 +00001123void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001124 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1125 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001126 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001127 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001128 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001129 if (!EnsureInitialized(self, h_class, true, true)) {
1130 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1131 << ": " << self->GetException()->Dump();
1132 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001133 } else {
1134 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001135 }
1136 }
1137}
1138
Vladimir Marko43354742021-02-03 15:37:01 +00001139static void InitializeObjectVirtualMethodHashes(ObjPtr<mirror::Class> java_lang_Object,
1140 PointerSize pointer_size,
1141 /*out*/ ArrayRef<uint32_t> virtual_method_hashes)
1142 REQUIRES_SHARED(Locks::mutator_lock_) {
1143 ArraySlice<ArtMethod> virtual_methods = java_lang_Object->GetVirtualMethods(pointer_size);
1144 DCHECK_EQ(virtual_method_hashes.size(), virtual_methods.size());
1145 for (size_t i = 0; i != virtual_method_hashes.size(); ++i) {
1146 const char* name = virtual_methods[i].GetName();
1147 virtual_method_hashes[i] = ComputeModifiedUtf8Hash(name);
1148 }
1149}
1150
Jeff Haodcdc85b2015-12-04 14:06:18 -08001151struct TrampolineCheckData {
1152 const void* quick_resolution_trampoline;
1153 const void* quick_imt_conflict_trampoline;
1154 const void* quick_generic_jni_trampoline;
1155 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001156 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001157 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001158 ArtMethod* m;
1159 bool error;
1160};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001161
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001162bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1163 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001164 CHECK(!init_done_);
1165
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001166 Runtime* const runtime = Runtime::Current();
1167 Thread* const self = Thread::Current();
1168 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001169 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1170 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001171 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1172 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001173 if (!ValidPointerSize(pointer_size_unchecked)) {
1174 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001175 return false;
1176 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001177 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001178 if (!runtime->IsAotCompiler()) {
1179 // Only the Aot compiler supports having an image with a different pointer size than the
1180 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1181 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001182 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001183 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001184 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001185 sizeof(void*));
1186 return false;
1187 }
1188 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001189 DCHECK(!runtime->HasResolutionMethod());
1190 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1191 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1192 runtime->SetImtUnimplementedMethod(
1193 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1194 runtime->SetCalleeSaveMethod(
1195 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1196 CalleeSaveType::kSaveAllCalleeSaves);
1197 runtime->SetCalleeSaveMethod(
1198 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1199 CalleeSaveType::kSaveRefsOnly);
1200 runtime->SetCalleeSaveMethod(
1201 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1202 CalleeSaveType::kSaveRefsAndArgs);
1203 runtime->SetCalleeSaveMethod(
1204 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1205 CalleeSaveType::kSaveEverything);
1206 runtime->SetCalleeSaveMethod(
1207 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1208 CalleeSaveType::kSaveEverythingForClinit);
1209 runtime->SetCalleeSaveMethod(
1210 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1211 CalleeSaveType::kSaveEverythingForSuspendCheck);
1212
Jeff Haodcdc85b2015-12-04 14:06:18 -08001213 std::vector<const OatFile*> oat_files =
1214 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1215 DCHECK(!oat_files.empty());
1216 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001217 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001218 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001219 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1220 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1221 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1222 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001223 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001224 if (kIsDebugBuild) {
1225 // Check that the other images use the same trampoline.
1226 for (size_t i = 1; i < oat_files.size(); ++i) {
1227 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001228 const void* ith_jni_dlsym_lookup_trampoline_ =
1229 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001230 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1231 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001232 const void* ith_quick_resolution_trampoline =
1233 ith_oat_header.GetQuickResolutionTrampoline();
1234 const void* ith_quick_imt_conflict_trampoline =
1235 ith_oat_header.GetQuickImtConflictTrampoline();
1236 const void* ith_quick_generic_jni_trampoline =
1237 ith_oat_header.GetQuickGenericJniTrampoline();
1238 const void* ith_quick_to_interpreter_bridge_trampoline =
1239 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001240 const void* ith_nterp_trampoline =
1241 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001242 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001243 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001244 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001245 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1246 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001247 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1248 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001249 // Make sure that all methods in this image do not contain those trampolines as
1250 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1251 TrampolineCheckData data;
1252 data.error = false;
1253 data.pointer_size = GetImagePointerSize();
1254 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1255 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1256 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1257 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001258 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001259 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001260 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1261 if (obj->IsClass()) {
1262 ObjPtr<mirror::Class> klass = obj->AsClass();
1263 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1264 const void* entrypoint =
1265 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1266 if (entrypoint == data.quick_resolution_trampoline ||
1267 entrypoint == data.quick_imt_conflict_trampoline ||
1268 entrypoint == data.quick_generic_jni_trampoline ||
1269 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1270 data.m = &m;
1271 data.error = true;
1272 return;
1273 }
1274 }
1275 }
1276 };
1277 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001278 if (data.error) {
1279 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001280 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001281 *error_msg = "Found an ArtMethod with a bad entrypoint";
1282 return false;
1283 }
1284 }
1285 }
1286 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001287
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001288 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001289 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001290 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001291 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001292
Vladimir Marko024d69f2019-06-13 10:52:32 +01001293 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1294 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1295 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1296 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1297 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1298 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001299
Vladimir Markod1908512018-11-22 14:57:28 +00001300 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001301 // Boot class loader, use a null handle.
1302 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001303 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001304 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001305 /*out*/&dex_files,
1306 error_msg)) {
1307 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001308 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001309 // Append opened dex files at the end.
1310 boot_dex_files_.insert(boot_dex_files_.end(),
1311 std::make_move_iterator(dex_files.begin()),
1312 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001313 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001314 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1315 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1316 }
Vladimir Marko43354742021-02-03 15:37:01 +00001317 InitializeObjectVirtualMethodHashes(GetClassRoot<mirror::Object>(this),
1318 image_pointer_size_,
1319 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Ian Rogers98379392014-02-24 16:53:16 -08001320 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001321
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001322 VLOG(startup) << __FUNCTION__ << " exiting";
1323 return true;
1324}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001325
Vladimir Marko4433c432018-12-04 14:57:47 +00001326void ClassLinker::AddExtraBootDexFiles(
1327 Thread* self,
1328 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1329 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001330 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001331 if (kIsDebugBuild) {
1332 for (const auto& boot_dex_file : boot_dex_files_) {
1333 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1334 }
1335 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001336 boot_dex_files_.push_back(std::move(dex_file));
1337 }
1338}
1339
Jeff Hao5872d7c2016-04-27 11:07:41 -07001340bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001341 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001342 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001343 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1344 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001345}
1346
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001347class CHAOnDeleteUpdateClassVisitor {
1348 public:
1349 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1350 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1351 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1352 self_(Thread::Current()) {}
1353
1354 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1355 // This class is going to be unloaded. Tell CHA about it.
1356 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1357 return true;
1358 }
1359 private:
1360 const LinearAlloc* allocator_;
1361 const ClassHierarchyAnalysis* cha_;
1362 const PointerSize pointer_size_;
1363 const Thread* self_;
1364};
1365
Chris Wailes0c61be42018-09-26 17:27:34 -07001366/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001367 * A class used to ensure that all references to strings interned in an AppImage have been
1368 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001369 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001370class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001371 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001372 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1373 const InternTable::UnorderedSet& image_interns)
1374 : space_(space),
1375 image_interns_(image_interns),
1376 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001377
Chris Wailes0c61be42018-09-26 17:27:34 -07001378 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001379 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001380 if (referred_obj != nullptr &&
1381 space_.HasAddress(referred_obj.Ptr()) &&
1382 referred_obj->IsString()) {
1383 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001384 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1385 if (it != image_interns_.end() && it->Read() == referred_str) {
1386 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001387 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001388 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001389 }
1390
Chris Wailes0c61be42018-09-26 17:27:34 -07001391 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001392 mirror::CompressedReference<mirror::Object>* root) const
1393 REQUIRES_SHARED(Locks::mutator_lock_) {
1394 if (!root->IsNull()) {
1395 VisitRoot(root);
1396 }
1397 }
1398
Chris Wailes0c61be42018-09-26 17:27:34 -07001399 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001400 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001401 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001402 }
1403
1404 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001405 void operator()(ObjPtr<mirror::Object> obj,
1406 MemberOffset offset,
1407 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001408 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001409 // References within image or across images don't need a read barrier.
1410 ObjPtr<mirror::Object> referred_obj =
1411 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1412 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001413 }
1414
1415 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1416 ObjPtr<mirror::Reference> ref) const
1417 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001418 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001419 }
1420
Vladimir Marko8e05f092019-06-10 11:10:38 +01001421 size_t GetCount() const {
1422 return count_;
1423 }
1424
1425 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001426 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001427 const InternTable::UnorderedSet& image_interns_;
1428 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001429};
1430
Chris Wailes0c61be42018-09-26 17:27:34 -07001431/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001432 * This function counts references to strings interned in the AppImage.
1433 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001434 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001435size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1436 const InternTable::UnorderedSet& image_interns)
1437 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001438 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1439 const ImageHeader& image_header = space.GetImageHeader();
1440 const uint8_t* target_base = space.GetMemMap()->Begin();
1441 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001442
1443 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1444 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001445
Vladimir Marko8e05f092019-06-10 11:10:38 +01001446 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001447 bitmap->VisitMarkedRange(objects_begin,
1448 objects_end,
1449 [&space, &visitor](mirror::Object* obj)
1450 REQUIRES_SHARED(Locks::mutator_lock_) {
1451 if (space.HasAddress(obj)) {
1452 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001453 obj->VisitReferences</* kVisitNativeRoots= */ true,
1454 kVerifyNone,
1455 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001456 } else {
1457 // Don't visit native roots for non-dex-cache as they can't contain
1458 // native references to strings. This is verified during compilation
1459 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001460 obj->VisitReferences</* kVisitNativeRoots= */ false,
1461 kVerifyNone,
1462 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001463 }
1464 }
1465 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001466 return visitor.GetCount();
1467}
1468
1469template <typename Visitor>
1470static void VisitInternedStringReferences(
1471 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001472 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1473 const uint8_t* target_base = space->Begin();
1474 const ImageSection& sro_section =
1475 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1476 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1477
1478 VLOG(image)
1479 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1480 << num_string_offsets;
1481
1482 const auto* sro_base =
1483 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1484
1485 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1486 uint32_t base_offset = sro_base[offset_index].first;
1487
David Srbecky86d6cd52020-12-02 18:13:10 +00001488 uint32_t raw_member_offset = sro_base[offset_index].second;
1489 DCHECK_ALIGNED(base_offset, 2);
1490 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001491
David Srbecky86d6cd52020-12-02 18:13:10 +00001492 ObjPtr<mirror::Object> obj_ptr =
1493 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1494 MemberOffset member_offset(raw_member_offset);
1495 ObjPtr<mirror::String> referred_string =
1496 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001497 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001498 kWithoutReadBarrier,
1499 /* kIsVolatile= */ false>(member_offset);
1500 DCHECK(referred_string != nullptr);
1501
1502 ObjPtr<mirror::String> visited = visitor(referred_string);
1503 if (visited != referred_string) {
1504 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1505 /* kCheckTransaction= */ false,
1506 kVerifyNone,
1507 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001508 }
1509 }
1510}
1511
1512static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1513 REQUIRES_SHARED(Locks::mutator_lock_) {
1514 InternTable::UnorderedSet image_interns;
1515 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1516 if (section.Size() > 0) {
1517 size_t read_count;
1518 const uint8_t* data = space->Begin() + section.Offset();
1519 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1520 image_set.swap(image_interns);
1521 }
1522 size_t num_recorded_refs = 0u;
1523 VisitInternedStringReferences(
1524 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001525 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1526 REQUIRES_SHARED(Locks::mutator_lock_) {
1527 auto it = image_interns.find(GcRoot<mirror::String>(str));
1528 CHECK(it != image_interns.end());
1529 CHECK(it->Read() == str);
1530 ++num_recorded_refs;
1531 return str;
1532 });
1533 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1534 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001535}
1536
Andreas Gampe2af99022017-04-25 08:32:59 -07001537// new_class_set is the set of classes that were read from the class table section in the image.
1538// If there was no class table section, it is null.
1539// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001540class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001541 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001542 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001543 ClassLinker* class_linker,
1544 gc::space::ImageSpace* space,
1545 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001546 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001547 REQUIRES(!Locks::dex_lock_)
1548 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001549
Chris Wailesfbeef462018-10-19 14:16:35 -07001550 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001551 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001552};
1553
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001554void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001555 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001556 gc::space::ImageSpace* space,
1557 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001558 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001559 REQUIRES(!Locks::dex_lock_)
1560 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001561 ScopedTrace app_image_timing("AppImage:Updating");
1562
Vladimir Marko8e05f092019-06-10 11:10:38 +01001563 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1564 // In debug build, verify the string references before applying
1565 // the Runtime::LoadAppImageStartupCache() option.
1566 VerifyInternedStringReferences(space);
1567 }
1568
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001569 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001570 Runtime* const runtime = Runtime::Current();
1571 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001572 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001573 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001574 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001575 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001576 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001577 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001578 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001579 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001580 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001581 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001582 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001583 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001584 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001585
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001586 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001587 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001588 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001589
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001590 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001591 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001592 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001593 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1594 header.VisitPackedArtMethods([&](ArtMethod& method)
1595 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1596 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1597 if (klass != nullptr) {
1598 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1599 }
1600 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001601 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001602}
1603
Chris Wailesfbeef462018-10-19 14:16:35 -07001604void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001605 // Iterate over the string reference offsets stored in the image and intern
1606 // the strings they point to.
1607 ScopedTrace timing("AppImage:InternString");
1608
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001609 Runtime* const runtime = Runtime::Current();
1610 InternTable* const intern_table = runtime->GetInternTable();
1611
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001612 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1613 // for faster lookup.
1614 // TODO: Optimize with a bitmap or bloom filter
1615 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001616 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001617 REQUIRES_SHARED(Locks::mutator_lock_)
1618 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001619 const size_t non_boot_image_strings = intern_table->CountInterns(
1620 /*visit_boot_images=*/false,
1621 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001622 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001623 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1624 // Visit the smaller of the two sets to compute the intersection.
1625 if (interns.size() < non_boot_image_strings) {
1626 for (auto it = interns.begin(); it != interns.end(); ) {
1627 ObjPtr<mirror::String> string = it->Read();
1628 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1629 if (existing == nullptr) {
1630 existing = intern_table->LookupStrongLocked(string);
1631 }
1632 if (existing != nullptr) {
1633 intern_remap.Put(string.Ptr(), existing.Ptr());
1634 it = interns.erase(it);
1635 } else {
1636 ++it;
1637 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001638 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001639 } else {
1640 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1641 REQUIRES_SHARED(Locks::mutator_lock_)
1642 REQUIRES(Locks::intern_table_lock_) {
1643 auto it = interns.find(root);
1644 if (it != interns.end()) {
1645 ObjPtr<mirror::String> existing = root.Read();
1646 intern_remap.Put(it->Read(), existing.Ptr());
1647 it = interns.erase(it);
1648 }
1649 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1650 }
David Srbecky346fd962020-07-27 16:51:00 +01001651 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001652 if (kIsDebugBuild) {
1653 for (GcRoot<mirror::String>& root : interns) {
1654 ObjPtr<mirror::String> string = root.Read();
1655 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1656 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001657 }
1658 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001659 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001660 intern_table->AddImageStringsToTable(space, func);
1661 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001662 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001663 VisitInternedStringReferences(
1664 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001665 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1666 auto it = intern_remap.find(str.Ptr());
1667 if (it != intern_remap.end()) {
1668 return ObjPtr<mirror::String>(it->second);
1669 }
1670 return str;
1671 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001672 }
1673}
1674
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001675static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1676 const char* location,
1677 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001678 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001679 DCHECK(error_msg != nullptr);
1680 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001681 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001682 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001683 return std::unique_ptr<const DexFile>();
1684 }
1685 std::string inner_error_msg;
1686 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1687 if (dex_file == nullptr) {
1688 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1689 location,
1690 oat_file->GetLocation().c_str(),
1691 inner_error_msg.c_str());
1692 return std::unique_ptr<const DexFile>();
1693 }
1694
1695 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1696 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1697 location,
1698 dex_file->GetLocationChecksum(),
1699 oat_dex_file->GetDexFileLocationChecksum());
1700 return std::unique_ptr<const DexFile>();
1701 }
1702 return dex_file;
1703}
1704
1705bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1706 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1707 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001708 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001709 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001710 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001711 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001712 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001713 dex_caches_object->AsObjectArray<mirror::DexCache>();
1714 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001715 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001716 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1717 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1718 dex_file_location.c_str(),
1719 error_msg);
1720 if (dex_file == nullptr) {
1721 return false;
1722 }
1723 dex_cache->SetDexFile(dex_file.get());
1724 out_dex_files->push_back(std::move(dex_file));
1725 }
1726 return true;
1727}
1728
Andreas Gampe0793bec2016-12-01 11:37:33 -08001729// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1730// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001731class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001732 public:
1733 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1734 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001735 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001736 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1737 DCHECK(obj != nullptr);
1738 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1739 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1740 if (obj->IsClass()) {
1741 auto klass = obj->AsClass();
1742 for (ArtField& field : klass->GetIFields()) {
1743 CHECK_EQ(field.GetDeclaringClass(), klass);
1744 }
1745 for (ArtField& field : klass->GetSFields()) {
1746 CHECK_EQ(field.GetDeclaringClass(), klass);
1747 }
Orion Hodson5880c772020-07-28 20:12:08 +01001748 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001749 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001750 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001751 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001752 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001753 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001754 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001755 }
1756 if (klass->ShouldHaveImt()) {
1757 ImTable* imt = klass->GetImt(pointer_size);
1758 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001759 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001760 }
1761 }
1762 if (klass->ShouldHaveEmbeddedVTable()) {
1763 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001764 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001765 }
1766 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001767 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001768 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1769 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001770 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001771 }
1772 }
1773 }
1774 };
1775 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001776 }
1777
Andreas Gampe0793bec2016-12-01 11:37:33 -08001778 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001779 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001780 : spaces_(heap->GetBootImageSpaces()),
1781 pointer_size_(class_linker->GetImagePointerSize()) {
1782 space_begin_.reserve(spaces_.size());
1783 method_sections_.reserve(spaces_.size());
1784 runtime_method_sections_.reserve(spaces_.size());
1785 for (gc::space::ImageSpace* space : spaces_) {
1786 space_begin_.push_back(space->Begin());
1787 auto& header = space->GetImageHeader();
1788 method_sections_.push_back(&header.GetMethodsSection());
1789 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1790 }
1791 }
1792
Orion Hodson5880c772020-07-28 20:12:08 +01001793 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001794 REQUIRES_SHARED(Locks::mutator_lock_) {
1795 if (m->IsRuntimeMethod()) {
1796 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1797 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1798 } else if (m->IsCopied()) {
1799 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1800 } else if (expected_class != nullptr) {
1801 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1802 }
1803 if (!spaces_.empty()) {
1804 bool contains = false;
1805 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1806 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1807 contains = method_sections_[i]->Contains(offset) ||
1808 runtime_method_sections_[i]->Contains(offset);
1809 }
1810 CHECK(contains) << m << " not found";
1811 }
1812 }
1813
Orion Hodson5880c772020-07-28 20:12:08 +01001814 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1815 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001816 REQUIRES_SHARED(Locks::mutator_lock_) {
1817 CHECK(arr != nullptr);
1818 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1819 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1820 // expected_class == null means we are a dex cache.
1821 if (expected_class != nullptr) {
1822 CHECK(method != nullptr);
1823 }
1824 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001825 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001826 }
1827 }
1828 }
1829
Andreas Gampe0793bec2016-12-01 11:37:33 -08001830 const std::vector<gc::space::ImageSpace*>& spaces_;
1831 const PointerSize pointer_size_;
1832
1833 // Cached sections from the spaces.
1834 std::vector<const uint8_t*> space_begin_;
1835 std::vector<const ImageSection*> method_sections_;
1836 std::vector<const ImageSection*> runtime_method_sections_;
1837};
1838
Andreas Gampebe7af222017-07-25 09:57:28 -07001839static void VerifyAppImage(const ImageHeader& header,
1840 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001841 ClassTable* class_table,
1842 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001843 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001844 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1845 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1846 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1847 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1848 << mirror::Class::PrettyClass(klass);
1849 }
1850 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001851 {
1852 // Verify that all direct interfaces of classes in the class table are also resolved.
1853 std::vector<ObjPtr<mirror::Class>> classes;
1854 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1855 REQUIRES_SHARED(Locks::mutator_lock_) {
1856 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1857 classes.push_back(klass);
1858 }
1859 return true;
1860 };
1861 class_table->Visit(verify_direct_interfaces_in_table);
1862 Thread* self = Thread::Current();
1863 for (ObjPtr<mirror::Class> klass : classes) {
1864 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1865 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1866 << klass->PrettyDescriptor() << " iface #" << i;
1867 }
1868 }
1869 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001870}
1871
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001872bool ClassLinker::AddImageSpace(
1873 gc::space::ImageSpace* space,
1874 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001875 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1876 std::string* error_msg) {
1877 DCHECK(out_dex_files != nullptr);
1878 DCHECK(error_msg != nullptr);
1879 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001880 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001881 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001882 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001883 DCHECK(dex_caches_object != nullptr);
1884 Runtime* const runtime = Runtime::Current();
1885 gc::Heap* const heap = runtime->GetHeap();
1886 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001887 // Check that the image is what we are expecting.
1888 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1889 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1890 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1891 image_pointer_size_);
1892 return false;
1893 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001894 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1895 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1896 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1897 expected_image_roots,
1898 header.GetImageRoots()->GetLength());
1899 return false;
1900 }
1901 StackHandleScope<3> hs(self);
1902 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1903 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1904 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1905 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001906 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001907 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1908 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001909 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001910 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001911 *error_msg = StringPrintf("Expected %d class roots but got %d",
1912 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001913 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001914 return false;
1915 }
1916 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001917 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1918 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1919 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001920 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1921 return false;
1922 }
1923 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001924 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001925 if (oat_file->GetOatHeader().GetDexFileCount() !=
1926 static_cast<uint32_t>(dex_caches->GetLength())) {
1927 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1928 "image";
1929 return false;
1930 }
1931
Alex Lighta9bbc082019-11-14 14:51:41 -08001932 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001933 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001934 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1935 dex_file_location.c_str(),
1936 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001937 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001938 return false;
1939 }
1940
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001941 LinearAlloc* linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader.Get());
1942 DCHECK(linear_alloc != nullptr);
1943 DCHECK_EQ(linear_alloc == Runtime::Current()->GetLinearAlloc(), !app_image);
David Srbecky86d6cd52020-12-02 18:13:10 +00001944 {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001945 // Native fields are all null. Initialize them and allocate native memory.
David Srbecky86d6cd52020-12-02 18:13:10 +00001946 WriterMutexLock mu(self, *Locks::dex_lock_);
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001947 dex_cache->InitializeNativeFields(dex_file.get(), linear_alloc);
David Srbecky86d6cd52020-12-02 18:13:10 +00001948 }
1949 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001950 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001951 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001952 }
1953 out_dex_files->push_back(std::move(dex_file));
1954 }
1955
1956 if (app_image) {
1957 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001958 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001959 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1960 *error_msg = "Unexpected BootClassLoader in app image";
1961 return false;
1962 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 }
1964
Orion Hodson5880c772020-07-28 20:12:08 +01001965 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001966 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001967 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001968 }
1969 }
1970
1971 // Set entry point to interpreter if in InterpretOnly mode.
1972 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001973 // Set image methods' entry point to interpreter.
1974 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1975 if (!method.IsRuntimeMethod()) {
1976 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001977 if (!method.IsNative() && !method.IsResolutionMethod()) {
1978 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1979 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001980 }
1981 }
1982 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001983 }
1984
Nicolas Geoffray47171752020-08-31 15:03:20 +01001985 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001986 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001987 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001988 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001989 // In the image, the `data` pointer field of the ArtMethod contains the code
1990 // item offset. Change this to the actual pointer to the code item.
1991 if (method.HasCodeItem()) {
1992 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1993 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01001994 method.SetCodeItem(code_item);
Nicolas Geoffray47171752020-08-31 15:03:20 +01001995 }
1996 // Set image methods' entry point that point to the interpreter bridge to the
1997 // nterp entry point.
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001998 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1999 if (can_use_nterp) {
Nicolas Geoffrayb1cf8372021-02-02 13:32:20 +00002000 DCHECK(!NeedsClinitCheckBeforeCall(&method) ||
2001 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00002002 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
2003 } else {
2004 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2005 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01002006 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002007 }, space->Begin(), image_pointer_size_);
2008 }
2009
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002010 if (runtime->IsVerificationSoftFail()) {
2011 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2012 if (!method.IsNative() && method.IsInvokable()) {
2013 method.ClearSkipAccessChecks();
2014 }
2015 }, space->Begin(), image_pointer_size_);
2016 }
2017
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002018 ClassTable* class_table = nullptr;
2019 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002020 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002021 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002022 }
2023 // If we have a class table section, read it and use it for verification in
2024 // UpdateAppImageClassLoadersAndDexCaches.
2025 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002026 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002027 const bool added_class_table = class_table_section.Size() > 0u;
2028 if (added_class_table) {
2029 const uint64_t start_time2 = NanoTime();
2030 size_t read_count = 0;
2031 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2032 /*make copy*/false,
2033 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002034 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002035 }
2036 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002037 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002038
2039 {
2040 ScopedTrace trace("AppImage:UpdateClassLoaders");
2041 // Update class loader and resolved strings. If added_class_table is false, the resolved
2042 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002043 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002044 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002045 // Note: We probably don't need the read barrier unless we copy the app image objects into
2046 // the region space.
2047 ObjPtr<mirror::Class> klass(root.Read());
2048 // Do not update class loader for boot image classes where the app image
2049 // class loader is only the initiating loader but not the defining loader.
2050 // Avoid read barrier since we are comparing against null.
2051 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002052 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002053 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002054 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002055 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002056
Vladimir Marko305c38b2018-02-14 11:50:07 +00002057 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002058 // Every class in the app image has initially SubtypeCheckInfo in the
2059 // Uninitialized state.
2060 //
2061 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2062 // after class initialization is complete. The app image ClassStatus as-is
2063 // are almost all ClassStatus::Initialized, and being in the
2064 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2065 //
2066 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2067 //
2068 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002069 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002070 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2071 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002072 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002073 }
2074 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002075 }
2076 if (!oat_file->GetBssGcRoots().empty()) {
2077 // Insert oat file to class table for visiting .bss GC roots.
2078 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002079 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002080
Mathieu Chartier69731002016-03-02 16:08:31 -08002081 if (added_class_table) {
2082 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2083 class_table->AddClassSet(std::move(temp_set));
2084 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002085
Mathieu Chartier69731002016-03-02 16:08:31 -08002086 if (kIsDebugBuild && app_image) {
2087 // This verification needs to happen after the classes have been added to the class loader.
2088 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002089 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002090 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002091 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002092
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002093 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002094 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002095}
2096
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002097void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002098 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2099 // enabling tracing requires the mutator lock, there are no race conditions here.
2100 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002101 Thread* const self = Thread::Current();
2102 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002103 if (kUseReadBarrier) {
2104 // We do not track new roots for CC.
2105 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2106 kVisitRootFlagClearRootLog |
2107 kVisitRootFlagStartLoggingNewRoots |
2108 kVisitRootFlagStopLoggingNewRoots));
2109 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002110 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002111 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2112 // There is 3 GC cases to handle:
2113 // Non moving concurrent:
2114 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002115 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002116 //
2117 // Moving non-concurrent:
2118 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2119 // To prevent missing roots, this case needs to ensure that there is no
2120 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2121 // class which is in the class table.
2122 //
2123 // Moving concurrent:
2124 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2125 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002126 //
2127 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2128 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2129 // these objects.
2130 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002131 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002132 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002133 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002134 for (const ClassLoaderData& data : class_loaders_) {
2135 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2136 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2137 }
2138 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002139 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002140 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002141 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002142 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002143 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002144 // Concurrent moving GC marked new roots through the to-space invariant.
2145 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002146 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002147 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2148 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2149 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2150 if (old_ref != nullptr) {
2151 DCHECK(old_ref->IsClass());
2152 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2153 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2154 // Concurrent moving GC marked new roots through the to-space invariant.
2155 CHECK_EQ(new_ref, old_ref);
2156 }
2157 }
2158 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002159 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002160 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002161 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002162 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002163 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002164 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002165 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002166 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002167 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002168 }
2169 // We deliberately ignore the class roots in the image since we
2170 // handle image roots by using the MS/CMS rescanning of dirty cards.
2171}
2172
Brian Carlstroma663ea52011-08-19 23:33:41 -07002173// Keep in sync with InitCallback. Anything we visit, we need to
2174// reinit references to when reinitializing a ClassLinker from a
2175// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002176void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002177 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002178 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002179 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2180 // unloading if we are marking roots.
2181 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002182}
2183
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002184class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2185 public:
2186 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2187 : visitor_(visitor),
2188 done_(false) {}
2189
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002190 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002191 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002192 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002193 if (!done_ && class_table != nullptr) {
2194 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2195 if (!class_table->Visit(visitor)) {
2196 // If the visitor ClassTable returns false it means that we don't need to continue.
2197 done_ = true;
2198 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002199 }
2200 }
2201
2202 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002203 // Class visitor that limits the class visits from a ClassTable to the classes with
2204 // the provided defining class loader. This filter is used to avoid multiple visits
2205 // of the same class which can be recorded for multiple initiating class loaders.
2206 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2207 public:
2208 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2209 ClassVisitor* visitor)
2210 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2211
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002212 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002213 if (klass->GetClassLoader() != defining_class_loader_) {
2214 return true;
2215 }
2216 return (*visitor_)(klass);
2217 }
2218
Vladimir Marko0984e482019-03-27 16:41:41 +00002219 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002220 ClassVisitor* const visitor_;
2221 };
2222
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002223 ClassVisitor* const visitor_;
2224 // If done is true then we don't need to do any more visiting.
2225 bool done_;
2226};
2227
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002228void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002229 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002230 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2231 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002232 }
2233}
2234
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002235void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002236 Thread* const self = Thread::Current();
2237 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2238 // Not safe to have thread suspension when we are holding a lock.
2239 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002240 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002241 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002242 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002243 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002244 }
2245}
2246
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002247class GetClassesInToVector : public ClassVisitor {
2248 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002249 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002250 classes_.push_back(klass);
2251 return true;
2252 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002253 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002254};
2255
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002256class GetClassInToObjectArray : public ClassVisitor {
2257 public:
2258 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2259 : arr_(arr), index_(0) {}
2260
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002261 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002262 ++index_;
2263 if (index_ <= arr_->GetLength()) {
2264 arr_->Set(index_ - 1, klass);
2265 return true;
2266 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002267 return false;
2268 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002269
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002270 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002271 return index_ <= arr_->GetLength();
2272 }
2273
2274 private:
2275 mirror::ObjectArray<mirror::Class>* const arr_;
2276 int32_t index_;
2277};
2278
2279void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002280 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2281 // is avoiding duplicates.
2282 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002283 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002284 GetClassesInToVector accumulator;
2285 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002286 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002287 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002288 return;
2289 }
2290 }
2291 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002292 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002293 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002294 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002295 // We size the array assuming classes won't be added to the class table during the visit.
2296 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002297 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002298 size_t class_table_size;
2299 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002300 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002301 // Add 100 in case new classes get loaded when we are filling in the object array.
2302 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002303 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002304 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002305 classes.Assign(
2306 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002307 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002308 GetClassInToObjectArray accumulator(classes.Get());
2309 VisitClasses(&accumulator);
2310 if (accumulator.Succeeded()) {
2311 break;
2312 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002313 }
2314 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2315 // If the class table shrank during creation of the clases array we expect null elements. If
2316 // the class table grew then the loop repeats. If classes are created after the loop has
2317 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002318 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002319 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002320 return;
2321 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002322 }
2323 }
2324}
2325
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002326ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002327 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002328 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002329 // CHA unloading analysis is not needed. No negative consequences are expected because
2330 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002331 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002332 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002333 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002334 while (!running_visibly_initialized_callbacks_.empty()) {
2335 std::unique_ptr<VisiblyInitializedCallback> callback(
2336 std::addressof(running_visibly_initialized_callbacks_.front()));
2337 running_visibly_initialized_callbacks_.pop_front();
2338 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002339}
2340
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002341void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002342 Runtime* const runtime = Runtime::Current();
2343 JavaVMExt* const vm = runtime->GetJavaVM();
2344 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002345 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002346 if (runtime->GetJit() != nullptr) {
2347 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2348 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002349 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002350 code_cache->RemoveMethodsIn(self, *data.allocator);
2351 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002352 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002353 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002354 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002355 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002356 // Cleanup references to single implementation ArtMethods that will be deleted.
2357 if (cleanup_cha) {
2358 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2359 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2360 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002361 {
2362 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2363 auto end = critical_native_code_with_clinit_check_.end();
2364 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2365 if (data.allocator->ContainsUnsafe(it->first)) {
2366 it = critical_native_code_with_clinit_check_.erase(it);
2367 } else {
2368 ++it;
2369 }
2370 }
2371 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002372
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002373 delete data.allocator;
2374 delete data.class_table;
2375}
2376
Vladimir Markobcf17522018-06-01 13:14:32 +01002377ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2378 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002379 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002380 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2381 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002382}
2383
David Srbecky86d6cd52020-12-02 18:13:10 +00002384ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002385 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002386 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002387 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002388 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002389 self->AssertPendingOOMException();
2390 return nullptr;
2391 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002392 // Use InternWeak() so that the location String can be collected when the ClassLoader
2393 // with this DexCache is collected.
2394 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002395 if (location == nullptr) {
2396 self->AssertPendingOOMException();
2397 return nullptr;
2398 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002399 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002400 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002401}
2402
Orion Hodsonb9b7d912021-02-24 09:24:47 +00002403ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2404 const DexFile& dex_file,
2405 LinearAlloc* linear_alloc) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002406 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002407 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002408 WriterMutexLock mu(self, *Locks::dex_lock_);
Orion Hodsonb9b7d912021-02-24 09:24:47 +00002409 dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002410 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002411 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002412}
2413
Vladimir Marko70e2a762019-07-12 16:49:00 +01002414template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002415ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2416 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002417 uint32_t class_size,
2418 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002419 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002420 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002421 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002422 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2423 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002424 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002425 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002426 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002427 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002428 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002429}
2430
Vladimir Marko70e2a762019-07-12 16:49:00 +01002431template <bool kMovable>
2432ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2433 ObjPtr<mirror::Class> java_lang_Class,
2434 uint32_t class_size) {
2435 mirror::Class::InitializeClassVisitor visitor(class_size);
2436 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2437}
2438
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002439ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002440 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002441}
2442
Vladimir Marko70e2a762019-07-12 16:49:00 +01002443void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2444 ClassRoot primitive_root,
2445 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002446 // We make this class non-movable for the unlikely case where it were to be
2447 // moved by a sticky-bit (minor) collection when using the Generational
2448 // Concurrent Copying (CC) collector, potentially creating a stale reference
2449 // in the `klass_` field of one of its instances allocated in the Large-Object
2450 // Space (LOS) -- see the comment about the dirty card scanning logic in
2451 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002452 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2453 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2454 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2455 DCHECK(component_type->IsPrimitive());
2456 array_class->SetComponentType(component_type);
2457 SetClassRoot(array_root, array_class);
2458}
2459
2460void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2461 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2462 array_class->SetSuperClass(java_lang_Object);
2463 array_class->SetVTable(java_lang_Object->GetVTable());
2464 array_class->SetPrimitiveType(Primitive::kPrimNot);
2465 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2466 array_class->SetClassFlags(component_type->IsPrimitive()
2467 ? mirror::kClassFlagNoReferenceFields
2468 : mirror::kClassFlagObjectArray);
2469 array_class->SetClassLoader(component_type->GetClassLoader());
2470 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2471 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2472 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2473 array_class->SetImt(object_imt, image_pointer_size_);
2474 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2475 // the kAccVerificationAttempted flag is added below, and there are no
2476 // methods that need the kAccSkipAccessChecks flag.
2477 DCHECK_EQ(array_class->NumMethods(), 0u);
2478
2479 // don't need to set new_class->SetObjectSize(..)
2480 // because Object::SizeOf delegates to Array::SizeOf
2481
2482 // All arrays have java/lang/Cloneable and java/io/Serializable as
2483 // interfaces. We need to set that up here, so that stuff like
2484 // "instanceof" works right.
2485
2486 // Use the single, global copies of "interfaces" and "iftable"
2487 // (remember not to free them for arrays).
2488 {
2489 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2490 CHECK(array_iftable != nullptr);
2491 array_class->SetIfTable(array_iftable);
2492 }
2493
2494 // Inherit access flags from the component type.
2495 int access_flags = component_type->GetAccessFlags();
2496 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2497 access_flags &= kAccJavaFlagsMask;
2498 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2499 // and remove "interface".
2500 access_flags |= kAccAbstract | kAccFinal;
2501 access_flags &= ~kAccInterface;
2502 // Arrays are access-checks-clean and preverified.
2503 access_flags |= kAccVerificationAttempted;
2504
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002505 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002506
Vladimir Markobf121912019-06-04 13:49:05 +01002507 // Array classes are fully initialized either during single threaded startup,
2508 // or from a pre-fence visitor, so visibly initialized.
2509 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002510}
2511
2512void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2513 // Do not hold lock on the array class object, the initialization of
2514 // core array classes is done while the process is still single threaded.
2515 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2516 FinishArrayClassSetup(array_class);
2517
2518 std::string temp;
2519 const char* descriptor = array_class->GetDescriptor(&temp);
2520 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2521 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2522 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002523}
2524
Vladimir Markobcf17522018-06-01 13:14:32 +01002525ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002526 Thread* self,
2527 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002528 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002529 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002530}
2531
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002532ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2533 const char* descriptor,
2534 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002535 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002536 if (kIsDebugBuild) {
2537 StackHandleScope<1> hs(self);
2538 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2539 Thread::PoisonObjectPointersIfDebug();
2540 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002541
2542 // For temporary classes we must wait for them to be retired.
2543 if (init_done_ && klass->IsTemp()) {
2544 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002545 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002546 ThrowEarlierClassFailure(klass);
2547 return nullptr;
2548 }
2549 StackHandleScope<1> hs(self);
2550 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2551 ObjectLock<mirror::Class> lock(self, h_class);
2552 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002553 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002554 lock.WaitIgnoringInterrupts();
2555 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002556 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002557 ThrowEarlierClassFailure(h_class.Get());
2558 return nullptr;
2559 }
2560 CHECK(h_class->IsRetired());
2561 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002562 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002563 }
2564
Brian Carlstromaded5f72011-10-07 17:15:04 -07002565 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002566 size_t index = 0;
2567 // Maximum number of yield iterations until we start sleeping.
2568 static const size_t kNumYieldIterations = 1000;
2569 // How long each sleep is in us.
2570 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002571 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002572 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002573 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002574 {
2575 ObjectTryLock<mirror::Class> lock(self, h_class);
2576 // Can not use a monitor wait here since it may block when returning and deadlock if another
2577 // thread has locked klass.
2578 if (lock.Acquired()) {
2579 // Check for circular dependencies between classes, the lock is required for SetStatus.
2580 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2581 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002582 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002583 return nullptr;
2584 }
2585 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002587 {
2588 // Handle wrapper deals with klass moving.
2589 ScopedThreadSuspension sts(self, kSuspended);
2590 if (index < kNumYieldIterations) {
2591 sched_yield();
2592 } else {
2593 usleep(kSleepDurationUS);
2594 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002596 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002598
Vladimir Marko72ab6842017-01-20 19:32:50 +00002599 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002600 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002601 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002602 }
2603 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002604 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002605 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002606 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002607}
2608
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002609using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002610
2611// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002612ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002613 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002614 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002615 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002616 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002617 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002618 return ClassPathEntry(dex_file, dex_class_def);
2619 }
2620 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002621 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002622}
2623
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002624bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2625 Thread* self,
2626 const char* descriptor,
2627 size_t hash,
2628 Handle<mirror::ClassLoader> class_loader,
2629 /*out*/ ObjPtr<mirror::Class>* result) {
2630 ArtField* field =
2631 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2632 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2633 if (raw_shared_libraries == nullptr) {
2634 return true;
2635 }
2636
2637 StackHandleScope<2> hs(self);
2638 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2639 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2640 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002641 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2642 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002643 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2644 return false; // One of the shared libraries is not supported.
2645 }
2646 if (*result != nullptr) {
2647 return true; // Found the class up the chain.
2648 }
2649 }
2650 return true;
2651}
2652
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002653bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2654 Thread* self,
2655 const char* descriptor,
2656 size_t hash,
2657 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002658 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002659 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002660 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002661 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002662 return true;
2663 }
2664
David Brazdil05909d82018-12-06 16:25:16 +00002665 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002666 // For regular path or dex class loader the search order is:
2667 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002668 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002669 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002670
Calin Juravlecdd49122017-07-05 20:09:53 -07002671 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2672 StackHandleScope<1> hs(self);
2673 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2674 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2675 return false; // One of the parents is not supported.
2676 }
2677 if (*result != nullptr) {
2678 return true; // Found the class up the chain.
2679 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002680
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002681 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2682 return false; // One of the shared library loader is not supported.
2683 }
2684 if (*result != nullptr) {
2685 return true; // Found the class in a shared library.
2686 }
2687
Calin Juravlecdd49122017-07-05 20:09:53 -07002688 // Search the current class loader classpath.
2689 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002690 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002691 }
2692
Calin Juravlecdd49122017-07-05 20:09:53 -07002693 if (IsDelegateLastClassLoader(soa, class_loader)) {
2694 // For delegate last, the search order is:
2695 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002696 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002697 // - class loader dex files
2698 // - parent
2699 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2700 if (*result != nullptr) {
2701 return true; // The class is part of the boot class path.
2702 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002703 if (self->IsExceptionPending()) {
2704 // Pending exception means there was an error other than ClassNotFound that must be returned
2705 // to the caller.
2706 return false;
2707 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002708
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002709 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2710 return false; // One of the shared library loader is not supported.
2711 }
2712 if (*result != nullptr) {
2713 return true; // Found the class in a shared library.
2714 }
2715
Calin Juravlecdd49122017-07-05 20:09:53 -07002716 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2717 if (*result != nullptr) {
2718 return true; // Found the class in the current class loader
2719 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002720 if (self->IsExceptionPending()) {
2721 // Pending exception means there was an error other than ClassNotFound that must be returned
2722 // to the caller.
2723 return false;
2724 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002725
2726 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2727 StackHandleScope<1> hs(self);
2728 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2729 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2730 }
2731
2732 // Unsupported class loader.
2733 *result = nullptr;
2734 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002735}
2736
Andreas Gampe501c3b02019-04-17 21:54:27 +00002737namespace {
2738
2739// Matches exceptions caught in DexFile.defineClass.
2740ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2741 ClassLinker* class_linker)
2742 REQUIRES_SHARED(Locks::mutator_lock_) {
2743 return
2744 // ClassNotFoundException.
2745 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2746 class_linker))
2747 ||
2748 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2749 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2750}
2751
2752// Clear exceptions caught in DexFile.defineClass.
2753ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2754 REQUIRES_SHARED(Locks::mutator_lock_) {
2755 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2756 self->ClearException();
2757 }
2758}
2759
2760} // namespace
2761
Calin Juravle415dc3d2017-06-28 11:03:12 -07002762// Finds the class in the boot class loader.
2763// If the class is found the method returns the resolved class. Otherwise it returns null.
2764ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2765 const char* descriptor,
2766 size_t hash) {
2767 ObjPtr<mirror::Class> result = nullptr;
2768 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2769 if (pair.second != nullptr) {
2770 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2771 if (klass != nullptr) {
2772 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002773 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002774 result = DefineClass(self,
2775 descriptor,
2776 hash,
2777 ScopedNullHandle<mirror::ClassLoader>(),
2778 *pair.first,
2779 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002780 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002781 if (result == nullptr) {
2782 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002783 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002784 }
2785 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002786 return result;
2787}
Andreas Gampef865ea92015-04-13 22:14:19 -07002788
Calin Juravle415dc3d2017-06-28 11:03:12 -07002789ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2790 ScopedObjectAccessAlreadyRunnable& soa,
2791 const char* descriptor,
2792 size_t hash,
2793 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002794 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2795 IsInMemoryDexClassLoader(soa, class_loader) ||
2796 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002797 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002798
Vladimir Marko68c07582021-04-19 16:01:15 +00002799 const DexFile* dex_file = nullptr;
2800 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002801 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002802 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2803 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2804 if (cp_class_def != nullptr) {
2805 dex_file = cp_dex_file;
2806 class_def = cp_class_def;
2807 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002808 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002809 return true; // Continue with the next DexFile.
2810 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002811 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002812
Vladimir Marko68c07582021-04-19 16:01:15 +00002813 ObjPtr<mirror::Class> klass = nullptr;
2814 if (class_def != nullptr) {
2815 klass = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2816 if (UNLIKELY(klass == nullptr)) {
2817 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2818 FilterDexFileCaughtExceptions(soa.Self(), this);
2819 } else {
2820 DCHECK(!soa.Self()->IsExceptionPending());
2821 }
2822 }
2823 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002824}
2825
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002826ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2827 const char* descriptor,
2828 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002829 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002830 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002831 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002832 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002833 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002834 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2835 // for primitive classes that aren't backed by dex files.
2836 return FindPrimitiveClass(descriptor[0]);
2837 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002838 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002839 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002840 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002841 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002842 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002843 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002844 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002845 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002846 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002847 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002848 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002849 return DefineClass(self,
2850 descriptor,
2851 hash,
2852 ScopedNullHandle<mirror::ClassLoader>(),
2853 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002854 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002855 } else {
2856 // The boot class loader is searched ahead of the application class loader, failures are
2857 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2858 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002859 ObjPtr<mirror::Throwable> pre_allocated =
2860 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002861 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002862 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002863 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002864 }
2865 ObjPtr<mirror::Class> result_ptr;
2866 bool descriptor_equals;
2867 if (descriptor[0] == '[') {
2868 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2869 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2870 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2871 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002872 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002873 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002874 bool known_hierarchy =
2875 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2876 if (result_ptr != nullptr) {
2877 // The chain was understood and we found the class. We still need to add the class to
2878 // the class table to protect from racy programs that can try and redefine the path list
2879 // which would change the Class<?> returned for subsequent evaluation of const-class.
2880 DCHECK(known_hierarchy);
2881 DCHECK(result_ptr->DescriptorEquals(descriptor));
2882 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002883 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002884 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002885 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2886 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002887 //
2888 // If the chain was understood but we did not find the class, let the Java-side
2889 // rediscover all this and throw the exception with the right stack trace. Note that
2890 // the Java-side could still succeed for racy programs if another thread is actively
2891 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002892
Alex Light185a4612018-10-04 15:54:25 -07002893 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002894 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002895 // Oops, we can't call into java so we can't run actual class-loader code.
2896 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002897 ObjPtr<mirror::Throwable> pre_allocated =
2898 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2899 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002900 return nullptr;
2901 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002902
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002903 // Inlined DescriptorToDot(descriptor) with extra validation.
2904 //
2905 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2906 // the DescriptorEquals() check below and give a confusing error message. For example,
2907 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2908 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2909 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2910 size_t descriptor_length = strlen(descriptor);
2911 if (UNLIKELY(descriptor[0] != 'L') ||
2912 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2913 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2914 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2915 return nullptr;
2916 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002917
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002918 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2919 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002920 if (known_hierarchy &&
2921 fast_class_not_found_exceptions_ &&
2922 !Runtime::Current()->IsJavaDebuggable()) {
2923 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2924 // debuggable, optimize this path by throwing directly here without going back to Java
2925 // language. This reduces how many ClassNotFoundExceptions happen.
2926 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2927 "%s",
2928 class_name_string.c_str());
2929 } else {
2930 ScopedLocalRef<jobject> class_loader_object(
2931 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2932 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2933 {
2934 ScopedThreadStateChange tsc(self, kNative);
2935 ScopedLocalRef<jobject> class_name_object(
2936 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2937 if (class_name_object.get() == nullptr) {
2938 DCHECK(self->IsExceptionPending()); // OOME.
2939 return nullptr;
2940 }
2941 CHECK(class_loader_object.get() != nullptr);
2942 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2943 WellKnownClasses::java_lang_ClassLoader_loadClass,
2944 class_name_object.get()));
2945 }
2946 if (result.get() == nullptr && !self->IsExceptionPending()) {
2947 // broken loader - throw NPE to be compatible with Dalvik
2948 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2949 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002950 return nullptr;
2951 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002952 result_ptr = soa.Decode<mirror::Class>(result.get());
2953 // Check the name of the returned class.
2954 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002955 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002956 } else {
2957 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002958 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002959 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002960
2961 if (self->IsExceptionPending()) {
2962 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2963 // However, to comply with the RI behavior, first check if another thread succeeded.
2964 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2965 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2966 self->ClearException();
2967 return EnsureResolved(self, descriptor, result_ptr);
2968 }
2969 return nullptr;
2970 }
2971
2972 // Try to insert the class to the class table, checking for mismatch.
2973 ObjPtr<mirror::Class> old;
2974 {
2975 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2976 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2977 old = class_table->Lookup(descriptor, hash);
2978 if (old == nullptr) {
2979 old = result_ptr; // For the comparison below, after releasing the lock.
2980 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002981 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002982 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002983 } // else throw below, after releasing the lock.
2984 }
2985 }
2986 if (UNLIKELY(old != result_ptr)) {
2987 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2988 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002989 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002990 const char* loader_class_name =
2991 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2992 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2993 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2994 << DescriptorToDot(descriptor) << "\").";
2995 return EnsureResolved(self, descriptor, old);
2996 }
2997 if (UNLIKELY(!descriptor_equals)) {
2998 std::string result_storage;
2999 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3000 std::string loader_storage;
3001 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3002 ThrowNoClassDefFoundError(
3003 "Initiating class loader of type %s returned class %s instead of %s.",
3004 DescriptorToDot(loader_class_name).c_str(),
3005 DescriptorToDot(result_name).c_str(),
3006 DescriptorToDot(descriptor).c_str());
3007 return nullptr;
3008 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003009 // Success.
3010 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003011}
3012
Alex Light270db1c2019-12-03 12:20:01 +00003013// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3014// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3015// like pausing class definition.
3016struct ScopedDefiningClass {
3017 public:
3018 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3019 : self_(self), returned_(false) {
3020 Locks::mutator_lock_->AssertSharedHeld(self_);
3021 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3022 self_->IncrDefineClassCount();
3023 }
3024 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3025 Locks::mutator_lock_->AssertSharedHeld(self_);
3026 CHECK(returned_);
3027 }
3028
3029 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3030 REQUIRES_SHARED(Locks::mutator_lock_) {
3031 CHECK(!returned_);
3032 self_->DecrDefineClassCount();
3033 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3034 Thread::PoisonObjectPointersIfDebug();
3035 returned_ = true;
3036 return h_klass.Get();
3037 }
3038
3039 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3040 REQUIRES_SHARED(Locks::mutator_lock_) {
3041 StackHandleScope<1> hs(self_);
3042 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3043 return Finish(h_klass);
3044 }
3045
3046 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3047 REQUIRES_SHARED(Locks::mutator_lock_) {
3048 ScopedNullHandle<mirror::Class> snh;
3049 return Finish(snh);
3050 }
3051
3052 private:
3053 Thread* self_;
3054 bool returned_;
3055};
3056
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003057ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3058 const char* descriptor,
3059 size_t hash,
3060 Handle<mirror::ClassLoader> class_loader,
3061 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003062 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003063 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003064 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003065 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003066 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003067
Brian Carlstromaded5f72011-10-07 17:15:04 -07003068 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003069 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003070 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003071 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003072 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003073 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003074 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003075 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003076 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003077 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003078 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003079 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003080 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003081 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003082 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003083 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003084 }
3085
Vladimir Markob9c29f62019-03-20 14:22:51 +00003086 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3087 // some runtime modules. Prevent definition of classes in app class loader that could clash
3088 // with these modules as these classes could be resolved differently during execution.
3089 if (class_loader != nullptr &&
3090 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003091 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003092 ObjPtr<mirror::Throwable> pre_allocated =
3093 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3094 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003095 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003096 }
3097
Calin Juravle33787682019-07-26 14:27:18 -07003098 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3099 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3100 // public class path then we prevent the definition of the class.
3101 //
3102 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3103 // classpath is not checked.
3104 if (class_loader == nullptr &&
3105 Runtime::Current()->IsAotCompiler() &&
3106 DenyAccessBasedOnPublicSdk(descriptor)) {
3107 ObjPtr<mirror::Throwable> pre_allocated =
3108 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3109 self->SetException(pre_allocated);
3110 return sdc.Finish(nullptr);
3111 }
3112
Alex Lighte9f61032018-09-24 16:04:51 -07003113 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3114 // code to be executed. We put it up here so we can avoid all the allocations associated with
3115 // creating the class. This can happen with (eg) jit threads.
3116 if (!self->CanLoadClasses()) {
3117 // Make sure we don't try to load anything, potentially causing an infinite loop.
3118 ObjPtr<mirror::Throwable> pre_allocated =
3119 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3120 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003121 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003122 }
3123
Andreas Gampefa4333d2017-02-14 11:10:34 -08003124 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003125 // Allocate a class with the status of not ready.
3126 // Interface object should get the right size here. Regular class will
3127 // figure out the right size later and be replaced with one of the right
3128 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003129 if (CanAllocClass()) {
3130 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3131 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003132 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003133 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003134 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003135 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003136 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003137 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003138 }
Alex Lightb0f11922017-01-23 14:25:17 -08003139 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3140 // nothing.
3141 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003142 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003143 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3144 // will only be called once.
3145 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3146 klass,
3147 class_loader,
3148 dex_file,
3149 dex_class_def,
3150 &new_dex_file,
3151 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003152 // Check to see if an exception happened during runtime callbacks. Return if so.
3153 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003154 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003155 }
Alex Lightb0f11922017-01-23 14:25:17 -08003156 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003157 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003158 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003159 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003160 }
3161 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003162 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003163
Jeff Hao848f70a2014-01-15 13:49:50 -08003164 // Mark the string class by setting its access flag.
3165 if (UNLIKELY(!init_done_)) {
3166 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3167 klass->SetStringClass();
3168 }
3169 }
3170
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003171 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003172 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003173 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003174 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003175
Mathieu Chartier590fee92013-09-13 13:46:47 -07003176 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003177 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003178 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003179 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3180 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003181 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003182 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003183
Mathieu Chartierc7853442015-03-27 14:35:38 -07003184 // Load the fields and other things after we are inserted in the table. This is so that we don't
3185 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3186 // other reason is that the field roots are only visited from the class table. So we need to be
3187 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003188 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003189 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003190 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003191 // An exception occured during load, set status to erroneous while holding klass' lock in case
3192 // notification is necessary.
3193 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003194 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003195 }
Alex Light270db1c2019-12-03 12:20:01 +00003196 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003197 }
3198
Brian Carlstromaded5f72011-10-07 17:15:04 -07003199 // Finish loading (if necessary) by finding parents
3200 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003201 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003202 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003203 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003204 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003205 }
Alex Light270db1c2019-12-03 12:20:01 +00003206 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003207 }
3208 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003209
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003210 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003211 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003212 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003213
Brian Carlstromaded5f72011-10-07 17:15:04 -07003214 // Link the class (if necessary)
3215 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003216 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003217 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003218
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003219 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003220 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003221 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003222 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003223 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003224 }
Alex Light270db1c2019-12-03 12:20:01 +00003225 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003226 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003227 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003228 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003229 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003230
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003231 // Instrumentation may have updated entrypoints for all methods of all
3232 // classes. However it could not update methods of this class while we
3233 // were loading it. Now the class is resolved, we can update entrypoints
3234 // as required by instrumentation.
3235 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3236 // We must be in the kRunnable state to prevent instrumentation from
3237 // suspending all threads to update entrypoints while we are doing it
3238 // for this class.
3239 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003240 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003241 }
3242
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003243 /*
3244 * We send CLASS_PREPARE events to the debugger from here. The
3245 * definition of "preparation" is creating the static fields for a
3246 * class and initializing them to the standard default values, but not
3247 * executing any code (that comes later, during "initialization").
3248 *
3249 * We did the static preparation in LinkClass.
3250 *
3251 * The class has been prepared and resolved but possibly not yet verified
3252 * at this point.
3253 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003254 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003255
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003256 // Notify native debugger of the new class and its layout.
3257 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3258
Alex Light270db1c2019-12-03 12:20:01 +00003259 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003260}
3261
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003262uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003263 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003264 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003265 size_t num_8 = 0;
3266 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003267 size_t num_32 = 0;
3268 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003269 ClassAccessor accessor(dex_file, dex_class_def);
3270 // We allow duplicate definitions of the same field in a class_data_item
3271 // but ignore the repeated indexes here, b/21868015.
3272 uint32_t last_field_idx = dex::kDexNoIndex;
3273 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3274 uint32_t field_idx = field.GetIndex();
3275 // Ordering enforced by DexFileVerifier.
3276 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3277 if (UNLIKELY(field_idx == last_field_idx)) {
3278 continue;
3279 }
3280 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003281 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003282 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3283 char c = descriptor[0];
3284 switch (c) {
3285 case 'L':
3286 case '[':
3287 num_ref++;
3288 break;
3289 case 'J':
3290 case 'D':
3291 num_64++;
3292 break;
3293 case 'I':
3294 case 'F':
3295 num_32++;
3296 break;
3297 case 'S':
3298 case 'C':
3299 num_16++;
3300 break;
3301 case 'B':
3302 case 'Z':
3303 num_8++;
3304 break;
3305 default:
3306 LOG(FATAL) << "Unknown descriptor: " << c;
3307 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003308 }
3309 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003310 return mirror::Class::ComputeClassSize(false,
3311 0,
3312 num_8,
3313 num_16,
3314 num_32,
3315 num_64,
3316 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003317 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003318}
3319
Alex Lightfc49fec2018-01-16 22:28:36 +00003320// Special case to get oat code without overwriting a trampoline.
3321const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003322 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003323 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003324 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003325 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003326 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003327 if (code != nullptr) {
3328 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003329 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003330
3331 jit::Jit* jit = Runtime::Current()->GetJit();
3332 if (jit != nullptr) {
3333 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3334 if (code != nullptr) {
3335 return code;
3336 }
3337 }
3338
Alex Lightfc49fec2018-01-16 22:28:36 +00003339 if (method->IsNative()) {
3340 // No code and native? Use generic trampoline.
3341 return GetQuickGenericJniStub();
3342 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003343
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003344 if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003345 return interpreter::GetNterpEntryPoint();
3346 }
3347
Alex Lightfc49fec2018-01-16 22:28:36 +00003348 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003349}
3350
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003351bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003352 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003353 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3354 return false;
3355 }
3356
Elliott Hughes956af0f2014-12-11 14:34:28 -08003357 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003358 return true;
3359 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003360
3361 Runtime* runtime = Runtime::Current();
3362 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3363 if (instr->InterpretOnly()) {
3364 return true;
3365 }
3366
3367 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3368 // Doing this check avoids doing compiled/interpreter transitions.
3369 return true;
3370 }
3371
Alex Lightfc588092020-01-23 15:39:08 -08003372 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003373 // Force the use of interpreter when it is required by the debugger.
3374 return true;
3375 }
3376
Alex Light8f34aba2017-10-09 13:46:32 -07003377 if (Thread::Current()->IsAsyncExceptionPending()) {
3378 // Force use of interpreter to handle async-exceptions
3379 return true;
3380 }
3381
Alex Light2d441b12018-06-08 15:33:21 -07003382 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3383 const void* instr_target = instr->GetCodeForInvoke(method);
3384 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3385 return ShouldUseInterpreterEntrypoint(method, instr_target);
3386 }
3387
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003388 if (runtime->IsJavaDebuggable()) {
3389 // For simplicity, we ignore precompiled code and go to the interpreter
3390 // assuming we don't already have jitted code.
3391 // We could look at the oat file where `quick_code` is being defined,
3392 // and check whether it's been compiled debuggable, but we decided to
3393 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003394 jit::Jit* jit = Runtime::Current()->GetJit();
3395 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3396 }
3397
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003398 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003399 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003400 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003401 // since we want to JIT it (at first use) with extra stackmaps for native
3402 // debugging. We keep however all AOT code from the boot image,
3403 // since the JIT-at-first-use is blocking and would result in non-negligible
3404 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003405 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003406 }
3407
3408 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003409}
3410
Vladimir Marko86c87522020-05-11 16:55:55 +01003411void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003412 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003413 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003414 size_t num_direct_methods = klass->NumDirectMethods();
3415 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003416 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003417 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003418 if (UNLIKELY(klass->IsProxyClass())) {
3419 return;
3420 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003421 PointerSize pointer_size = image_pointer_size_;
3422 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3423 klass->GetDirectMethods(pointer_size).end(),
3424 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3425 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3426 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3427 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3428 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3429 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3430 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3431 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3432 lb->first->SetEntryPointFromJni(lb->second);
3433 lb = critical_native_code_with_clinit_check_.erase(lb);
3434 }
3435 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003436 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003437 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003438 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003439 return; // OAT file unavailable.
3440 }
Ian Rogers19846512012-02-24 11:42:47 -08003441 }
Alex Light64ad14d2014-08-19 14:23:13 -07003442
Mathieu Chartierf8322842014-05-16 10:59:25 -07003443 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003444 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003445 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3446 klass->GetDexClassDefIndex(),
3447 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003448 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003449 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3450 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003451 if (!method->IsStatic()) {
3452 // Only update static methods.
3453 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003454 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003455 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003456
3457 // In order:
3458 // 1) Check if we have AOT Code.
3459 // 2) Check if we have JIT Code.
3460 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003461 if (has_oat_class) {
3462 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003463 quick_code = oat_method.GetQuickCode();
3464 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003465
Vladimir Markocce414f2019-10-07 08:51:33 +01003466 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003467 if (quick_code == nullptr && jit != nullptr) {
3468 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003469 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003470
3471 if (quick_code == nullptr &&
3472 interpreter::CanRuntimeUseNterp() &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003473 CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003474 quick_code = interpreter::GetNterpEntryPoint();
3475 }
3476
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003477 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003478 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003479 quick_code = GetQuickGenericJniStub();
3480 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003481 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003482 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3483 // If we have the trampoline or the bridge already, no need to update.
3484 // This saves in not dirtying boot image memory.
3485 continue;
3486 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003487 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003488 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003489 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003490 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003491 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003492 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003493}
3494
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003495// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3496// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003497inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3498 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003499 DCHECK(method != nullptr);
3500 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003501 method->SetEntryPointFromQuickCompiledCodePtrSize(
3502 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3503 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003504}
3505
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003506static void LinkCode(ClassLinker* class_linker,
3507 ArtMethod* method,
3508 const OatFile::OatClass* oat_class,
3509 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003510 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003511 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003512 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003513 // The following code only applies to a non-compiler runtime.
3514 return;
3515 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003516
Ian Rogers62d6c772013-02-27 08:32:07 -08003517 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003518 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003519
Alex Light9139e002015-10-09 15:59:48 -07003520 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003521 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003522 return;
3523 }
Ian Rogers19846512012-02-24 11:42:47 -08003524
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003525 const void* quick_code = nullptr;
3526 if (oat_class != nullptr) {
3527 // Every kind of method should at least get an invoke stub from the oat_method.
3528 // non-abstract methods also get their code pointers.
3529 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3530 quick_code = oat_method.GetQuickCode();
3531 }
3532
3533 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3534
3535 // Note: this mimics the logic in image_writer.cc that installs the resolution
3536 // stub only if we have compiled code and the method needs a class initialization
3537 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003538 if (quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003539 method->SetEntryPointFromQuickCompiledCode(
3540 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3541 } else if (enter_interpreter) {
3542 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003543 } else if (NeedsClinitCheckBeforeCall(method)) {
3544 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3545 // If we do have code but the method needs a class initialization check before calling
3546 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003547 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3548 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003549 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003550 } else {
3551 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003552 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003553
Ian Rogers62d6c772013-02-27 08:32:07 -08003554 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003555 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3556 // as the extra processing for @CriticalNative is not needed yet.
3557 method->SetEntryPointFromJni(
3558 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003559
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003560 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003561 // We have a native method here without code. Then it should have the generic JNI
3562 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003563 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003564 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003565 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003566 }
3567}
3568
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003569void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003570 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003571 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003572 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003573 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003574 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003575 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003576 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003577 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003578
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003579 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003580 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003581 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003582 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003583 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003584 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003585 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003586
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003587 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003588 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003589}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003590
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003591LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3592 LinearAlloc* allocator,
3593 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003594 if (length == 0) {
3595 return nullptr;
3596 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003597 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3598 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3599 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003600 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003601 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003602 CHECK(ret != nullptr);
3603 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3604 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003605}
3606
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003607LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3608 LinearAlloc* allocator,
3609 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003610 if (length == 0) {
3611 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003612 }
Vladimir Marko14632852015-08-17 12:07:23 +01003613 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3614 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003615 const size_t storage_size =
3616 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003617 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003618 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003619 CHECK(ret != nullptr);
3620 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003621 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003622 }
3623 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003624}
3625
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003626LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003627 if (class_loader == nullptr) {
3628 return Runtime::Current()->GetLinearAlloc();
3629 }
3630 LinearAlloc* allocator = class_loader->GetAllocator();
3631 DCHECK(allocator != nullptr);
3632 return allocator;
3633}
3634
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003635LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003636 if (class_loader == nullptr) {
3637 return Runtime::Current()->GetLinearAlloc();
3638 }
3639 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3640 LinearAlloc* allocator = class_loader->GetAllocator();
3641 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003642 RegisterClassLoader(class_loader);
3643 allocator = class_loader->GetAllocator();
3644 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003645 }
3646 return allocator;
3647}
3648
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003649void ClassLinker::LoadClass(Thread* self,
3650 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003651 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003652 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003653 ClassAccessor accessor(dex_file,
3654 dex_class_def,
3655 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003656 if (!accessor.HasClassData()) {
3657 return;
3658 }
3659 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003660 {
3661 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3662 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003663 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003664 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003665 // We allow duplicate definitions of the same field in a class_data_item
3666 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003667 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003668 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3669 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003670 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003671 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3672 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003673 accessor.NumInstanceFields());
3674 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003675 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003676 uint32_t last_static_field_idx = 0u;
3677 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003678
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003679 // Methods
3680 bool has_oat_class = false;
3681 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3682 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3683 : OatFile::OatClass::Invalid();
3684 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3685 klass->SetMethodsPtr(
3686 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3687 accessor.NumDirectMethods(),
3688 accessor.NumVirtualMethods());
3689 size_t class_def_method_index = 0;
3690 uint32_t last_dex_method_index = dex::kDexNoIndex;
3691 size_t last_class_def_method_index = 0;
3692
3693 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3694 // methods needs to decode all of the fields.
3695 accessor.VisitFieldsAndMethods([&](
3696 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3697 uint32_t field_idx = field.GetIndex();
3698 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3699 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3700 LoadField(field, klass, &sfields->At(num_sfields));
3701 ++num_sfields;
3702 last_static_field_idx = field_idx;
3703 }
3704 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3705 uint32_t field_idx = field.GetIndex();
3706 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3707 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3708 LoadField(field, klass, &ifields->At(num_ifields));
3709 ++num_ifields;
3710 last_instance_field_idx = field_idx;
3711 }
3712 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3713 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3714 image_pointer_size_);
3715 LoadMethod(dex_file, method, klass, art_method);
3716 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3717 uint32_t it_method_index = method.GetIndex();
3718 if (last_dex_method_index == it_method_index) {
3719 // duplicate case
3720 art_method->SetMethodIndex(last_class_def_method_index);
3721 } else {
3722 art_method->SetMethodIndex(class_def_method_index);
3723 last_dex_method_index = it_method_index;
3724 last_class_def_method_index = class_def_method_index;
3725 }
3726 ++class_def_method_index;
3727 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3728 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3729 class_def_method_index - accessor.NumDirectMethods(),
3730 image_pointer_size_);
3731 LoadMethod(dex_file, method, klass, art_method);
3732 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3733 ++class_def_method_index;
3734 });
3735
3736 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003737 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003738 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3739 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3740 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003741 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3742 if (sfields != nullptr) {
3743 sfields->SetSize(num_sfields);
3744 }
3745 if (ifields != nullptr) {
3746 ifields->SetSize(num_ifields);
3747 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003748 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003749 // Set the field arrays.
3750 klass->SetSFieldsPtr(sfields);
3751 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003752 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003753 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003754 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003755 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003756 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003757 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003758}
3759
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003760void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003761 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003762 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003763 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003764 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003765 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003766
David Brazdil85865692018-10-30 17:26:20 +00003767 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3768 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003769}
3770
Mathieu Chartier268764d2016-09-13 12:09:38 -07003771void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003772 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003773 Handle<mirror::Class> klass,
3774 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003775 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003776 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003777 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003778
Mathieu Chartier268764d2016-09-13 12:09:38 -07003779 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003780 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003781 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003782
David Brazdil85865692018-10-30 17:26:20 +00003783 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3784 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003785
Ian Rogersdfb325e2013-10-30 01:00:44 -07003786 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003787 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003788 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3789 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003790 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003791 klass->SetFinalizable();
3792 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003793 std::string temp;
3794 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003795 // The Enum class declares a "final" finalize() method to prevent subclasses from
3796 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3797 // subclasses, so we exclude it here.
3798 // We also want to avoid setting the flag on Object, where we know that finalize() is
3799 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003800 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3801 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003802 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003803 }
3804 }
3805 }
3806 } else if (method_name[0] == '<') {
3807 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003808 bool is_init = (strcmp("<init>", method_name) == 0);
3809 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003810 if (UNLIKELY(!is_init && !is_clinit)) {
3811 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3812 } else {
3813 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3814 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003815 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003816 access_flags |= kAccConstructor;
3817 }
3818 }
3819 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003820 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3821 // Check if the native method is annotated with @FastNative or @CriticalNative.
3822 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3823 dex_file, dst->GetClassDef(), dex_method_idx);
3824 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003825 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003826 // Must be done after SetAccessFlags since IsAbstract depends on it.
3827 if (klass->IsInterface() && dst->IsAbstract()) {
3828 dst->CalculateAndSetImtIndex();
3829 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003830 if (dst->HasCodeItem()) {
3831 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3832 if (Runtime::Current()->IsAotCompiler()) {
3833 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3834 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003835 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003836 }
3837 } else {
3838 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3839 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3840 }
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003841
3842 // Set optimization flags related to the shorty.
3843 const char* shorty = dst->GetShorty();
3844 bool all_parameters_are_reference = true;
3845 bool all_parameters_are_reference_or_int = true;
3846 bool return_type_is_fp = (shorty[0] == 'F' || shorty[0] == 'D');
3847
3848 for (size_t i = 1, e = strlen(shorty); i < e; ++i) {
3849 if (shorty[i] != 'L') {
3850 all_parameters_are_reference = false;
3851 if (shorty[i] == 'F' || shorty[i] == 'D' || shorty[i] == 'J') {
3852 all_parameters_are_reference_or_int = false;
3853 break;
3854 }
3855 }
3856 }
3857
3858 if (!dst->IsNative() && all_parameters_are_reference) {
3859 dst->SetNterpEntryPointFastPathFlag();
3860 }
3861
3862 if (!return_type_is_fp && all_parameters_are_reference_or_int) {
3863 dst->SetNterpInvokeFastPathFlag();
3864 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003865}
3866
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003867void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00003868 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
3869 self,
3870 *dex_file,
3871 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003872 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003873 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003874}
3875
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003876void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003877 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003878 CHECK(dex_file != nullptr);
3879 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3880 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003881 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003882 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003883}
3884
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003885void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003886 ObjPtr<mirror::DexCache> dex_cache,
3887 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003888 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003889 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003890 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003891 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003892 // For app images, the dex cache location may be a suffix of the dex file location since the
3893 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003894 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3895 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003896 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3897 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003898 // The following paths checks don't work on preopt when using boot dex files, where the dex
3899 // cache location is the one on device, and the dex_file's location is the one on host.
3900 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3901 CHECK_GE(dex_file_location.length(), dex_cache_length)
3902 << dex_cache_location << " " << dex_file.GetLocation();
3903 const std::string dex_file_suffix = dex_file_location.substr(
3904 dex_file_location.length() - dex_cache_length,
3905 dex_cache_length);
3906 // Example dex_cache location is SettingsProvider.apk and
3907 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3908 CHECK_EQ(dex_cache_location, dex_file_suffix);
3909 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003910 const OatFile* oat_file =
3911 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003912 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3913 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3914 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3915 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003916 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003917 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3918 DexCacheData data = *it;
3919 if (self->IsJWeakCleared(data.weak_root)) {
3920 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003921 it = dex_caches_.erase(it);
3922 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003923 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003924 it->dex_file->GetOatDexFile() != nullptr &&
3925 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003926 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003927 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003928 ++it;
3929 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003930 }
Vladimir Markob066d432018-01-03 13:14:37 +00003931 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003932 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003933 }
David Brazdila5c3a802019-03-08 14:59:41 +00003934 // Let hiddenapi assign a domain to the newly registered dex file.
3935 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3936
Vladimir Markocd556b02017-02-03 11:47:34 +00003937 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003938 DexCacheData data;
3939 data.weak_root = dex_cache_jweak;
3940 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003941 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003942 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003943 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003944 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3945 // path dex caches without an image.
3946 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003947 // Make sure that the dex cache holds the classloader live.
3948 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003949 if (class_loader != nullptr) {
3950 // Since we added a strong root to the class table, do the write barrier as required for
3951 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003952 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003953 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003954 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003955}
3956
Alex Light725da8f2020-02-19 14:46:33 -08003957ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3958 return data != nullptr
3959 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003960 : nullptr;
3961}
3962
Alex Light725da8f2020-02-19 14:46:33 -08003963bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003964 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003965 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003966 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003967 CHECK(data != nullptr);
3968 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
3969 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003970}
3971
Alex Light07f06212017-06-01 14:01:43 -07003972void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3973 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003974 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003975 Thread* self = Thread::Current();
3976 StackHandleScope<2> hs(self);
3977 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3978 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3979 const DexFile* dex_file = dex_cache->GetDexFile();
3980 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3981 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003982 ReaderMutexLock mu(self, *Locks::dex_lock_);
3983 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3984 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003985 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3986 << "been registered on dex file " << dex_file->GetLocation();
3987 }
3988 ClassTable* table;
3989 {
3990 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3991 table = InsertClassTableForClassLoader(h_class_loader.Get());
3992 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003993 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3994 // a thread holding the dex lock and blocking on a condition variable regarding
3995 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003996 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003997 WriterMutexLock mu(self, *Locks::dex_lock_);
3998 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3999 table->InsertStrongRoot(h_dex_cache.Get());
4000 if (h_class_loader.Get() != nullptr) {
4001 // Since we added a strong root to the class table, do the write barrier as required for
4002 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004003 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004004 }
4005}
4006
Alex Lightde7f8782020-02-24 10:14:22 -08004007static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
4008 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08004009 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08004010 "Attempt to register dex file %s with multiple class loaders",
4011 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08004012}
4013
Vladimir Markocd556b02017-02-03 11:47:34 +00004014ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4015 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004016 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08004017 ObjPtr<mirror::DexCache> old_dex_cache;
4018 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004019 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004020 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004021 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4022 old_dex_cache = DecodeDexCacheLocked(self, old_data);
4023 if (old_dex_cache != nullptr) {
4024 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
4025 return old_dex_cache;
4026 } else {
4027 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
4028 // be thrown when it's safe to do so to simplify this.
4029 registered_with_another_class_loader = true;
4030 }
4031 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004032 }
Alex Light725da8f2020-02-19 14:46:33 -08004033 // We need to have released the dex_lock_ to allocate safely.
4034 if (registered_with_another_class_loader) {
4035 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4036 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004037 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004038 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004039 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4040 DCHECK(linear_alloc != nullptr);
4041 ClassTable* table;
4042 {
4043 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4044 table = InsertClassTableForClassLoader(class_loader);
4045 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004046 // Don't alloc while holding the lock, since allocation may need to
4047 // suspend all threads and another thread may need the dex_lock_ to
4048 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004049 StackHandleScope<3> hs(self);
4050 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004051 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004052 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004053 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4054 // a thread holding the dex lock and blocking on a condition variable regarding
4055 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004056 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004057 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004058 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4059 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004060 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00004061 // Do InitializeNativeFields while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00004062 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4063 // DCHECK that the arrays are null.
Orion Hodsonb9b7d912021-02-24 09:24:47 +00004064 h_dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Vladimir Markocd556b02017-02-03 11:47:34 +00004065 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004066 }
Alex Light725da8f2020-02-19 14:46:33 -08004067 if (old_dex_cache != nullptr) {
4068 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4069 // If this thread encountered OOME, ignore it.
4070 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4071 self->ClearException();
4072 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4073 // dex_lock_.
4074 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4075 return old_dex_cache;
4076 } else {
4077 registered_with_another_class_loader = true;
4078 }
4079 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004080 }
Alex Light725da8f2020-02-19 14:46:33 -08004081 if (registered_with_another_class_loader) {
4082 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4083 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004084 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004085 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004086 self->AssertPendingOOMException();
4087 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004088 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004089 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004090 if (h_class_loader.Get() != nullptr) {
4091 // Since we added a strong root to the class table, do the write barrier as required for
4092 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004093 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004094 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004095 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01004096 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004097 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004098}
4099
Vladimir Markocd556b02017-02-03 11:47:34 +00004100bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004101 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004102 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004103}
4104
Vladimir Markocd556b02017-02-03 11:47:34 +00004105ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4106 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004107 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4108 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004109 if (dex_cache != nullptr) {
4110 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004111 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004112 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004113 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004114 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004115 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004116 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004117 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004118 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004119 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004120 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004121}
4122
Vladimir Markocd556b02017-02-03 11:47:34 +00004123ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4124 const DexFile* dex_file = dex_cache->GetDexFile();
4125 DCHECK(dex_file != nullptr);
4126 ReaderMutexLock mu(self, *Locks::dex_lock_);
4127 // Search assuming unique-ness of dex file.
4128 for (const DexCacheData& data : dex_caches_) {
4129 // Avoid decoding (and read barriers) other unrelated dex caches.
4130 if (data.dex_file == dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004131 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004132 if (registered_dex_cache != nullptr) {
4133 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4134 return data.class_table;
4135 }
4136 }
4137 }
4138 return nullptr;
4139}
4140
Alex Light725da8f2020-02-19 14:46:33 -08004141const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004142 // Search assuming unique-ness of dex file.
4143 for (const DexCacheData& data : dex_caches_) {
4144 // Avoid decoding (and read barriers) other unrelated dex caches.
4145 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004146 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004147 }
4148 }
Alex Light725da8f2020-02-19 14:46:33 -08004149 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004150}
4151
Vladimir Marko70e2a762019-07-12 16:49:00 +01004152void ClassLinker::CreatePrimitiveClass(Thread* self,
4153 Primitive::Type type,
4154 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004155 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004156 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004157 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4158 // Do not hold lock on the primitive class object, the initialization of
4159 // primitive classes is done while the process is still single threaded.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004160 primitive_class->SetAccessFlagsDuringLinking(
Vladimir Marko70e2a762019-07-12 16:49:00 +01004161 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4162 primitive_class->SetPrimitiveType(type);
4163 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4164 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4165 // the kAccVerificationAttempted flag was added above, and there are no
4166 // methods that need the kAccSkipAccessChecks flag.
4167 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004168 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4169 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004170 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004171 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004172 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004173 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004174 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004175 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004176}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004177
Vladimir Marko02610552018-06-04 14:38:00 +01004178inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4179 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4180}
4181
Brian Carlstrombe977852011-07-19 14:54:54 -07004182// Create an array class (i.e. the class object for the array, not the
4183// array itself). "descriptor" looks like "[C" or "[[[[B" or
4184// "[Ljava/lang/String;".
4185//
4186// If "descriptor" refers to an array of primitives, look up the
4187// primitive type's internally-generated class object.
4188//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004189// "class_loader" is the class loader of the class that's referring to
4190// us. It's used to ensure that we're looking for the element type in
4191// the right context. It does NOT become the class loader for the
4192// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004193//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004194// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004195ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4196 const char* descriptor,
4197 size_t hash,
4198 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004199 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004200 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004201 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004202
4203 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4204 // code to be executed. We put it up here so we can avoid all the allocations associated with
4205 // creating the class. This can happen with (eg) jit threads.
4206 if (!self->CanLoadClasses()) {
4207 // Make sure we don't try to load anything, potentially causing an infinite loop.
4208 ObjPtr<mirror::Throwable> pre_allocated =
4209 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4210 self->SetException(pre_allocated);
4211 return nullptr;
4212 }
4213
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004214 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4215 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004216 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004217 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004218 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004219 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4220 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004221 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004222 DCHECK(self->IsExceptionPending());
4223 return nullptr;
4224 } else {
4225 self->ClearException();
4226 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004227 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004228 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4229 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4230 return nullptr;
4231 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004232 // See if the component type is already loaded. Array classes are
4233 // always associated with the class loader of their underlying
4234 // element type -- an array of Strings goes with the loader for
4235 // java/lang/String -- so we need to look for it there. (The
4236 // caller should have checked for the existence of the class
4237 // before calling here, but they did so with *their* class loader,
4238 // not the component type's loader.)
4239 //
4240 // If we find it, the caller adds "loader" to the class' initiating
4241 // loader list, which should prevent us from going through this again.
4242 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004243 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004244 // are the same, because our caller (FindClass) just did the
4245 // lookup. (Even if we get this wrong we still have correct behavior,
4246 // because we effectively do this lookup again when we add the new
4247 // class to the hash table --- necessary because of possible races with
4248 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004249 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004250 ObjPtr<mirror::Class> new_class =
4251 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004252 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004253 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004254 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004255 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004256 // Core array classes, i.e. Object[], Class[], String[] and primitive
4257 // arrays, have special initialization and they should be found above.
4258 DCHECK(!component_type->IsObjectClass() ||
4259 // Guard from false positives for errors before setting superclass.
4260 component_type->IsErroneousUnresolved());
4261 DCHECK(!component_type->IsStringClass());
4262 DCHECK(!component_type->IsClassClass());
4263 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004264
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004265 // Fill out the fields in the Class.
4266 //
4267 // It is possible to execute some methods against arrays, because
4268 // all arrays are subclasses of java_lang_Object_, so we need to set
4269 // up a vtable. We can just point at the one in java_lang_Object_.
4270 //
4271 // Array classes are simple enough that we don't need to do a full
4272 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004273 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4274 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4275 size_t usable_size)
4276 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004277 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004278 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4279 init_class(obj, usable_size);
4280 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4281 klass->SetComponentType(component_type.Get());
4282 // Do not hold lock for initialization, the fence issued after the visitor
4283 // returns ensures memory visibility together with the implicit consume
4284 // semantics (for all supported architectures) for any thread that loads
4285 // the array class reference from any memory locations afterwards.
4286 FinishArrayClassSetup(klass);
4287 };
4288 auto new_class = hs.NewHandle<mirror::Class>(
4289 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004290 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004291 self->AssertPendingOOMException();
4292 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004293 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004294
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004295 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004296 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004297 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4298 // duplicate events in case of races. Array classes don't really follow dedicated
4299 // load and prepare, anyways.
4300 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4301 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4302
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004303 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004304 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004305 }
4306 // Another thread must have loaded the class after we
4307 // started but before we finished. Abandon what we've
4308 // done.
4309 //
4310 // (Yes, this happens.)
4311
Vladimir Markobcf17522018-06-01 13:14:32 +01004312 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004313}
4314
Vladimir Marko9186b182018-11-06 14:55:54 +00004315ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4316 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004317 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004318 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4319 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4320 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4321 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4322 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4323 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4324 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4325 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4326 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004327 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004328 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004329 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004330 return GetClassRoot(class_root, this);
4331}
4332
4333ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4334 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4335 if (UNLIKELY(result == nullptr)) {
4336 std::string printable_type(PrintableChar(type));
4337 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4338 }
4339 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004340}
4341
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004342ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4343 ObjPtr<mirror::Class> klass,
4344 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004345 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004346 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004347 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004348 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004349 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004350 source += " from ";
4351 source += dex_cache->GetLocation()->ToModifiedUtf8();
4352 }
4353 LOG(INFO) << "Loaded class " << descriptor << source;
4354 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004355 {
4356 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004357 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004358 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004359 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004360 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004361 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004362 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004363 VerifyObject(klass);
4364 class_table->InsertWithHash(klass, hash);
4365 if (class_loader != nullptr) {
4366 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004367 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004368 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004369 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004370 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004371 }
4372 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004373 if (kIsDebugBuild) {
4374 // Test that copied methods correctly can find their holder.
4375 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4376 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4377 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004378 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004379 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004380}
4381
Vladimir Marko1998cd02017-01-13 13:02:58 +00004382void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004383 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4384 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4385 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4386 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004387 }
4388}
4389
Alex Lighte64300b2015-12-15 15:02:47 -08004390// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004391void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004392 LengthPrefixedArray<ArtMethod>* new_methods) {
4393 klass->SetMethodsPtrUnchecked(new_methods,
4394 klass->NumDirectMethods(),
4395 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004396 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004397 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004398}
4399
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004400ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4401 const char* descriptor,
4402 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004403 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4404}
4405
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004406ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4407 const char* descriptor,
4408 size_t hash,
4409 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004410 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4411 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4412 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004413 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004414 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004415 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004416 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004417 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004418 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004419}
4420
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004421class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4422 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004423 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004424
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004425 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004426 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004427 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004428 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004429 if (class_table != nullptr) {
4430 class_table->FreezeSnapshot();
4431 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004432 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004433};
4434
4435void ClassLinker::MoveClassTableToPreZygote() {
4436 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004437 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004438 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004439 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004440}
4441
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004442// Look up classes by hash and descriptor and put all matching ones in the result array.
4443class LookupClassesVisitor : public ClassLoaderVisitor {
4444 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004445 LookupClassesVisitor(const char* descriptor,
4446 size_t hash,
4447 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004448 : descriptor_(descriptor),
4449 hash_(hash),
4450 result_(result) {}
4451
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004452 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004453 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004454 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004455 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004456 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4457 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004458 result_->push_back(klass);
4459 }
4460 }
4461
4462 private:
4463 const char* const descriptor_;
4464 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004465 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004466};
4467
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004468void ClassLinker::LookupClasses(const char* descriptor,
4469 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004470 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004471 Thread* const self = Thread::Current();
4472 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004473 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004474 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004475 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004476 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004477 result.push_back(klass);
4478 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004479 LookupClassesVisitor visitor(descriptor, hash, &result);
4480 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004481}
4482
Alex Lightf1f10492015-10-07 16:08:36 -07004483bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004484 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004485 Handle<mirror::Class> klass,
4486 Handle<mirror::Class> supertype) {
4487 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004488 DCHECK(klass != nullptr);
4489 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004490
Alex Lightf1f10492015-10-07 16:08:36 -07004491 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004492 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004493 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004494
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004495 if (supertype->IsVerified()
4496 || supertype->ShouldVerifyAtRuntime()
4497 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004498 // The supertype is either verified, or we soft failed at AOT time.
4499 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004500 return true;
4501 }
4502 // If we got this far then we have a hard failure.
4503 std::string error_msg =
4504 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004505 klass->PrettyDescriptor().c_str(),
4506 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004507 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004508 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004509 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004510 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004511 // Set during VerifyClass call (if at all).
4512 self->ClearException();
4513 }
4514 // Change into a verify error.
4515 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004516 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004517 self->GetException()->SetCause(cause.Get());
4518 }
4519 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4520 if (Runtime::Current()->IsAotCompiler()) {
4521 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4522 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004523 // Need to grab the lock to change status.
4524 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004525 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004526 return false;
4527}
4528
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004529verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4530 verifier::VerifierDeps* verifier_deps,
4531 Handle<mirror::Class> klass,
4532 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004533 {
4534 // TODO: assert that the monitor on the Class is held
4535 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004536
Andreas Gampe884f3b82016-03-30 19:52:58 -07004537 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004538 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004539 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004540 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004541 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4542 // case we may see the same status again. b/62912904. This is why the check is
4543 // greater or equal.
4544 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004545 << "Class '" << klass->PrettyClass()
4546 << "' performed an illegal verification state transition from " << old_status
4547 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004548 old_status = klass->GetStatus();
4549 }
jeffhao98eacac2011-09-14 16:11:53 -07004550
Andreas Gampe884f3b82016-03-30 19:52:58 -07004551 // The class might already be erroneous, for example at compile time if we attempted to verify
4552 // this class as a parent to another.
4553 if (klass->IsErroneous()) {
4554 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004555 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004556 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004557
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004558 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004559 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004560 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Nicolas Geoffray80789962021-04-30 16:50:39 +01004561 if (verifier_deps != nullptr &&
4562 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4563 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4564 !Runtime::Current()->IsAotCompiler()) {
4565 // If the klass is verified, but `verifier_deps` did not record it, this
4566 // means we are running background verification of a secondary dex file.
4567 // Re-run the verifier to populate `verifier_deps`.
4568 // No need to run the verification when running on the AOT Compiler, as
4569 // the driver handles those multithreaded cases already.
4570 std::string error_msg;
4571 verifier::FailureKind failure =
4572 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4573 // We could have soft failures, so just check that we don't have a hard
4574 // failure.
4575 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4576 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004577 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004578 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004579
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004580 if (klass->IsVerifiedNeedsAccessChecks()) {
4581 if (!Runtime::Current()->IsAotCompiler()) {
4582 // Mark the class as having a verification attempt to avoid re-running
4583 // the verifier and avoid calling EnsureSkipAccessChecksMethods.
4584 klass->SetVerificationAttempted();
4585 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4586 }
4587 return verifier::FailureKind::kAccessChecksFailure;
4588 }
4589
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004590 // For AOT, don't attempt to re-verify if we have already found we should
4591 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004592 if (klass->ShouldVerifyAtRuntime()) {
4593 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004594 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004595 }
jeffhao98eacac2011-09-14 16:11:53 -07004596
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004597 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4598 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004599
4600 // Skip verification if disabled.
4601 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004602 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004603 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004604 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004605 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004606 }
4607
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004608 VLOG(class_linker) << "Beginning verification for class: "
4609 << klass->PrettyDescriptor()
4610 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4611
Ian Rogers9ffb0392012-09-10 11:56:50 -07004612 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004613 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004614 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4615 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004616 if (supertype != nullptr &&
4617 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004618 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004619 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004620 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004621
Alex Lightf1f10492015-10-07 16:08:36 -07004622 // Verify all default super-interfaces.
4623 //
4624 // (1) Don't bother if the superclass has already had a soft verification failure.
4625 //
4626 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4627 // recursive initialization by themselves. This is because when an interface is initialized
4628 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4629 // but choose not to for an optimization. If the interfaces is being verified due to a class
4630 // initialization (which would need all the default interfaces to be verified) the class code
4631 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004632 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004633 && !klass->IsInterface()) { // See (2)
4634 int32_t iftable_count = klass->GetIfTableCount();
4635 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4636 // Loop through all interfaces this class has defined. It doesn't matter the order.
4637 for (int32_t i = 0; i < iftable_count; i++) {
4638 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004639 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004640 // We only care if we have default interfaces and can skip if we are already verified...
4641 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4642 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004643 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004644 // We had a hard failure while verifying this interface. Just return immediately.
4645 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004646 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004647 } else if (UNLIKELY(!iface->IsVerified())) {
4648 // We softly failed to verify the iface. Stop checking and clean up.
4649 // Put the iface into the supertype handle so we know what caused us to fail.
4650 supertype.Assign(iface.Get());
4651 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004652 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004653 }
4654 }
4655
Alex Lightf1f10492015-10-07 16:08:36 -07004656 // At this point if verification failed, then supertype is the "first" supertype that failed
4657 // verification (without a specific order). If verification succeeded, then supertype is either
4658 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004659 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004660 supertype.Get() == klass->GetSuperClass() ||
4661 !supertype->IsVerified());
4662
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004663 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004664 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004665 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004666 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004667
4668 VLOG(class_linker) << "Class preverified status for class "
4669 << klass->PrettyDescriptor()
4670 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4671 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004672 << preverified
4673 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004674
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004675 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4676 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004677 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4678 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004679
Ian Rogers62d6c772013-02-27 08:32:07 -08004680 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004681 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004682 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004683 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004684 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004685
4686 // Verification is done, grab the lock again.
4687 ObjectLock<mirror::Class> lock(self, klass);
4688
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004689 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4690 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004691 VLOG(class_linker) << "Soft verification failure in class "
4692 << klass->PrettyDescriptor()
4693 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4694 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004695 }
Ian Rogers1f539342012-10-03 21:09:42 -07004696 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004697 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004698 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004699 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004700 // Even though there were no verifier failures we need to respect whether the super-class and
4701 // super-default-interfaces were verified or requiring runtime reverification.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004702 if (supertype == nullptr
4703 || supertype->IsVerified()
4704 || supertype->IsVerifiedNeedsAccessChecks()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004705 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004706 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004707 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004708 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4709 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004710 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004711 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004712 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004713 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004714 CHECK(verifier_failure == verifier::FailureKind::kSoftFailure ||
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004715 verifier_failure == verifier::FailureKind::kTypeChecksFailure ||
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004716 verifier_failure == verifier::FailureKind::kAccessChecksFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004717 // Soft failures at compile time should be retried at runtime. Soft
4718 // failures at runtime will be handled by slow paths in the generated
4719 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004720 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004721 if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4722 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004723 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4724 } else {
4725 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4726 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004727 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004728 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004729 // As this is a fake verified status, make sure the methods are _not_ marked
4730 // kAccSkipAccessChecks later.
4731 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004732 }
4733 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004734 } else {
David Sehr709b0702016-10-13 09:12:37 -07004735 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004736 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4737 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004738 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004739 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004740 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004741 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004742 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004743 if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks ||
4744 UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004745 // Never skip access checks if the verification soft fail is forced.
4746 // Mark the class as having a verification attempt to avoid re-running the verifier.
4747 klass->SetVerificationAttempted();
4748 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004749 // Class is verified so we don't need to do any access check on its methods.
4750 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
4751 // method.
4752 // Note: we're going here during compilation and at runtime. When we set the
4753 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
4754 // in the image and is set when loading the image.
Andreas Gampecc1b5352016-12-01 16:58:38 -08004755 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004756 }
Andreas Gampe48498592014-09-10 19:48:05 -07004757 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004758 // Done verifying. Notify the compiler about the verification status, in case the class
4759 // was verified implicitly (eg super class of a compiled class).
4760 if (Runtime::Current()->IsAotCompiler()) {
4761 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4762 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4763 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004764 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004765}
4766
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004767verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004768 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004769 Handle<mirror::Class> klass,
4770 verifier::HardFailLogMode log_level,
4771 std::string* error_msg) {
4772 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004773 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004774 verifier_deps,
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004775 klass.Get(),
4776 runtime->GetCompilerCallbacks(),
4777 runtime->IsAotCompiler(),
4778 log_level,
4779 Runtime::Current()->GetTargetSdkVersion(),
4780 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004781}
4782
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004783bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4784 const DexFile& dex_file,
4785 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004786 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004787 // If we're compiling, we can only verify the class using the oat file if
4788 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004789 // the compilation unit (app - dependencies). We will let the compiler callback
4790 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004791 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004792 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004793 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004794 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004795 return false;
4796 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004797 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004798
Andreas Gampeb40d3612018-06-26 15:49:42 -07004799 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004800 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004801 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004802 return false;
4803 }
4804
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004805 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004806 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004807 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004808 return true;
4809 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004810 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4811 // We return that the clas has already been verified, and the caller should
4812 // check the class status to ensure we run with access checks.
4813 return true;
4814 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004815
4816 // Check the class status with the vdex file.
4817 const OatFile* oat_file = oat_dex_file->GetOatFile();
4818 if (oat_file != nullptr) {
4819 oat_file_class_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4820 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4821 return true;
4822 }
4823 }
4824
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004825 // If we only verified a subset of the classes at compile time, we can end up with classes that
4826 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004827 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004828 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004829 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004830 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4831 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4832 << klass->PrettyClass() << " " << dex_file.GetLocation();
4833
Vladimir Marko72ab6842017-01-20 19:32:50 +00004834 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004835 // Compile time verification failed with a hard error. This is caused by invalid instructions
4836 // in the class. These errors are unrecoverable.
4837 return false;
4838 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004839 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004840 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4841 // not loading the class.
4842 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4843 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004844 return false;
4845 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004846 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004847 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004848 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004849 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004850 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004851}
4852
Alex Light5a559862016-01-29 12:24:48 -08004853void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004854 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004855 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004856 }
4857}
4858
Alex Light5a559862016-01-29 12:24:48 -08004859void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004860 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004861 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004862 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004863 return; // native or abstract method
4864 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004865 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004866 return; // nothing to process
4867 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004868 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004869 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004870 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4871 CatchHandlerIterator iterator(handlers_ptr);
4872 for (; iterator.HasNext(); iterator.Next()) {
4873 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4874 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004875 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004876 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004877 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004878 DCHECK(Thread::Current()->IsExceptionPending());
4879 Thread::Current()->ClearException();
4880 }
4881 }
4882 }
4883 handlers_ptr = iterator.EndDataPointer();
4884 }
4885}
4886
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004887ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4888 jstring name,
4889 jobjectArray interfaces,
4890 jobject loader,
4891 jobjectArray methods,
4892 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004893 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004894
4895 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4896 // code to be executed. We put it up here so we can avoid all the allocations associated with
4897 // creating the class. This can happen with (eg) jit-threads.
4898 if (!self->CanLoadClasses()) {
4899 // Make sure we don't try to load anything, potentially causing an infinite loop.
4900 ObjPtr<mirror::Throwable> pre_allocated =
4901 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4902 self->SetException(pre_allocated);
4903 return nullptr;
4904 }
4905
Alex Light133987d2020-03-26 19:22:12 +00004906 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004907 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004908 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004909 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004910 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004911 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004912 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004913 DCHECK(temp_klass->GetClass() != nullptr);
4914 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004915 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4916 // the methods.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004917 temp_klass->SetAccessFlagsDuringLinking(
4918 kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004919 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4920 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4921 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004922 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004923 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004924 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004925 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004926 std::string storage;
4927 const char* descriptor = temp_klass->GetDescriptor(&storage);
4928 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004929
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004930 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004931 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004932
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004933 // Insert the class before loading the fields as the field roots
4934 // (ArtField::declaring_class_) are only visited from the class
4935 // table. There can't be any suspend points between inserting the
4936 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004937 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004938 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004939
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004940 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004941 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004942 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004943 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004944
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004945 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4946 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004947 ArtField& interfaces_sfield = sfields->At(0);
4948 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004949 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004950 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004951
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004952 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004953 ArtField& throws_sfield = sfields->At(1);
4954 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004955 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004956 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004957
Ian Rogers466bb252011-10-14 03:29:56 -07004958 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004959 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004960
Alex Light133987d2020-03-26 19:22:12 +00004961 // The array we get passed contains all methods, including private and static
4962 // ones that aren't proxied. We need to filter those out since only interface
4963 // methods (non-private & virtual) are actually proxied.
4964 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4965 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004966 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004967 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004968 // List of the actual virtual methods this class will have.
4969 std::vector<ArtMethod*> proxied_methods;
4970 std::vector<size_t> proxied_throws_idx;
4971 proxied_methods.reserve(h_methods->GetLength());
4972 proxied_throws_idx.reserve(h_methods->GetLength());
4973 // Filter out to only the non-private virtual methods.
4974 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4975 ArtMethod* m = mirror->GetArtMethod();
4976 if (!m->IsPrivate() && !m->IsStatic()) {
4977 proxied_methods.push_back(m);
4978 proxied_throws_idx.push_back(idx);
4979 }
4980 }
4981 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004982 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4983 // contains an array of all the classes each function is declared to throw.
4984 // This is used to wrap unexpected exceptions in a
4985 // UndeclaredThrowableException exception. This array is in the same order as
4986 // the methods array and like the methods array must be filtered to remove any
4987 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004988 const bool has_filtered_methods =
4989 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4990 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4991 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4992 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4993 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4994 (has_filtered_methods)
4995 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4996 self, original_proxied_throws->GetClass(), num_virtual_methods)
4997 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004998 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4999 self->AssertPendingOOMException();
5000 return nullptr;
5001 }
Alex Light133987d2020-03-26 19:22:12 +00005002 if (has_filtered_methods) {
5003 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
5004 DCHECK_LE(new_idx, orig_idx);
5005 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
5006 }
5007 }
Alex Lighte64300b2015-12-15 15:02:47 -08005008
5009 // Create the methods array.
5010 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5011 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005012 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5013 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005014 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005015 self->AssertPendingOOMException();
5016 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005017 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005018 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005019
5020 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005021 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005022
5023 // Create virtual method using specified prototypes.
5024 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005025 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005026 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005027 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005028 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005029 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5030 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005031 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005032
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005033 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005034 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005035 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005036 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005037 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005038
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005039 // At this point the class is loaded. Publish a ClassLoad event.
5040 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5041 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5042
5043 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005044 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005045 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005046 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005047 // Link the fields and virtual methods, creating vtable and iftables.
5048 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005049 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005050 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005051 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005052 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005053 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005054 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005055 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005056 CHECK(temp_klass->IsRetired());
5057 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005058
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005059 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005060 interfaces_sfield.SetObject<false>(
5061 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005062 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005063 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5064 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005065 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005066 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005067
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005068 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5069
Vladimir Marko305c38b2018-02-14 11:50:07 +00005070 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5071 // See also ClassLinker::EnsureInitialized().
5072 if (kBitstringSubtypeCheckEnabled) {
5073 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5074 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5075 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5076 }
5077
Vladimir Markobf121912019-06-04 13:49:05 +01005078 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005079 {
5080 // Lock on klass is released. Lock new class object.
5081 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005082 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005083 // Conservatively go through the ClassStatus::kInitialized state.
5084 callback = MarkClassInitialized(self, klass);
5085 }
5086 if (callback != nullptr) {
5087 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005088 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005089
David Srbecky346fd962020-07-27 16:51:00 +01005090 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005091 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005092 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005093 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5094
Ian Rogersc2b44472011-12-14 21:17:17 -08005095 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005096 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005097 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005098 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005099
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005100 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005101 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005102 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005103 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005104 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005105
5106 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005107 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005108 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005109
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005110 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005111 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005112 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005113 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005114 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005115 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005116}
5117
Mathieu Chartiere401d142015-04-22 13:56:20 -07005118void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5119 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005120 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5121 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005122
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005123 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5124 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005125 ArtMethod* proxy_constructor =
5126 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005127 DCHECK(proxy_constructor != nullptr)
5128 << "Could not find <init> method in java.lang.reflect.Proxy";
5129
Jeff Haodb8a6642014-08-14 17:18:52 -07005130 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5131 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005132 DCHECK(out != nullptr);
5133 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005134 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005135 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005136 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005137 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5138 kAccPublic |
5139 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005140 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005141
5142 // Set the original constructor method.
5143 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005144}
5145
Mathieu Chartiere401d142015-04-22 13:56:20 -07005146void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005147 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005148 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5149 CHECK_STREQ(np->GetName(), "<init>");
5150 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005151 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005152}
5153
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005154void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005155 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005156 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005157 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005158 DCHECK(out != nullptr);
5159 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005160
Alex Lighte9dd04f2016-03-16 16:09:45 -07005161 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005162 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005163 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005164 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005165 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005166 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005167 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5168 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005169 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5170
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005171 // Set the original interface method.
5172 out->SetDataPtrSize(prototype, image_pointer_size_);
5173
Ian Rogers466bb252011-10-14 03:29:56 -07005174 // At runtime the method looks like a reference and argument saving method, clone the code
5175 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005176 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005177}
Jesse Wilson95caa792011-10-12 18:14:17 -04005178
Mathieu Chartiere401d142015-04-22 13:56:20 -07005179void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005180 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005181 CHECK(!prototype->IsFinal());
5182 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005183 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005184
5185 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5186 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005187 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005188 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005189}
5190
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005191bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005192 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005193 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005194 return true;
5195 }
5196 if (!can_init_statics) {
5197 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005198 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005199 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005200 return false;
5201 }
5202 // Check if there are encoded static values needing initialization.
5203 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005204 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005205 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005206 if (dex_class_def->static_values_off_ != 0) {
5207 return false;
5208 }
5209 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005210 }
5211 // If we are a class we need to initialize all interfaces with default methods when we are
5212 // initialized. Check all of them.
5213 if (!klass->IsInterface()) {
5214 size_t num_interfaces = klass->GetIfTableCount();
5215 for (size_t i = 0; i < num_interfaces; i++) {
5216 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5217 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5218 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005219 return false;
5220 }
5221 }
5222 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005223 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005224 if (klass->IsInterface() || !klass->HasSuperClass()) {
5225 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005226 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005227 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005228 if (super_class->IsInitialized()) {
5229 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005230 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005231 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005232}
5233
Mathieu Chartier23369542020-03-04 08:24:11 -08005234bool ClassLinker::InitializeClass(Thread* self,
5235 Handle<mirror::Class> klass,
5236 bool can_init_statics,
5237 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005238 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5239
5240 // Are we already initialized and therefore done?
5241 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5242 // an initialized class will never change its state.
5243 if (klass->IsInitialized()) {
5244 return true;
5245 }
5246
5247 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005248 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005249 return false;
5250 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005251
Ian Rogers7b078e82014-09-10 14:44:24 -07005252 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005253 Runtime* const runtime = Runtime::Current();
5254 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005255 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005256 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005257 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005258
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005259 // Re-check under the lock in case another thread initialized ahead of us.
5260 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005261 return true;
5262 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005263
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005264 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005265 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005266 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005267 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005268 return false;
5269 }
5270
Vladimir Marko72ab6842017-01-20 19:32:50 +00005271 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5272 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005273
5274 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005275 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005276 if (!klass->IsVerified()) {
5277 // We failed to verify, expect either the klass to be erroneous or verification failed at
5278 // compile time.
5279 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005280 // The class is erroneous. This may be a verifier error, or another thread attempted
5281 // verification and/or initialization and failed. We can distinguish those cases by
5282 // whether an exception is already pending.
5283 if (self->IsExceptionPending()) {
5284 // Check that it's a VerifyError.
5285 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005286 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005287 } else {
5288 // Check that another thread attempted initialization.
5289 DCHECK_NE(0, klass->GetClinitThreadId());
5290 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5291 // Need to rethrow the previous failure now.
5292 ThrowEarlierClassFailure(klass.Get(), true);
5293 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005294 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005295 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005296 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005297 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005298 self->AssertNoPendingException();
5299 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005300 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005301 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005302 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005303 } else {
5304 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005305 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005306
5307 // A separate thread could have moved us all the way to initialized. A "simple" example
5308 // involves a subclass of the current class being initialized at the same time (which
5309 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005310 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005311 if (klass->IsInitialized()) {
5312 return true;
5313 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005314 }
5315
Vladimir Marko2c64a832018-01-04 11:31:56 +00005316 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005317 // initializing higher up the stack or another thread has beat us
5318 // to initializing and we need to wait. Either way, this
5319 // invocation of InitializeClass will not be responsible for
5320 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005321 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005322 // Could have got an exception during verification.
5323 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005324 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005325 return false;
5326 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005327 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005328 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005329 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005330 return true;
5331 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005332 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005333 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005334 }
5335
Jeff Haoe2e40342017-07-19 10:45:18 -07005336 // Try to get the oat class's status for this class if the oat file is present. The compiler
5337 // tries to validate superclass descriptors, and writes the result into the oat file.
5338 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5339 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5340 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005341 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005342 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5343 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5344 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005345 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005346 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005347 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005348 return false;
5349 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005350 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005351
Vladimir Marko2c64a832018-01-04 11:31:56 +00005352 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005353 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005354
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005355 // From here out other threads may observe that we're initializing and so changes of state
5356 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005357 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005358 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005359
Mathieu Chartier23369542020-03-04 08:24:11 -08005360 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005361 }
5362
Andreas Gampeaf864702019-07-23 14:05:35 -07005363 uint64_t t_sub = 0;
5364
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005365 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005366 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005367 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005368 if (!super_class->IsInitialized()) {
5369 CHECK(!super_class->IsInterface());
5370 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005371 StackHandleScope<1> hs(self);
5372 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005373 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005374 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005375 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005376 if (!super_initialized) {
5377 // The super class was verified ahead of entering initializing, we should only be here if
5378 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005379 // For the case of aot compiler, the super class might also be initializing but we don't
5380 // want to process circular dependencies in pre-compile.
5381 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005382 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005383 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005384 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005385 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005386 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005387 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005388 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005389 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005390 return false;
5391 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005392 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005393 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005394 }
5395
Alex Lighteb7c1442015-08-31 13:17:42 -07005396 if (!klass->IsInterface()) {
5397 // Initialize interfaces with default methods for the JLS.
5398 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005399 // Only setup the (expensive) handle scope if we actually need to.
5400 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005401 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005402 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5403 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005404 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005405 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005406 CHECK(handle_scope_iface->IsInterface());
5407 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5408 // We have already done this for this interface. Skip it.
5409 continue;
5410 }
5411 // We cannot just call initialize class directly because we need to ensure that ALL
5412 // interfaces with default methods are initialized. Non-default interface initialization
5413 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005414 // This is not very precise, misses all walking.
5415 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005416 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5417 handle_scope_iface,
5418 can_init_statics,
5419 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005420 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005421 if (!iface_initialized) {
5422 ObjectLock<mirror::Class> lock(self, klass);
5423 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005424 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005425 return false;
5426 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005427 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005428 }
5429 }
5430 }
5431
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005432 const size_t num_static_fields = klass->NumStaticFields();
5433 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005434 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005435 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005436 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005437 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005438 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005439
5440 // Eagerly fill in static fields so that the we don't have to do as many expensive
5441 // Class::FindStaticField in ResolveField.
5442 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005443 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005444 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005445 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005446 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005447 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005448 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5449 field,
5450 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5451 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005452 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005453 } else {
5454 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005455 }
5456 }
5457
Vladimir Markoe11dd502017-12-08 14:09:45 +00005458 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5459 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005460 this,
5461 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005462 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005463
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005464 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005465 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005466 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005467 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5468 if (!value_it.HasNext()) {
5469 break;
5470 }
5471 ArtField* art_field = ResolveField(field.GetIndex(),
5472 dex_cache,
5473 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005474 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005475 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005476 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005477 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005478 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005479 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005480 if (self->IsExceptionPending()) {
5481 break;
5482 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005483 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005484 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005485 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005486 }
5487 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005488
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005489
Mathieu Chartierda595be2016-08-10 13:57:39 -07005490 if (!self->IsExceptionPending()) {
5491 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5492 if (clinit != nullptr) {
5493 CHECK(can_init_statics);
5494 JValue result;
5495 clinit->Invoke(self, nullptr, 0, &result, "V");
5496 }
5497 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005498 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005499 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005500
Vladimir Markobf121912019-06-04 13:49:05 +01005501 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005502 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005503 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005504 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005505
5506 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005507 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005508 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005509 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005510 } else if (Runtime::Current()->IsTransactionAborted()) {
5511 // The exception thrown when the transaction aborted has been caught and cleared
5512 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005513 VLOG(compiler) << "Return from class initializer of "
5514 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005515 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005516 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005517 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005518 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005519 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005520 if (stats_enabled) {
5521 RuntimeStats* global_stats = runtime->GetStats();
5522 RuntimeStats* thread_stats = self->GetStats();
5523 ++global_stats->class_init_count;
5524 ++thread_stats->class_init_count;
5525 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5526 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5527 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005528 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005529 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005530 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005531 std::string temp;
5532 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005533 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005534 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005535 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005536 }
Vladimir Markobf121912019-06-04 13:49:05 +01005537 if (callback != nullptr) {
5538 callback->MakeVisible(self);
5539 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005540 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005541}
5542
Alex Lighteb7c1442015-08-31 13:17:42 -07005543// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5544// and perform the initialization only on those interfaces that contain default methods.
5545bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5546 Handle<mirror::Class> iface,
5547 bool can_init_statics,
5548 bool can_init_parents) {
5549 CHECK(iface->IsInterface());
5550 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005551 // Only create the (expensive) handle scope if we need it.
5552 if (UNLIKELY(num_direct_ifaces > 0)) {
5553 StackHandleScope<1> hs(self);
5554 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5555 // First we initialize all of iface's super-interfaces recursively.
5556 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005557 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005558 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005559 if (!super_iface->HasBeenRecursivelyInitialized()) {
5560 // Recursive step
5561 handle_super_iface.Assign(super_iface);
5562 if (!InitializeDefaultInterfaceRecursive(self,
5563 handle_super_iface,
5564 can_init_statics,
5565 can_init_parents)) {
5566 return false;
5567 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005568 }
5569 }
5570 }
5571
5572 bool result = true;
5573 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5574 // initialize if we don't have default methods.
5575 if (iface->HasDefaultMethods()) {
5576 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5577 }
5578
5579 // Mark that this interface has undergone recursive default interface initialization so we know we
5580 // can skip it on any later class initializations. We do this even if we are not a default
5581 // interface since we can still avoid the traversal. This is purely a performance optimization.
5582 if (result) {
5583 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005584 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5585 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5586 // initialization is a performance optimization (to avoid another idempotent visit
5587 // for other implementing classes/interfaces), and can be revisited later.
5588 ObjectTryLock<mirror::Class> lock(self, iface);
5589 if (lock.Acquired()) {
5590 iface->SetRecursivelyInitialized();
5591 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005592 }
5593 return result;
5594}
5595
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005596bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5597 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005598 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005599 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005600 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005601 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005602 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005603 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005604
5605 // When we wake up, repeat the test for init-in-progress. If
5606 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005607 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005608 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005609 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005610 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005611 return false;
5612 }
5613 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005614 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005615 continue;
5616 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005617 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005618 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005619 // Compile time initialization failed.
5620 return false;
5621 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005622 if (klass->IsErroneous()) {
5623 // The caller wants an exception, but it was thrown in a
5624 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005625 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005626 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005627 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005628 return false;
5629 }
5630 if (klass->IsInitialized()) {
5631 return true;
5632 }
David Sehr709b0702016-10-13 09:12:37 -07005633 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005634 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005635 }
Ian Rogers07140832014-09-30 15:43:59 -07005636 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005637}
5638
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005639static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5640 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005641 ArtMethod* method,
5642 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005643 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005644 DCHECK(Thread::Current()->IsExceptionPending());
5645 DCHECK(!m->IsProxyMethod());
5646 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005647 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5648 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005649 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005650 std::string return_type = dex_file->PrettyType(return_type_idx);
5651 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005652 ThrowWrappedLinkageError(klass.Get(),
5653 "While checking class %s method %s signature against %s %s: "
5654 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005655 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5656 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005657 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005658 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005659 return_type.c_str(), class_loader.c_str());
5660}
5661
5662static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5663 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005664 ArtMethod* method,
5665 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005666 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005667 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005668 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005669 DCHECK(Thread::Current()->IsExceptionPending());
5670 DCHECK(!m->IsProxyMethod());
5671 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005672 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5673 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005674 ThrowWrappedLinkageError(klass.Get(),
5675 "While checking class %s method %s signature against %s %s: "
5676 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005677 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5678 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005679 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005680 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005681 index, arg_type.c_str(), class_loader.c_str());
5682}
5683
5684static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5685 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005686 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005687 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005688 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005689 ThrowLinkageError(klass.Get(),
5690 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005691 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5692 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005693 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005694 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005695 error_msg.c_str());
5696}
5697
Ian Rogersb5fb2072014-12-02 17:22:02 -08005698static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005699 Handle<mirror::Class> klass,
5700 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005701 ArtMethod* method1,
5702 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005703 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005704 {
5705 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005706 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005707 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005708 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005709 return false;
5710 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005711 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005712 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005713 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005714 return false;
5715 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005716 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005717 ThrowSignatureMismatch(klass, super_klass, method1,
5718 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005719 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005720 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005721 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005722 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005723 return false;
5724 }
5725 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005726 const dex::TypeList* types1 = method1->GetParameterTypeList();
5727 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005728 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005729 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005730 ThrowSignatureMismatch(klass, super_klass, method1,
5731 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005732 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005733 return false;
5734 }
5735 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005736 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005737 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005738 ThrowSignatureMismatch(klass, super_klass, method1,
5739 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005740 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005741 return false;
5742 }
5743 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005744 }
5745 uint32_t num_types = types1->Size();
5746 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005747 ThrowSignatureMismatch(klass, super_klass, method1,
5748 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005749 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005750 return false;
5751 }
5752 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005753 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005754 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005755 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005756 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005757 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005758 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005759 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005760 return false;
5761 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005762 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005763 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005764 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005765 if (UNLIKELY(other_param_type == nullptr)) {
5766 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005767 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005768 return false;
5769 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005770 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005771 ThrowSignatureMismatch(klass, super_klass, method1,
5772 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5773 i,
David Sehr709b0702016-10-13 09:12:37 -07005774 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005775 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005776 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005777 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005778 return false;
5779 }
5780 }
5781 return true;
5782}
5783
5784
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005785bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005786 if (klass->IsInterface()) {
5787 return true;
5788 }
Ian Rogers151f2212014-05-06 11:27:27 -07005789 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005790 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005791 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005792 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005793 if (klass->HasSuperClass() &&
5794 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005795 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005796 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005797 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5798 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5799 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005800 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5801 klass,
5802 super_klass,
5803 m,
5804 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005805 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005806 return false;
5807 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005808 }
5809 }
5810 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005811 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005812 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5813 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5814 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005815 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005816 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5817 j, image_pointer_size_);
5818 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5819 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005820 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5821 klass,
5822 super_klass,
5823 m,
5824 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005825 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005826 return false;
5827 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005828 }
5829 }
5830 }
5831 }
5832 return true;
5833}
5834
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005835bool ClassLinker::EnsureInitialized(Thread* self,
5836 Handle<mirror::Class> c,
5837 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005838 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005839 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005840
Mathieu Chartier524507a2014-08-27 15:28:28 -07005841 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005842 // If we've seen an initialized but not visibly initialized class
5843 // many times, request visible initialization.
5844 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5845 // Thanks to the x86 memory model classes skip the initialized status.
5846 DCHECK(c->IsVisiblyInitialized());
5847 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5848 if (self->IncrementMakeVisiblyInitializedCounter()) {
5849 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5850 }
5851 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005852 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005853 return true;
5854 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005855 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5856 //
5857 // Ensure the bitstring is initialized before any of the class initialization
5858 // logic occurs. Once a class initializer starts running, objects can
5859 // escape into the heap and use the subtype checking code.
5860 //
5861 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5862 // can be used as a source for the IsSubClass check, and that all ancestors
5863 // of the class are Assigned (can be used as a target for IsSubClass check)
5864 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005865 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005866 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005867 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005868 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5869 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005870 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005871 if (!success) {
5872 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005873 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005874 } else {
5875 // There may or may not be an exception pending. If there is, clear it.
5876 // We propagate the exception only if we can initialize fields and parents.
5877 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005878 }
5879 } else {
5880 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005881 }
5882 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005883}
5884
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005885void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5886 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005887 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005888 for (ArtField& field : new_class->GetIFields()) {
5889 if (field.GetDeclaringClass() == temp_class) {
5890 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005891 }
5892 }
5893
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005894 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005895 for (ArtField& field : new_class->GetSFields()) {
5896 if (field.GetDeclaringClass() == temp_class) {
5897 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005898 }
5899 }
5900
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005901 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005902 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005903 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005904 if (method.GetDeclaringClass() == temp_class) {
5905 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005906 }
5907 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005908
5909 // Make sure the remembered set and mod-union tables know that we updated some of the native
5910 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005911 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005912}
5913
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005914void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005915 CHECK(class_loader->GetAllocator() == nullptr);
5916 CHECK(class_loader->GetClassTable() == nullptr);
5917 Thread* const self = Thread::Current();
5918 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005919 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005920 // Create and set the class table.
5921 data.class_table = new ClassTable;
5922 class_loader->SetClassTable(data.class_table);
5923 // Create and set the linear allocator.
5924 data.allocator = Runtime::Current()->CreateLinearAlloc();
5925 class_loader->SetAllocator(data.allocator);
5926 // Add to the list so that we know to free the data later.
5927 class_loaders_.push_back(data);
5928}
5929
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005930ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005931 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005932 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005933 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005934 ClassTable* class_table = class_loader->GetClassTable();
5935 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005936 RegisterClassLoader(class_loader);
5937 class_table = class_loader->GetClassTable();
5938 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005939 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005940 return class_table;
5941}
5942
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005943ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005944 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005945}
5946
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005947static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005948 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005949 while (klass->HasSuperClass()) {
5950 klass = klass->GetSuperClass();
5951 if (klass->ShouldHaveImt()) {
5952 return klass->GetImt(pointer_size);
5953 }
5954 }
5955 return nullptr;
5956}
5957
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005958bool ClassLinker::LinkClass(Thread* self,
5959 const char* descriptor,
5960 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005961 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005962 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005963 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005964
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005965 if (!LinkSuperClass(klass)) {
5966 return false;
5967 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005968 ArtMethod* imt_data[ImTable::kSize];
5969 // If there are any new conflicts compared to super class.
5970 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005971 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005972 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005973 return false;
5974 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005975 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005976 return false;
5977 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005978 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005979 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005980 return false;
5981 }
5982 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005983 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005984
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005985 ImTable* imt = nullptr;
5986 if (klass->ShouldHaveImt()) {
5987 // If there are any new conflicts compared to the super class we can not make a copy. There
5988 // can be cases where both will have a conflict method at the same slot without having the same
5989 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5990 // will possibly create a table that is incorrect for either of the classes.
5991 // Same IMT with new_conflict does not happen very often.
5992 if (!new_conflict) {
5993 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5994 if (super_imt != nullptr) {
5995 bool imt_equals = true;
5996 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5997 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5998 }
5999 if (imt_equals) {
6000 imt = super_imt;
6001 }
6002 }
6003 }
6004 if (imt == nullptr) {
6005 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6006 imt = reinterpret_cast<ImTable*>(
6007 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6008 if (imt == nullptr) {
6009 return false;
6010 }
6011 imt->Populate(imt_data, image_pointer_size_);
6012 }
6013 }
6014
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006015 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6016 // We don't need to retire this class as it has no embedded tables or it was created the
6017 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006018 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006019
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006020 if (klass->ShouldHaveEmbeddedVTable()) {
6021 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006022 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006023 if (klass->ShouldHaveImt()) {
6024 klass->SetImt(imt, image_pointer_size_);
6025 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006026
6027 // Update CHA info based on whether we override methods.
6028 // Have to do this before setting the class as resolved which allows
6029 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006030 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006031 cha_->UpdateAfterLoadingOf(klass);
6032 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006033
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006034 // This will notify waiters on klass that saw the not yet resolved
6035 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006036 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006037 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006038 } else {
6039 CHECK(!klass->IsResolved());
6040 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006041 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006042 Handle<mirror::Class> h_new_class =
6043 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006044 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6045 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6046 // may not see any references to the target space and clean the card for a class if another
6047 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006048 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006049 klass->SetSFieldsPtrUnchecked(nullptr);
6050 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006051 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006052 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006053 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006054 return false;
6055 }
6056
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006057 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6058 ObjectLock<mirror::Class> lock(self, h_new_class);
6059 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006060
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006061 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006062 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006063 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006064 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006065 const ObjPtr<mirror::Class> existing =
6066 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006067 if (class_loader != nullptr) {
6068 // We updated the class in the class table, perform the write barrier so that the GC knows
6069 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006070 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006071 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006072 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006073 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006074 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6075 }
6076 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006077
Mingyao Yang063fc772016-08-02 11:02:54 -07006078 // Update CHA info based on whether we override methods.
6079 // Have to do this before setting the class as resolved which allows
6080 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006081 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006082 cha_->UpdateAfterLoadingOf(h_new_class);
6083 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006084
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006085 // This will notify waiters on temp class that saw the not yet resolved class in the
6086 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006087 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006088
Vladimir Marko2c64a832018-01-04 11:31:56 +00006089 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006090 // This will notify waiters on new_class that saw the not yet resolved
6091 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006092 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006093 // Return the new class.
6094 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006095 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006096 return true;
6097}
6098
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006099bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006100 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006101 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006102 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6103 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006104 // Check that a class does not inherit from itself directly.
6105 //
6106 // TODO: This is a cheap check to detect the straightforward case
6107 // of a class extending itself (b/28685551), but we should do a
6108 // proper cycle detection on loaded classes, to detect all cases
6109 // of class circularity errors (b/28830038).
6110 if (super_class_idx == class_def.class_idx_) {
6111 ThrowClassCircularityError(klass.Get(),
6112 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006113 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006114 return false;
6115 }
6116
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006117 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006118 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006119 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006120 return false;
6121 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006122 // Verify
6123 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006124 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006125 super_class->PrettyDescriptor().c_str(),
6126 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006127 return false;
6128 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006129 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006130 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006131 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006132 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006133 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006134 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006135 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006136 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006137 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006138 DCHECK(Thread::Current()->IsExceptionPending());
6139 return false;
6140 }
6141 // Verify
6142 if (!klass->CanAccess(interface)) {
6143 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006144 ThrowIllegalAccessError(klass.Get(),
6145 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006146 interface->PrettyDescriptor().c_str(),
6147 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006148 return false;
6149 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006150 }
6151 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006152 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006153 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006154 return true;
6155}
6156
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006157bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006158 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006159 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006160 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6161 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006162 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006163 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006164 return false;
6165 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006166 return true;
6167 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006168 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006169 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006170 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006171 return false;
6172 }
6173 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006174 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006175 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6176 return false;
6177 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006178 if (super->IsFinal()) {
6179 ThrowVerifyError(klass.Get(),
6180 "Superclass %s of %s is declared final",
6181 super->PrettyDescriptor().c_str(),
6182 klass->PrettyDescriptor().c_str());
6183 return false;
6184 }
6185 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006186 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006187 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006188 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006189 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006190 return false;
6191 }
6192 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006193 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006194 super->PrettyDescriptor().c_str(),
6195 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006196 return false;
6197 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006198
Brian Carlstromf3632832014-05-20 15:36:53 -07006199 // Inherit kAccClassIsFinalizable from the superclass in case this
6200 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006201 if (super->IsFinalizable()) {
6202 klass->SetFinalizable();
6203 }
6204
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006205 // Inherit class loader flag form super class.
6206 if (super->IsClassLoaderClass()) {
6207 klass->SetClassLoaderClass();
6208 }
6209
Elliott Hughes2da50362011-10-10 16:57:08 -07006210 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006211 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006212 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006213 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006214 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006215 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006216 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006217 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006218 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006219 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006220 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006221 return false;
6222 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006223
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006224 if (kIsDebugBuild) {
6225 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006226 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006227 CHECK(super->IsResolved());
6228 super = super->GetSuperClass();
6229 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006230 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006231 return true;
6232}
6233
Vladimir Marko782fb712020-12-23 12:47:31 +00006234// A wrapper class representing the result of a method translation used for linking methods and
6235// updating superclass default methods. For each method in a classes vtable there are 4 states it
6236// could be in:
6237// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6238// is the standard case and is true when the method is not overridable by a default method,
6239// the class defines a concrete implementation of the method, the default method implementation
6240// remains the same, or an abstract method stayed abstract.
6241// 2) The method must be translated to a different default method. We note this with
6242// CreateTranslatedMethod.
6243// 3) The method must be replaced with a conflict method. This happens when a superclass
6244// implements an interface with a default method and this class implements an unrelated
6245// interface that also defines that default method. We note this with CreateConflictingMethod.
6246// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6247// implements an interface with a default method and this class implements a subinterface of
6248// the superclass's interface which declares the default method abstract. We note this with
6249// CreateAbstractMethod.
6250//
6251// When a method translation is unnecessary (case #1), we don't put it into the
6252// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6253class ClassLinker::MethodTranslation {
6254 public:
6255 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6256
6257 // This slot must become a default conflict method.
6258 static MethodTranslation CreateConflictingMethod() {
6259 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6260 }
6261
6262 // This slot must become an abstract method.
6263 static MethodTranslation CreateAbstractMethod() {
6264 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6265 }
6266
6267 // Use the given method as the current value for this vtable slot during translation.
6268 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6269 return MethodTranslation(Type::kTranslation, new_method);
6270 }
6271
6272 // Returns true if this is a method that must become a conflict method.
6273 bool IsInConflict() const {
6274 return type_ == Type::kConflict;
6275 }
6276
6277 // Returns true if this is a method that must become an abstract method.
6278 bool IsAbstract() const {
6279 return type_ == Type::kAbstract;
6280 }
6281
6282 // Returns true if this is a method that must become a different method.
6283 bool IsTranslation() const {
6284 return type_ == Type::kTranslation;
6285 }
6286
6287 // Get the translated version of this method.
6288 ArtMethod* GetTranslation() const {
6289 DCHECK(IsTranslation());
6290 DCHECK(translation_ != nullptr);
6291 return translation_;
6292 }
6293
6294 private:
6295 enum class Type {
6296 kInvalid,
6297 kTranslation,
6298 kConflict,
6299 kAbstract,
6300 };
6301
6302 MethodTranslation(Type type, ArtMethod* translation)
6303 : translation_(translation), type_(type) {}
6304
6305 ArtMethod* translation_;
6306 Type type_;
6307};
6308
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006309// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006310bool ClassLinker::LinkMethods(Thread* self,
6311 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006312 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006313 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006314 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006315 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006316 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6317 // need to have default methods be in the virtuals array of each class but we don't set that up
6318 // until LinkInterfaceMethods.
Vladimir Marko782fb712020-12-23 12:47:31 +00006319 constexpr size_t kBufferSize = 8; // Avoid malloc/free for a few translations.
6320 std::pair<size_t, ClassLinker::MethodTranslation> buffer[kBufferSize];
6321 HashMap<size_t, ClassLinker::MethodTranslation> default_translations(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006322 // Link virtual methods then interface methods.
6323 // We set up the interface lookup table first because we need it to determine if we need to update
6324 // any vtable entries with new default method implementations.
6325 return SetupInterfaceLookupTable(self, klass, interfaces)
6326 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006327 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006328}
6329
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006330// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6331// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6332// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006333class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006334 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006335 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006336 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006337 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6338 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006339 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006340 }
6341
6342 const char* GetName() {
6343 if (name_ == nullptr) {
6344 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6345 }
6346 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006347 }
6348
Mathieu Chartiere401d142015-04-22 13:56:20 -07006349 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006350 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006351 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006352 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006353 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006354 if (dex_file_ == other_dex_file) {
6355 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6356 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006357 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006358 uint32_t other_name_len;
6359 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6360 &other_name_len);
6361 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6362 return false;
6363 }
6364 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6365 }
6366
6367 private:
6368 // Dex file for the method to compare against.
6369 const DexFile* const dex_file_;
6370 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006371 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006372 // Lazily computed name from the dex file's strings.
6373 const char* name_;
6374 // Lazily computed name length.
6375 uint32_t name_len_;
6376};
6377
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006378class LinkVirtualHashTable {
6379 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006380 LinkVirtualHashTable(Handle<mirror::Class> klass,
6381 size_t hash_size,
6382 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006383 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006384 : klass_(klass),
6385 hash_size_(hash_size),
6386 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006387 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006388 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6389 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006390
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006391 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006392 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6393 virtual_method_index, image_pointer_size_);
6394 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006395 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006396 uint32_t index = hash % hash_size_;
6397 // Linear probe until we have an empty slot.
6398 while (hash_table_[index] != invalid_index_) {
6399 if (++index == hash_size_) {
6400 index = 0;
6401 }
6402 }
6403 hash_table_[index] = virtual_method_index;
6404 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006405
Vladimir Marko43354742021-02-03 15:37:01 +00006406 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator, uint32_t hash)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006407 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko43354742021-02-03 15:37:01 +00006408 DCHECK_EQ(hash, ComputeModifiedUtf8Hash(comparator->GetName()));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006409 size_t index = hash % hash_size_;
6410 while (true) {
6411 const uint32_t value = hash_table_[index];
6412 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6413 // the block and can safely assume not found.
6414 if (value == invalid_index_) {
6415 break;
6416 }
6417 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006418 ArtMethod* virtual_method =
6419 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6420 if (comparator->HasSameNameAndSignature(
6421 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006422 hash_table_[index] = removed_index_;
6423 return value;
6424 }
6425 }
6426 if (++index == hash_size_) {
6427 index = 0;
6428 }
6429 }
6430 return GetNotFoundIndex();
6431 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006432
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006433 static uint32_t GetNotFoundIndex() {
6434 return invalid_index_;
6435 }
6436
6437 private:
6438 static const uint32_t invalid_index_;
6439 static const uint32_t removed_index_;
6440
6441 Handle<mirror::Class> klass_;
6442 const size_t hash_size_;
6443 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006444 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006445};
6446
6447const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6448const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6449
Stephen Hines1ddd9132017-02-08 01:51:18 -08006450bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006451 Thread* self,
6452 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006453 /*out*/HashMap<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006454 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006455 if (klass->IsInterface()) {
6456 // No vtable.
6457 if (!IsUint<16>(num_virtual_methods)) {
6458 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6459 return false;
6460 }
6461 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006462 // Assign each method an IMT index and set the default flag.
6463 for (size_t i = 0; i < num_virtual_methods; ++i) {
6464 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6465 m->SetMethodIndex(i);
6466 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006467 // If the dex file does not support default methods, throw ClassFormatError.
6468 // This check is necessary to protect from odd cases, such as native default
6469 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6470 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6471 // currently running CTS tests for default methods with dex file version 035 which
6472 // does not support default methods. So, we limit this to native methods. b/157718952
6473 if (m->IsNative()) {
6474 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6475 ThrowClassFormatError(klass.Get(),
6476 "Dex file does not support default method '%s'",
6477 m->PrettyMethod().c_str());
6478 return false;
6479 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006480 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6481 has_defaults = true;
6482 }
6483 }
6484 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6485 // during initialization. This is a performance optimization. We could simply traverse the
6486 // virtual_methods_ array again during initialization.
6487 if (has_defaults) {
6488 klass->SetHasDefaultMethods();
6489 }
6490 return true;
6491 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006492 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6493 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006494 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006495 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006496 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006497 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006498 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006499 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006500 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006501 return false;
6502 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006503 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006504 vtable->SetElementPtrSize(
6505 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006506 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006507 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6508 // might give us new default methods). If no new interfaces then we can skip the rest since
6509 // the class cannot override any of the super-class's methods. This is required for
6510 // correctness since without it we might not update overridden default method vtable entries
6511 // correctly.
6512 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006513 klass->SetVTable(vtable.Get());
6514 return true;
6515 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006516 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006517 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006518 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006519 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006520 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6521 // might give us new default methods). See comment above.
6522 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006523 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006524 return true;
6525 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006526 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6527 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006528 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006529 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006530 return false;
6531 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006532 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006533 // How the algorithm works:
6534 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6535 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6536 // method which has not been matched to a vtable method, and j if the virtual method at the
6537 // index overrode the super virtual method at index j.
6538 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6539 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6540 // the need for the initial vtable which we later shrink back down).
6541 // 3. Add non overridden methods to the end of the vtable.
6542 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006543 // + 1 so that even if we only have new default methods we will still be able to use this hash
6544 // table (i.e. it will never have 0 size).
6545 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006546 uint32_t* hash_table_ptr;
6547 std::unique_ptr<uint32_t[]> hash_heap_storage;
6548 if (hash_table_size <= kMaxStackHash) {
6549 hash_table_ptr = reinterpret_cast<uint32_t*>(
6550 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6551 } else {
6552 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6553 hash_table_ptr = hash_heap_storage.get();
6554 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006555 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006556 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006557 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006558 DCHECK(klass->GetVirtualMethodDuringLinking(
6559 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006560 hash_table.Add(i);
6561 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006562 // 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 -07006563 // the hash table.
6564 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006565 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006566 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006567 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6568 super_method->GetAccessFlags())) {
6569 // Continue on to the next method since this one is package private and canot be overridden.
6570 // Before Android 4.1, the package-private method super_method might have been incorrectly
6571 // overridden.
6572 continue;
6573 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006574 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006575 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006576 // We remove the method so that subsequent lookups will be faster by making the hash-map
6577 // smaller as we go on.
Vladimir Marko43354742021-02-03 15:37:01 +00006578 uint32_t hash = (j < mirror::Object::kVTableLength)
6579 ? object_virtual_method_hashes_[j]
6580 : ComputeModifiedUtf8Hash(super_method_name_comparator.GetName());
6581 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator, hash);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006582 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006583 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6584 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006585 if (super_method->IsFinal()) {
6586 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6587 virtual_method->PrettyMethod().c_str(),
6588 super_method->GetDeclaringClassDescriptor());
6589 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006590 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006591 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6592 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006593 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006594 // We didn't directly override this method but we might through default methods...
6595 // Check for default method update.
6596 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006597 switch (FindDefaultMethodImplementation(self,
6598 super_method,
6599 klass,
6600 /*out*/&default_method)) {
6601 case DefaultMethodSearchResult::kDefaultConflict: {
6602 // A conflict was found looking for default methods. Note this (assuming it wasn't
6603 // pre-existing) in the translations map.
6604 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6605 // Don't generate another conflict method to reduce memory use as an optimization.
6606 default_translations->insert(
6607 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6608 }
6609 break;
6610 }
6611 case DefaultMethodSearchResult::kAbstractFound: {
6612 // No conflict but method is abstract.
6613 // We note that this vtable entry must be made abstract.
6614 if (UNLIKELY(!super_method->IsAbstract())) {
6615 default_translations->insert(
6616 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6617 }
6618 break;
6619 }
6620 case DefaultMethodSearchResult::kDefaultFound: {
6621 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6622 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6623 // Found a default method implementation that is new.
6624 // TODO Refactor this add default methods to virtuals here and not in
6625 // LinkInterfaceMethods maybe.
6626 // The problem is default methods might override previously present
6627 // default-method or miranda-method vtable entries from the superclass.
6628 // Unfortunately we need these to be entries in this class's virtuals. We do not
6629 // give these entries there until LinkInterfaceMethods so we pass this map around
6630 // to let it know which vtable entries need to be updated.
6631 // Make a note that vtable entry j must be updated, store what it needs to be updated
6632 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6633 // then.
6634 default_translations->insert(
6635 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006636 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6637 << " overridden by default "
6638 << default_method->PrettyMethod()
6639 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006640 }
6641 break;
6642 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006643 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006644 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006645 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006646 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006647 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006648 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006649 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006650 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6651 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006652 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006653 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006654 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006655 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006656 local_method->SetMethodIndex(actual_count);
6657 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006658 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006659 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006660 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006661 return false;
6662 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006663 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006664 CHECK_LE(actual_count, max_count);
6665 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006666 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6667 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006668 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006669 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006670 return false;
6671 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006672 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006673 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006674 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006675 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006676 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006677 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6678 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006679 return false;
6680 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006681 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006682 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006683 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006684 return false;
6685 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006686 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006687 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6688 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006689 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006690 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006691 klass->SetVTable(vtable);
Vladimir Marko43354742021-02-03 15:37:01 +00006692 InitializeObjectVirtualMethodHashes(klass.Get(),
6693 image_pointer_size_,
6694 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006695 }
6696 return true;
6697}
6698
Alex Light9139e002015-10-09 15:59:48 -07006699// Determine if the given iface has any subinterface in the given list that declares the method
6700// specified by 'target'.
6701//
6702// Arguments
6703// - self: The thread we are running on
6704// - target: A comparator that will match any method that overrides the method we are checking for
6705// - iftable: The iftable we are searching for an overriding method on.
6706// - ifstart: The index of the interface we are checking to see if anything overrides
6707// - iface: The interface we are checking to see if anything overrides.
6708// - image_pointer_size:
6709// The image pointer size.
6710//
6711// Returns
6712// - True: There is some method that matches the target comparator defined in an interface that
6713// is a subtype of iface.
6714// - False: There is no method that matches the target comparator in any interface that is a subtype
6715// of iface.
6716static bool ContainsOverridingMethodOf(Thread* self,
6717 MethodNameAndSignatureComparator& target,
6718 Handle<mirror::IfTable> iftable,
6719 size_t ifstart,
6720 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006721 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006722 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006723 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006724 DCHECK(iface != nullptr);
6725 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006726 DCHECK_GE(ifstart, 0u);
6727 DCHECK_LT(ifstart, iftable->Count());
6728 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6729 DCHECK(iface->IsInterface());
6730
6731 size_t iftable_count = iftable->Count();
6732 StackHandleScope<1> hs(self);
6733 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6734 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6735 // Skip ifstart since our current interface obviously cannot override itself.
6736 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006737 // Iterate through every method on this interface. The order does not matter.
6738 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006739 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006740 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006741 // Check if the i'th interface is a subtype of this one.
6742 if (iface->IsAssignableFrom(current_iface.Get())) {
6743 return true;
6744 }
6745 break;
6746 }
6747 }
6748 }
6749 return false;
6750}
6751
Alex Lighteb7c1442015-08-31 13:17:42 -07006752// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006753// out_default_method and returns kDefaultFound on success. If no default method was found return
6754// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6755// default_method conflict) it will return kDefaultConflict.
6756ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6757 Thread* self,
6758 ArtMethod* target_method,
6759 Handle<mirror::Class> klass,
6760 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006761 DCHECK(self != nullptr);
6762 DCHECK(target_method != nullptr);
6763 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006764
6765 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006766
6767 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6768 // table. This lets us walk the table backwards when searching for default methods. The first one
6769 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6770 // track of it and then continue checking all other interfaces, since we need to throw an error if
6771 // we encounter conflicting default method implementations (one is not a subtype of the other).
6772 //
6773 // The order of unrelated interfaces does not matter and is not defined.
6774 size_t iftable_count = klass->GetIfTableCount();
6775 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006776 // No interfaces. We have already reset out to null so just return kAbstractFound.
6777 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006778 }
6779
Alex Light9139e002015-10-09 15:59:48 -07006780 StackHandleScope<3> hs(self);
6781 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006782 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006783 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006784 MethodNameAndSignatureComparator target_name_comparator(
6785 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6786 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006787 for (size_t k = iftable_count; k != 0; ) {
6788 --k;
6789
Alex Lighteb7c1442015-08-31 13:17:42 -07006790 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006791
6792 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006793 // Iterate through every declared method on this interface. The order does not matter.
6794 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6795 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006796 // Skip abstract methods and methods with different names.
6797 if (current_method->IsAbstract() ||
6798 !target_name_comparator.HasSameNameAndSignature(
6799 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6800 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006801 } else if (!current_method->IsPublic()) {
6802 // The verifier should have caught the non-public method for dex version 37. Just warn and
6803 // skip it since this is from before default-methods so we don't really need to care that it
6804 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006805 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6806 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006807 << "This will be a fatal error in subsequent versions of android. "
6808 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006809 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006810 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006811 // We have multiple default impls of the same method. This is a potential default conflict.
6812 // We need to check if this possibly conflicting method is either a superclass of the chosen
6813 // default implementation or is overridden by a non-default interface method. In either case
6814 // there is no conflict.
6815 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6816 !ContainsOverridingMethodOf(self,
6817 target_name_comparator,
6818 iftable,
6819 k,
6820 iface,
6821 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006822 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006823 << current_method->PrettyMethod() << " and "
6824 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6825 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006826 *out_default_method = nullptr;
6827 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006828 } else {
6829 break; // Continue checking at the next interface.
6830 }
6831 } else {
Alex Light9139e002015-10-09 15:59:48 -07006832 // chosen_iface == null
6833 if (!ContainsOverridingMethodOf(self,
6834 target_name_comparator,
6835 iftable,
6836 k,
6837 iface,
6838 image_pointer_size_)) {
6839 // Don't set this as the chosen interface if something else is overriding it (because that
6840 // other interface would be potentially chosen instead if it was default). If the other
6841 // interface was abstract then we wouldn't select this interface as chosen anyway since
6842 // the abstract method masks it.
6843 *out_default_method = current_method;
6844 chosen_iface.Assign(iface.Get());
6845 // We should now finish traversing the graph to find if we have default methods that
6846 // conflict.
6847 } else {
David Sehr709b0702016-10-13 09:12:37 -07006848 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6849 << "' was "
6850 << "skipped because it was overridden by an abstract method in a "
6851 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006852 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006853 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006854 break;
6855 }
6856 }
Alex Light9139e002015-10-09 15:59:48 -07006857 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006858 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6859 << "' selected "
6860 << "as the implementation for '" << target_method->PrettyMethod()
6861 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006862 return DefaultMethodSearchResult::kDefaultFound;
6863 } else {
6864 return DefaultMethodSearchResult::kAbstractFound;
6865 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006866}
6867
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006868ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006869 ArtMethod* conflict_method,
6870 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006871 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006872 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006873 Runtime* const runtime = Runtime::Current();
6874 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006875
6876 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006877 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006878 ? runtime->CreateImtConflictMethod(linear_alloc)
6879 : conflict_method;
6880
6881 // Allocate a new table. Note that we will leak this table at the next conflict,
6882 // but that's a tradeoff compared to making the table fixed size.
6883 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006884 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6885 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006886 if (data == nullptr) {
6887 LOG(ERROR) << "Failed to allocate conflict table";
6888 return conflict_method;
6889 }
6890 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6891 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006892 method,
6893 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006894
6895 // Do a fence to ensure threads see the data in the table before it is assigned
6896 // to the conflict method.
6897 // Note that there is a race in the presence of multiple threads and we may leak
6898 // memory from the LinearAlloc, but that's a tradeoff compared to using
6899 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006900 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006901 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006902 return new_conflict_method;
6903}
6904
Vladimir Marko921094a2017-01-12 18:37:06 +00006905bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6906 Handle<mirror::Class> klass,
6907 Handle<mirror::IfTable> iftable) {
6908 DCHECK(!klass->IsInterface());
6909 const bool has_superclass = klass->HasSuperClass();
6910 const bool extend_super_iftable = has_superclass;
6911 const size_t ifcount = klass->GetIfTableCount();
6912 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6913 for (size_t i = 0; i < ifcount; ++i) {
6914 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6915 if (num_methods > 0) {
6916 const bool is_super = i < super_ifcount;
6917 // This is an interface implemented by a super-class. Therefore we can just copy the method
6918 // array from the superclass.
6919 const bool super_interface = is_super && extend_super_iftable;
6920 ObjPtr<mirror::PointerArray> method_array;
6921 if (super_interface) {
6922 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6923 DCHECK(if_table != nullptr);
6924 DCHECK(if_table->GetMethodArray(i) != nullptr);
6925 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006926 StackHandleScope<1u> hs(self);
6927 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6928 method_array =
6929 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006930 } else {
6931 method_array = AllocPointerArray(self, num_methods);
6932 }
6933 if (UNLIKELY(method_array == nullptr)) {
6934 self->AssertPendingOOMException();
6935 return false;
6936 }
6937 iftable->SetMethodArray(i, method_array);
6938 }
6939 }
6940 return true;
6941}
6942
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006943void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6944 ArtMethod* imt_conflict_method,
6945 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006946 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006947 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006948 // Place method in imt if entry is empty, place conflict otherwise.
6949 if (*imt_ref == unimplemented_method) {
6950 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006951 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006952 // If we are not a conflict and we have the same signature and name as the imt
6953 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006954 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6955 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006956 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006957 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006958 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006959 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006960 *imt_ref = current_method;
6961 } else {
Alex Light9139e002015-10-09 15:59:48 -07006962 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006963 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006964 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006965 } else {
6966 // Place the default conflict method. Note that there may be an existing conflict
6967 // method in the IMT, but it could be one tailored to the super class, with a
6968 // specific ImtConflictTable.
6969 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006970 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006971 }
6972}
6973
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006974void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006975 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6976 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006977 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006978 Runtime* const runtime = Runtime::Current();
6979 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6980 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006981 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006982 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006983 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006984 FillIMTFromIfTable(klass->GetIfTable(),
6985 unimplemented_method,
6986 conflict_method,
6987 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006988 /*create_conflict_tables=*/true,
6989 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006990 &new_conflict,
6991 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006992 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006993 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6994 // we can just use the same pointer.
6995 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006996 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006997 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6998 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6999 bool same = true;
7000 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
7001 ArtMethod* method = imt_data[i];
7002 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
7003 if (method != super_method) {
7004 bool is_conflict_table = method->IsRuntimeMethod() &&
7005 method != unimplemented_method &&
7006 method != conflict_method;
7007 // Verify conflict contents.
7008 bool super_conflict_table = super_method->IsRuntimeMethod() &&
7009 super_method != unimplemented_method &&
7010 super_method != conflict_method;
7011 if (!is_conflict_table || !super_conflict_table) {
7012 same = false;
7013 } else {
7014 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
7015 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
7016 same = same && table1->Equals(table2, image_pointer_size_);
7017 }
7018 }
7019 }
7020 if (same) {
7021 imt = super_imt;
7022 }
7023 }
7024 if (imt == nullptr) {
7025 imt = klass->GetImt(image_pointer_size_);
7026 DCHECK(imt != nullptr);
7027 imt->Populate(imt_data, image_pointer_size_);
7028 } else {
7029 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007030 }
7031}
7032
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007033ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7034 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007035 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007036 void* data = linear_alloc->Alloc(Thread::Current(),
7037 ImtConflictTable::ComputeSize(count,
7038 image_pointer_size));
7039 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7040}
7041
7042ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7043 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7044}
7045
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007046void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007047 ArtMethod* unimplemented_method,
7048 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007049 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007050 bool create_conflict_tables,
7051 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007052 /*out*/bool* new_conflict,
7053 /*out*/ArtMethod** imt) {
7054 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007055 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007056 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007057 const size_t num_virtuals = interface->NumVirtualMethods();
7058 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7059 // Virtual methods can be larger than the if table methods if there are default methods.
7060 DCHECK_GE(num_virtuals, method_array_count);
7061 if (kIsDebugBuild) {
7062 if (klass->IsInterface()) {
7063 DCHECK_EQ(method_array_count, 0u);
7064 } else {
7065 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7066 }
7067 }
7068 if (method_array_count == 0) {
7069 continue;
7070 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007071 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007072 for (size_t j = 0; j < method_array_count; ++j) {
7073 ArtMethod* implementation_method =
7074 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7075 if (ignore_copied_methods && implementation_method->IsCopied()) {
7076 continue;
7077 }
7078 DCHECK(implementation_method != nullptr);
7079 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7080 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7081 // or interface methods in the IMT here they will not create extra conflicts since we compare
7082 // names and signatures in SetIMTRef.
7083 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007084 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007085
7086 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7087 // the same implementation method, keep track of this to avoid creating a conflict table in
7088 // this case.
7089
7090 // Conflict table size for each IMT slot.
7091 ++conflict_counts[imt_index];
7092
7093 SetIMTRef(unimplemented_method,
7094 imt_conflict_method,
7095 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007096 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007097 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007098 }
7099 }
7100
7101 if (create_conflict_tables) {
7102 // Create the conflict tables.
7103 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007104 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007105 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007106 if (imt[i] == imt_conflict_method) {
7107 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7108 if (new_table != nullptr) {
7109 ArtMethod* new_conflict_method =
7110 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7111 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7112 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007113 } else {
7114 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007115 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007116 }
7117 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007118 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007119 }
7120 }
7121
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007122 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007123 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007124 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7125 // Virtual methods can be larger than the if table methods if there are default methods.
7126 if (method_array_count == 0) {
7127 continue;
7128 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007129 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007130 for (size_t j = 0; j < method_array_count; ++j) {
7131 ArtMethod* implementation_method =
7132 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7133 if (ignore_copied_methods && implementation_method->IsCopied()) {
7134 continue;
7135 }
7136 DCHECK(implementation_method != nullptr);
7137 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007138 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007139 if (!imt[imt_index]->IsRuntimeMethod() ||
7140 imt[imt_index] == unimplemented_method ||
7141 imt[imt_index] == imt_conflict_method) {
7142 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007143 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007144 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7145 const size_t num_entries = table->NumEntries(image_pointer_size_);
7146 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7147 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007148 }
7149 }
7150 }
7151}
7152
Alex Lighteb7c1442015-08-31 13:17:42 -07007153// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7154// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007155static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00007156 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007157 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007158 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007159 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007160 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007161 for (ObjPtr<mirror::Class> c : classes) {
7162 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007163 return false;
7164 }
7165 }
7166 return true;
7167}
7168
7169// Fills in and flattens the interface inheritance hierarchy.
7170//
7171// By the end of this function all interfaces in the transitive closure of to_process are added to
7172// the iftable and every interface precedes all of its sub-interfaces in this list.
7173//
7174// all I, J: Interface | I <: J implies J precedes I
7175//
7176// (note A <: B means that A is a subtype of B)
7177//
7178// This returns the total number of items in the iftable. The iftable might be resized down after
7179// this call.
7180//
7181// We order this backwards so that we do not need to reorder superclass interfaces when new
7182// interfaces are added in subclass's interface tables.
7183//
7184// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7185// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7186// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7187// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Marko782fb712020-12-23 12:47:31 +00007188static size_t FillIfTable(Thread* self,
7189 ObjPtr<mirror::Class> klass,
7190 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
7191 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007192 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00007193 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007194 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00007195 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
7196 // This is the set of all classes already in the iftable. Used to make checking
7197 // if a class has already been added quicker.
7198 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
7199 mirror::Class* buffer[kBufferSize];
7200 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07007201 // The first super_ifcount elements are from the superclass. We note that they are already added.
7202 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007203 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007204 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007205 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007206 }
7207 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00007208 const bool have_interfaces = interfaces != nullptr;
7209 for (size_t i = 0; i != num_interfaces; ++i) {
7210 ObjPtr<mirror::Class> interface = have_interfaces
7211 ? interfaces->Get(i)
7212 : mirror::Class::GetDirectInterface(self, klass, i);
7213
Alex Lighteb7c1442015-08-31 13:17:42 -07007214 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7215 // At this point in the loop current-iface-list has the invariant that:
7216 // for every pair of interfaces I,J within it:
7217 // if index_of(I) < index_of(J) then I is not a subtype of J
7218
7219 // If we have already seen this element then all of its super-interfaces must already be in the
7220 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00007221 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007222 // We haven't seen this interface so add all of its super-interfaces onto the
7223 // current-iface-list, skipping those already on it.
7224 int32_t ifcount = interface->GetIfTableCount();
7225 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007226 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007227 if (!ContainsElement(classes_in_iftable, super_interface)) {
7228 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007229 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007230 iftable->SetInterface(filled_ifcount, super_interface);
7231 filled_ifcount++;
7232 }
7233 }
7234 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7235 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00007236 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007237 iftable->SetInterface(filled_ifcount, interface);
7238 filled_ifcount++;
7239 } else if (kIsDebugBuild) {
7240 // Check all super-interfaces are already in the list.
7241 int32_t ifcount = interface->GetIfTableCount();
7242 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007243 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007244 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007245 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7246 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007247 }
7248 }
7249 }
7250 if (kIsDebugBuild) {
7251 // Check that the iftable is ordered correctly.
7252 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007253 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007254 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007255 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007256 // !(if_a <: if_b)
7257 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007258 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7259 << ") extends "
7260 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007261 << "interface list.";
7262 }
7263 }
7264 }
7265 return filled_ifcount;
7266}
7267
Vladimir Marko782fb712020-12-23 12:47:31 +00007268bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
7269 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07007270 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7271 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007272 const bool has_superclass = klass->HasSuperClass();
7273 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007274 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007275 const size_t num_interfaces =
7276 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007277 if (num_interfaces == 0) {
7278 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007279 if (LIKELY(has_superclass)) {
7280 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7281 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007282 // Class implements no interfaces.
7283 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007284 return true;
7285 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007286 // Class implements same interfaces as parent, are any of these not marker interfaces?
7287 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007288 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007289 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007290 if (super_iftable->GetMethodArrayCount(i) > 0) {
7291 has_non_marker_interface = true;
7292 break;
7293 }
7294 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007295 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007296 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007297 klass->SetIfTable(super_iftable);
7298 return true;
7299 }
7300 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007301 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007302 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007303 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007304 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007305 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007306 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007307 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007308 if (UNLIKELY(!interface->IsInterface())) {
7309 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007310 ThrowIncompatibleClassChangeError(klass.Get(),
7311 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007312 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007313 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7314 return false;
7315 }
7316 ifcount += interface->GetIfTableCount();
7317 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007318 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007319 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007320 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007321 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007322 return false;
7323 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007324 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007325 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007326 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007327 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007328 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007329 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007330 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007331 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007332
7333 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7334 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7335 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007336 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007337
Vladimir Marko782fb712020-12-23 12:47:31 +00007338 const size_t new_ifcount = FillIfTable(
7339 self, klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007340
Ian Rogers7b078e82014-09-10 14:44:24 -07007341 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007342
Ian Rogersb52b01a2012-01-12 17:01:38 -08007343 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007344 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007345 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007346 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007347 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007348 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007349 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007350 return false;
7351 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007352 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007353 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007354 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007355 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007356 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007357 return true;
7358}
7359
Alex Light1f3925d2016-09-07 12:04:20 -07007360// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7361// of methods must be unique.
7362static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7363 return nullptr;
7364}
7365
7366template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007367static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007368 const ScopedArenaVector<ArtMethod*>& list,
7369 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007370 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007371 for (ArtMethod* method : list) {
7372 if (cmp.HasSameNameAndSignature(method)) {
7373 return method;
7374 }
7375 }
Alex Light1f3925d2016-09-07 12:04:20 -07007376 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007377}
7378
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007379namespace {
7380
Alex Light1f3925d2016-09-07 12:04:20 -07007381// Check that all vtable entries are present in this class's virtuals or are the same as a
7382// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007383void CheckClassOwnsVTableEntries(Thread* self,
7384 Handle<mirror::Class> klass,
7385 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007386 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007387 StackHandleScope<2> hs(self);
7388 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007389 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007390 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007391 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007392 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7393 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7394 CHECK(m != nullptr);
7395
Alex Lighta41a30782017-03-29 11:33:19 -07007396 if (m->GetMethodIndexDuringLinking() != i) {
7397 LOG(WARNING) << m->PrettyMethod()
7398 << " has an unexpected method index for its spot in the vtable for class"
7399 << klass->PrettyClass();
7400 }
Alex Lighte64300b2015-12-15 15:02:47 -08007401 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7402 auto is_same_method = [m] (const ArtMethod& meth) {
7403 return &meth == m;
7404 };
Alex Light3f980532017-03-17 15:10:32 -07007405 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7406 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7407 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7408 << klass->PrettyClass() << " or any of its superclasses!";
7409 }
Alex Lighte64300b2015-12-15 15:02:47 -08007410 }
7411}
7412
Alex Light1f3925d2016-09-07 12:04:20 -07007413// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7414// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007415template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007416void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007417 REQUIRES_SHARED(Locks::mutator_lock_) {
7418 StackHandleScope<1> hs(self);
7419 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7420 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007421
7422 // Observations:
7423 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7424 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7425 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7426 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7427 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7428 // * The single-pass algorithm will trade memory for speed, but that is OK.
7429
7430 CHECK_GT(num_entries, 0);
7431
7432 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7433 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7434 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7435 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7436 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7437 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7438 << m2->PrettyMethod() << " (0x" << std::hex
7439 << reinterpret_cast<uintptr_t>(m2) << ")";
7440 };
7441 struct BaseHashType {
7442 static size_t HashCombine(size_t seed, size_t val) {
7443 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7444 }
7445 };
7446
7447 // Check assuming all entries come from the same dex file.
7448 {
7449 // Find the first interesting method and its dex file.
7450 int32_t start = 0;
7451 for (; start < num_entries; ++start) {
7452 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7453 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7454 // maybe).
7455 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7456 vtable_entry->GetAccessFlags())) {
7457 continue;
7458 }
7459 break;
7460 }
7461 if (start == num_entries) {
7462 return;
7463 }
7464 const DexFile* dex_file =
7465 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7466 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7467
7468 // Helper function to avoid logging if we have to run the cross-file checks.
7469 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7470 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7471 using PairType = std::pair<uint32_t, uint16_t>;
7472 struct PairHash : BaseHashType {
7473 size_t operator()(const PairType& key) const {
7474 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7475 }
7476 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007477 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007478 seen.reserve(2 * num_entries);
7479 bool need_slow_path = false;
7480 bool found_dup = false;
7481 for (int i = start; i < num_entries; ++i) {
7482 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7483 // wrt/ kPointerSize.
7484 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7485 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7486 vtable_entry->GetAccessFlags())) {
7487 continue;
7488 }
7489 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7490 if (dex_file != m->GetDexFile()) {
7491 need_slow_path = true;
7492 break;
7493 }
7494 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7495 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7496 auto it = seen.find(pair);
7497 if (it != seen.end()) {
7498 found_dup = true;
7499 if (log_warn) {
7500 log_fn(it->second, i);
7501 }
7502 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007503 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007504 }
7505 }
7506 return std::make_pair(need_slow_path, found_dup);
7507 };
7508 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7509 if (!result.first) {
7510 if (result.second) {
7511 check_fn(/* log_warn= */ true);
7512 }
7513 return;
7514 }
7515 }
7516
7517 // Need to check across dex files.
7518 struct Entry {
7519 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007520 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007521 const char* name = nullptr;
7522 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007523
Vladimir Marko782fb712020-12-23 12:47:31 +00007524 Entry() = default;
7525 Entry(const Entry& other) = default;
7526 Entry& operator=(const Entry& other) = default;
7527
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007528 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007529 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7530 // This call writes `name_len` and it is therefore necessary that the
7531 // initializer for `name_len` comes before it, otherwise the value
7532 // from the call would be overwritten by that initializer.
7533 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007534 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007535 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7536 if (name[name_len] != 0) {
7537 name_len += strlen(name + name_len);
7538 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007539 }
7540
7541 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007542 return name_len == other.name_len &&
7543 memcmp(name, other.name, name_len) == 0 &&
7544 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007545 }
7546 };
7547 struct EntryHash {
7548 size_t operator()(const Entry& key) const {
7549 return key.cached_hash;
7550 }
7551 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007552 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007553 for (int32_t i = 0; i < num_entries; ++i) {
7554 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7555 // wrt/ kPointerSize.
7556 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7557 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7558 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007559 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7560 vtable_entry->GetAccessFlags())) {
7561 continue;
7562 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007563 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7564 const DexFile* dex_file = m->GetDexFile();
7565 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7566
7567 Entry e(dex_file, mid);
7568
7569 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7570 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7571 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7572 sig_hash);
7573
7574 auto it = map.find(e);
7575 if (it != map.end()) {
7576 log_fn(it->second, i);
7577 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007578 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007579 }
7580 }
7581}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007582
7583void CheckVTableHasNoDuplicates(Thread* self,
7584 Handle<mirror::Class> klass,
7585 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007586 REQUIRES_SHARED(Locks::mutator_lock_) {
7587 switch (pointer_size) {
7588 case PointerSize::k64:
7589 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7590 break;
7591 case PointerSize::k32:
7592 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7593 break;
7594 }
7595}
Alex Light1f3925d2016-09-07 12:04:20 -07007596
Orion Hodson5880c772020-07-28 20:12:08 +01007597static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007598 REQUIRES_SHARED(Locks::mutator_lock_) {
7599 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7600 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7601}
7602
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007603} // namespace
7604
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007605void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7606 ArtMethod* unimplemented_method,
7607 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007608 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007609 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007610 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007611 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007612 if (super_class->ShouldHaveImt()) {
7613 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7614 for (size_t i = 0; i < ImTable::kSize; ++i) {
7615 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007616 }
7617 } else {
7618 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007619 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007620 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007621 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007622 FillIMTFromIfTable(if_table,
7623 unimplemented_method,
7624 imt_conflict_method,
7625 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007626 /*create_conflict_tables=*/false,
7627 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007628 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007629 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007630 }
7631 }
7632}
7633
Vladimir Marko921094a2017-01-12 18:37:06 +00007634class ClassLinker::LinkInterfaceMethodsHelper {
7635 public:
7636 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7637 Handle<mirror::Class> klass,
7638 Thread* self,
7639 Runtime* runtime)
7640 : class_linker_(class_linker),
7641 klass_(klass),
7642 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7643 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7644 self_(self),
7645 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7646 allocator_(&stack_),
7647 default_conflict_methods_(allocator_.Adapter()),
7648 overriding_default_conflict_methods_(allocator_.Adapter()),
7649 miranda_methods_(allocator_.Adapter()),
7650 default_methods_(allocator_.Adapter()),
7651 overriding_default_methods_(allocator_.Adapter()),
7652 move_table_(allocator_.Adapter()) {
7653 }
7654
7655 ArtMethod* FindMethod(ArtMethod* interface_method,
7656 MethodNameAndSignatureComparator& interface_name_comparator,
7657 ArtMethod* vtable_impl)
7658 REQUIRES_SHARED(Locks::mutator_lock_);
7659
7660 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7661 MethodNameAndSignatureComparator& interface_name_comparator)
7662 REQUIRES_SHARED(Locks::mutator_lock_);
7663
7664 bool HasNewVirtuals() const {
7665 return !(miranda_methods_.empty() &&
7666 default_methods_.empty() &&
7667 overriding_default_methods_.empty() &&
7668 overriding_default_conflict_methods_.empty() &&
7669 default_conflict_methods_.empty());
7670 }
7671
7672 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7673
7674 ObjPtr<mirror::PointerArray> UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007675 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007676 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007677
7678 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7679
7680 void UpdateIMT(ArtMethod** out_imt);
7681
7682 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7683 if (kIsDebugBuild) {
7684 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7685 // Check that there are no stale methods are in the dex cache array.
7686 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7687 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
David Srbecky5de5efe2021-02-15 21:23:00 +00007688 auto pair = mirror::DexCache::GetNativePair(resolved_methods, i);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007689 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007690 CHECK(move_table_.find(m) == move_table_.end() ||
7691 // The original versions of copied methods will still be present so allow those too.
7692 // Note that if the first check passes this might fail to GetDeclaringClass().
7693 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7694 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7695 [m] (ArtMethod& meth) {
7696 return &meth == m;
7697 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7698 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7699 }
7700 }
7701 }
7702
7703 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7704 LengthPrefixedArray<ArtMethod>* methods) {
7705 if (kIsDebugBuild) {
7706 CHECK(methods != nullptr);
7707 // Put some random garbage in old methods to help find stale pointers.
7708 if (methods != old_methods && old_methods != nullptr) {
7709 // Need to make sure the GC is not running since it could be scanning the methods we are
7710 // about to overwrite.
7711 ScopedThreadStateChange tsc(self_, kSuspended);
7712 gc::ScopedGCCriticalSection gcs(self_,
7713 gc::kGcCauseClassLinker,
7714 gc::kCollectorTypeClassLinker);
7715 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7716 method_size_,
7717 method_alignment_);
7718 memset(old_methods, 0xFEu, old_size);
7719 }
7720 }
7721 }
7722
7723 private:
7724 size_t NumberOfNewVirtuals() const {
7725 return miranda_methods_.size() +
7726 default_methods_.size() +
7727 overriding_default_conflict_methods_.size() +
7728 overriding_default_methods_.size() +
7729 default_conflict_methods_.size();
7730 }
7731
7732 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7733 return !klass_->IsInterface();
7734 }
7735
7736 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7737 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7738 << "Interfaces should only have default-conflict methods appended to them.";
7739 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7740 << miranda_methods_.size()
7741 << " default_methods=" << default_methods_.size()
7742 << " overriding_default_methods=" << overriding_default_methods_.size()
7743 << " default_conflict_methods=" << default_conflict_methods_.size()
7744 << " overriding_default_conflict_methods="
7745 << overriding_default_conflict_methods_.size();
7746 }
7747
7748 ClassLinker* class_linker_;
7749 Handle<mirror::Class> klass_;
7750 size_t method_alignment_;
7751 size_t method_size_;
7752 Thread* const self_;
7753
7754 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7755 // the virtual methods array.
7756 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7757 // during cross compilation.
7758 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7759 ArenaStack stack_;
7760 ScopedArenaAllocator allocator_;
7761
7762 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7763 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7764 ScopedArenaVector<ArtMethod*> miranda_methods_;
7765 ScopedArenaVector<ArtMethod*> default_methods_;
7766 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7767
7768 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7769};
7770
7771ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7772 ArtMethod* interface_method,
7773 MethodNameAndSignatureComparator& interface_name_comparator,
7774 ArtMethod* vtable_impl) {
7775 ArtMethod* current_method = nullptr;
7776 switch (class_linker_->FindDefaultMethodImplementation(self_,
7777 interface_method,
7778 klass_,
7779 /*out*/&current_method)) {
7780 case DefaultMethodSearchResult::kDefaultConflict: {
7781 // Default method conflict.
7782 DCHECK(current_method == nullptr);
7783 ArtMethod* default_conflict_method = nullptr;
7784 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7785 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7786 default_conflict_method = vtable_impl;
7787 } else {
7788 // See if we already have a conflict method for this method.
7789 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7790 interface_name_comparator,
7791 default_conflict_methods_,
7792 overriding_default_conflict_methods_);
7793 if (LIKELY(preexisting_conflict != nullptr)) {
7794 // We already have another conflict we can reuse.
7795 default_conflict_method = preexisting_conflict;
7796 } else {
7797 // Note that we do this even if we are an interface since we need to create this and
7798 // cannot reuse another classes.
7799 // Create a new conflict method for this to use.
7800 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7801 new(default_conflict_method) ArtMethod(interface_method,
7802 class_linker_->GetImagePointerSize());
7803 if (vtable_impl == nullptr) {
7804 // Save the conflict method. We need to add it to the vtable.
7805 default_conflict_methods_.push_back(default_conflict_method);
7806 } else {
7807 // Save the conflict method but it is already in the vtable.
7808 overriding_default_conflict_methods_.push_back(default_conflict_method);
7809 }
7810 }
7811 }
7812 current_method = default_conflict_method;
7813 break;
7814 } // case kDefaultConflict
7815 case DefaultMethodSearchResult::kDefaultFound: {
7816 DCHECK(current_method != nullptr);
7817 // Found a default method.
7818 if (vtable_impl != nullptr &&
7819 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7820 // We found a default method but it was the same one we already have from our
7821 // superclass. Don't bother adding it to our vtable again.
7822 current_method = vtable_impl;
7823 } else if (LIKELY(FillTables())) {
7824 // Interfaces don't need to copy default methods since they don't have vtables.
7825 // Only record this default method if it is new to save space.
7826 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7827 // would make lookup for interface super much faster. (We would only need to scan
7828 // the iftable to find if there is a NSME or AME.)
7829 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7830 default_methods_,
7831 overriding_default_methods_);
7832 if (old == nullptr) {
7833 // We found a default method implementation and there were no conflicts.
7834 if (vtable_impl == nullptr) {
7835 // Save the default method. We need to add it to the vtable.
7836 default_methods_.push_back(current_method);
7837 } else {
7838 // Save the default method but it is already in the vtable.
7839 overriding_default_methods_.push_back(current_method);
7840 }
7841 } else {
7842 CHECK(old == current_method) << "Multiple default implementations selected!";
7843 }
7844 }
7845 break;
7846 } // case kDefaultFound
7847 case DefaultMethodSearchResult::kAbstractFound: {
7848 DCHECK(current_method == nullptr);
7849 // Abstract method masks all defaults.
7850 if (vtable_impl != nullptr &&
7851 vtable_impl->IsAbstract() &&
7852 !vtable_impl->IsDefaultConflicting()) {
7853 // We need to make this an abstract method but the version in the vtable already is so
7854 // don't do anything.
7855 current_method = vtable_impl;
7856 }
7857 break;
7858 } // case kAbstractFound
7859 }
7860 return current_method;
7861}
7862
7863ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7864 ArtMethod* interface_method,
7865 MethodNameAndSignatureComparator& interface_name_comparator) {
7866 // Find out if there is already a miranda method we can use.
7867 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7868 miranda_methods_);
7869 if (miranda_method == nullptr) {
7870 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7871 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7872 CHECK(miranda_method != nullptr);
7873 // Point the interface table at a phantom slot.
7874 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7875 miranda_methods_.push_back(miranda_method);
7876 }
7877 return miranda_method;
7878}
7879
7880void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7881 LogNewVirtuals();
7882
7883 const size_t old_method_count = klass_->NumMethods();
7884 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7885 DCHECK_NE(old_method_count, new_method_count);
7886
7887 // Attempt to realloc to save RAM if possible.
7888 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7889 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7890 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7891 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7892 // CopyFrom has internal read barriers.
7893 //
7894 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7895 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7896 method_size_,
7897 method_alignment_);
7898 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7899 method_size_,
7900 method_alignment_);
7901 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7902 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007903 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007904 self_, old_methods, old_methods_ptr_size, new_size));
7905 CHECK(methods != nullptr); // Native allocation failure aborts.
7906
7907 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7908 if (methods != old_methods) {
7909 // Maps from heap allocated miranda method to linear alloc miranda method.
7910 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7911 // Copy over the old methods.
7912 for (auto& m : klass_->GetMethods(pointer_size)) {
7913 move_table_.emplace(&m, &*out);
7914 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7915 // barriers when it copies.
7916 out->CopyFrom(&m, pointer_size);
7917 ++out;
7918 }
7919 }
7920 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7921 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7922 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007923 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7924 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007925 ArtMethod& new_method = *out;
7926 new_method.CopyFrom(mir_method, pointer_size);
Vladimir Markode0d0de2021-03-18 14:12:35 +00007927 uint32_t access_flags = new_method.GetAccessFlags();
7928 DCHECK_EQ(access_flags & kAccIntrinsic, 0u) << "Miranda method should not be an intrinsic!";
7929 DCHECK_EQ(access_flags & kAccDefault, 0u) << "Miranda method should not be a default method!";
7930 DCHECK_NE(access_flags & kAccAbstract, 0u) << "Miranda method should be abstract!";
7931 new_method.SetAccessFlags(access_flags | kAccCopied);
Vladimir Marko921094a2017-01-12 18:37:06 +00007932 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007933 // Update the entry in the method array, as the array will be used for future lookups,
7934 // where thread suspension is allowed.
7935 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7936 // would not see them.
7937 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007938 ++out;
7939 }
7940 // We need to copy the default methods into our own method table since the runtime requires that
7941 // every method on a class's vtable be in that respective class's virtual method table.
7942 // NOTE This means that two classes might have the same implementation of a method from the same
7943 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7944 // default method found on a class with one found on the declaring interface directly and must
7945 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007946 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7947 &overriding_default_methods_}) {
7948 for (size_t i = 0; i < methods_vec->size(); ++i) {
7949 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007950 ArtMethod& new_method = *out;
7951 new_method.CopyFrom(def_method, pointer_size);
7952 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7953 // verified yet it shouldn't have methods that are skipping access checks.
7954 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7955 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007956 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007957 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7958 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7959 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7960 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007961 // Update the entry in the method array, as the array will be used for future lookups,
7962 // where thread suspension is allowed.
7963 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7964 // would not see them.
7965 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007966 ++out;
7967 }
7968 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007969 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7970 &overriding_default_conflict_methods_}) {
7971 for (size_t i = 0; i < methods_vec->size(); ++i) {
7972 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007973 ArtMethod& new_method = *out;
7974 new_method.CopyFrom(conf_method, pointer_size);
7975 // This is a type of default method (there are default method impls, just a conflict) so
Vladimir Markode0d0de2021-03-18 14:12:35 +00007976 // mark this as a default. We use the `kAccAbstract` flag to distinguish it from invokable
7977 // copied default method without using a separate access flag but the default conflicting
7978 // method is technically not abstract and ArtMethod::IsAbstract() shall return false.
7979 // Also clear the kAccSkipAccessChecks bit since this class hasn't been verified yet it
7980 // shouldn't have methods that are skipping access checks. Also clear potential
7981 // kAccSingleImplementation to avoid CHA trying to inline the default method.
7982 uint32_t access_flags = new_method.GetAccessFlags();
7983 DCHECK_EQ(access_flags & kAccNative, 0u);
7984 DCHECK_EQ(access_flags & kAccIntrinsic, 0u);
7985 constexpr uint32_t kSetFlags = kAccDefault | kAccAbstract | kAccCopied;
7986 constexpr uint32_t kMaskFlags = ~(kAccSkipAccessChecks | kAccSingleImplementation);
7987 new_method.SetAccessFlags((access_flags | kSetFlags) & kMaskFlags);
Vladimir Marko921094a2017-01-12 18:37:06 +00007988 DCHECK(new_method.IsDefaultConflicting());
Vladimir Markode0d0de2021-03-18 14:12:35 +00007989 DCHECK(!new_method.IsAbstract());
Vladimir Marko921094a2017-01-12 18:37:06 +00007990 // The actual method might or might not be marked abstract since we just copied it from a
7991 // (possibly default) interface method. We need to set it entry point to be the bridge so
7992 // that the compiler will not invoke the implementation of whatever method we copied from.
7993 EnsureThrowsInvocationError(class_linker_, &new_method);
7994 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007995 // Update the entry in the method array, as the array will be used for future lookups,
7996 // where thread suspension is allowed.
7997 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7998 // would not see them.
7999 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008000 ++out;
8001 }
8002 }
8003 methods->SetSize(new_method_count);
8004 class_linker_->UpdateClassMethods(klass_.Get(), methods);
8005}
8006
8007ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00008008 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01008009 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008010 // Update the vtable to the new method structures. We can skip this for interfaces since they
8011 // do not have vtables.
8012 const size_t old_vtable_count = old_vtable->GetLength();
8013 const size_t new_vtable_count = old_vtable_count +
8014 miranda_methods_.size() +
8015 default_methods_.size() +
8016 default_conflict_methods_.size();
8017
Vladimir Marko3068d582019-05-28 16:39:29 +01008018 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
8019 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00008020 if (UNLIKELY(vtable == nullptr)) {
8021 self_->AssertPendingOOMException();
8022 return nullptr;
8023 }
8024
8025 size_t vtable_pos = old_vtable_count;
8026 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8027 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8028 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8029 default_conflict_methods_,
8030 miranda_methods_}) {
8031 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008032 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008033 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8034 // fields are references into the dex file the method was defined in. Since the ArtMethod
8035 // does not store that information it uses declaring_class_->dex_cache_.
8036 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8037 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8038 ++vtable_pos;
8039 }
8040 }
8041 DCHECK_EQ(vtable_pos, new_vtable_count);
8042
8043 // Update old vtable methods. We use the default_translations map to figure out what each
8044 // vtable entry should be updated to, if they need to be at all.
8045 for (size_t i = 0; i < old_vtable_count; ++i) {
8046 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8047 // Try and find what we need to change this method to.
8048 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008049 if (translation_it != default_translations.end()) {
8050 if (translation_it->second.IsInConflict()) {
8051 // Find which conflict method we are to use for this method.
8052 MethodNameAndSignatureComparator old_method_comparator(
8053 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8054 // We only need to look through overriding_default_conflict_methods since this is an
8055 // overridden method we are fixing up here.
8056 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8057 old_method_comparator, overriding_default_conflict_methods_);
8058 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8059 translated_method = new_conflict_method;
8060 } else if (translation_it->second.IsAbstract()) {
8061 // Find which miranda method we are to use for this method.
8062 MethodNameAndSignatureComparator old_method_comparator(
8063 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8064 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8065 miranda_methods_);
8066 DCHECK(miranda_method != nullptr);
8067 translated_method = miranda_method;
8068 } else {
8069 // Normal default method (changed from an older default or abstract interface method).
8070 DCHECK(translation_it->second.IsTranslation());
8071 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008072 auto it = move_table_.find(translated_method);
8073 DCHECK(it != move_table_.end());
8074 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008075 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008076 } else {
8077 auto it = move_table_.find(translated_method);
8078 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008079 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008080
8081 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008082 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008083 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008084 if (kIsDebugBuild) {
8085 auto* methods = klass_->GetMethodsPtr();
8086 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008087 reinterpret_cast<uintptr_t>(translated_method));
8088 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008089 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8090 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008091 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008092 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008093 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008094 }
8095 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008096 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008097 return vtable;
8098}
8099
8100void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8101 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8102 const size_t ifcount = klass_->GetIfTableCount();
8103 // Go fix up all the stale iftable pointers.
8104 for (size_t i = 0; i < ifcount; ++i) {
8105 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008106 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8107 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008108 DCHECK(m != nullptr) << klass_->PrettyClass();
8109 auto it = move_table_.find(m);
8110 if (it != move_table_.end()) {
8111 auto* new_m = it->second;
8112 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8113 method_array->SetElementPtrSize(j, new_m, pointer_size);
8114 }
8115 }
8116 }
8117}
8118
8119void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8120 // Fix up IMT next.
8121 for (size_t i = 0; i < ImTable::kSize; ++i) {
8122 auto it = move_table_.find(out_imt[i]);
8123 if (it != move_table_.end()) {
8124 out_imt[i] = it->second;
8125 }
8126 }
8127}
8128
Alex Light705ad492015-09-21 11:36:30 -07008129// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008130bool ClassLinker::LinkInterfaceMethods(
8131 Thread* self,
8132 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00008133 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008134 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008135 ArtMethod** out_imt) {
8136 StackHandleScope<3> hs(self);
8137 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008138
8139 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008140 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008141 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008142 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008143 const size_t ifcount = klass->GetIfTableCount();
8144
Vladimir Marko921094a2017-01-12 18:37:06 +00008145 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008146
8147 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8148 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008149 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008150 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008151 const bool extend_super_iftable = has_superclass;
8152 if (has_superclass && fill_tables) {
8153 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008154 unimplemented_method,
8155 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008156 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008157 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008158 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008159 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8160 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008161 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008162 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8163 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008164 }
8165 }
8166
Vladimir Marko921094a2017-01-12 18:37:06 +00008167 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8168
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008169 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008170 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008171 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8172 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8173 // they will already be null. This has the additional benefit that the declarer of a miranda
8174 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008175 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008176 --i;
Alex Light9139e002015-10-09 15:59:48 -07008177 DCHECK_LT(i, ifcount);
8178
Alex Light705ad492015-09-21 11:36:30 -07008179 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008180 if (num_methods > 0) {
8181 StackHandleScope<2> hs2(self);
8182 const bool is_super = i < super_ifcount;
8183 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008184 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8185 // conflict methods. Just set this as nullptr in those cases.
8186 Handle<mirror::PointerArray> method_array(fill_tables
8187 ? hs2.NewHandle(iftable->GetMethodArray(i))
8188 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008189
Alex Lighte64300b2015-12-15 15:02:47 -08008190 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008191 ScopedNullHandle<mirror::PointerArray> null_handle;
8192 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008193 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008194
Alex Light9139e002015-10-09 15:59:48 -07008195 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8196 // and confusing. Default methods should always look through all the superclasses
8197 // because they are the last choice of an implementation. We get around this by looking
8198 // at the super-classes iftable methods (copied into method_array previously) when we are
8199 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008200 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008201 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008202 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008203 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008204 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008205 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008206 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008207 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008208 // For a new interface, however, we need the whole vtable in case a new
8209 // interface method is implemented in the whole superclass.
8210 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008211 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008212 input_vtable_array = vtable;
8213 input_array_length = input_vtable_array->GetLength();
8214 }
Alex Lighte64300b2015-12-15 15:02:47 -08008215
Alex Lighteb7c1442015-08-31 13:17:42 -07008216 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008217 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008218 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008219 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008220 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008221 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008222 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008223 // For each method listed in the interface's method list, find the
8224 // matching method in our class's method list. We want to favor the
8225 // subclass over the superclass, which just requires walking
8226 // back from the end of the vtable. (This only matters if the
8227 // superclass defines a private method and this class redefines
8228 // it -- otherwise it would use the same vtable slot. In .dex files
8229 // those don't end up in the virtual method table, so it shouldn't
8230 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008231 //
8232 // To find defaults we need to do the same but also go over interfaces.
8233 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008234 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008235 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008236 ArtMethod* vtable_method = using_virtuals ?
8237 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008238 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8239 ArtMethod* vtable_method_for_name_comparison =
8240 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008241 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008242 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008243 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008244 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008245 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8246 // allocations.
8247 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008248 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008249 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008250 vtable_method->PrettyMethod().c_str(),
8251 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008252 return false;
Alex Light9139e002015-10-09 15:59:48 -07008253 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008254 // We might have a newer, better, default method for this, so we just skip it. If we
8255 // are still using this we will select it again when scanning for default methods. To
8256 // obviate the need to copy the method again we will make a note that we already found
8257 // a default here.
8258 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008259 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008260 break;
8261 } else {
8262 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008263 if (LIKELY(fill_tables)) {
8264 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8265 // Place method in imt if entry is empty, place conflict otherwise.
8266 SetIMTRef(unimplemented_method,
8267 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008268 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008269 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008270 /*out*/imt_ptr);
8271 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008272 break;
8273 }
8274 }
Alex Light9139e002015-10-09 15:59:48 -07008275 }
8276 // Continue on to the next method if we are done.
8277 if (LIKELY(found_impl)) {
8278 continue;
8279 } else if (LIKELY(super_interface)) {
8280 // Don't look for a default implementation when the super-method is implemented directly
8281 // by the class.
8282 //
8283 // See if we can use the superclasses method and skip searching everything else.
8284 // Note: !found_impl && super_interface
8285 CHECK(extend_super_iftable);
8286 // If this is a super_interface method it is possible we shouldn't override it because a
8287 // superclass could have implemented it directly. We get the method the superclass used
8288 // to implement this to know if we can override it with a default method. Doing this is
8289 // safe since we know that the super_iftable is filled in so we can simply pull it from
8290 // there. We don't bother if this is not a super-classes interface since in that case we
8291 // have scanned the entire vtable anyway and would have found it.
8292 // TODO This is rather dirty but it is faster than searching through the entire vtable
8293 // every time.
8294 ArtMethod* supers_method =
8295 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8296 DCHECK(supers_method != nullptr);
8297 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008298 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008299 // The method is not overridable by a default method (i.e. it is directly implemented
8300 // in some class). Therefore move onto the next interface method.
8301 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008302 } else {
8303 // If the super-classes method is override-able by a default method we need to keep
8304 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8305 // 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 -07008306 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8307 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8308 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008309 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008310 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8311 << " and not 'nullptr' or "
8312 << supers_method->PrettyMethod()
8313 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008314 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008315 }
8316 }
8317 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008318 ArtMethod* current_method = helper.FindMethod(interface_method,
8319 interface_name_comparator,
8320 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008321 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008322 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008323 // We could not find an implementation for this method and since it is a brand new
8324 // interface we searched the entire vtable (and all default methods) for an
8325 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008326 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8327 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008328 }
8329
8330 if (current_method != nullptr) {
8331 // We found a default method implementation. Record it in the iftable and IMT.
8332 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8333 SetIMTRef(unimplemented_method,
8334 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008335 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008336 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008337 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008338 }
8339 }
Alex Light705ad492015-09-21 11:36:30 -07008340 } // For each method in interface end.
8341 } // if (num_methods > 0)
8342 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008343 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008344 if (helper.HasNewVirtuals()) {
8345 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8346 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8347 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8348
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008349 // 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 -07008350 // suspension assert.
8351 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008352
Alex Light705ad492015-09-21 11:36:30 -07008353 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008354 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008355 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008356 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008357 return false;
8358 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008359 helper.UpdateIfTable(iftable);
8360 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008361 }
Alex Light705ad492015-09-21 11:36:30 -07008362
Vladimir Marko921094a2017-01-12 18:37:06 +00008363 helper.CheckNoStaleMethodsInDexCache();
8364 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008365 } else {
8366 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008367 }
Alex Light705ad492015-09-21 11:36:30 -07008368 if (kIsDebugBuild && !is_interface) {
Orion Hodson5880c772020-07-28 20:12:08 +01008369 CheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008370 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008371 return true;
8372}
8373
Vladimir Marko42bee502021-01-28 14:58:35 +00008374class ClassLinker::LinkFieldsHelper {
8375 public:
8376 static bool LinkFields(ClassLinker* class_linker,
8377 Thread* self,
8378 Handle<mirror::Class> klass,
8379 bool is_static,
8380 size_t* class_size)
8381 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008382
Vladimir Marko42bee502021-01-28 14:58:35 +00008383 private:
8384 enum class FieldTypeOrder : uint16_t;
8385 class FieldGaps;
8386
8387 struct FieldTypeOrderAndIndex {
8388 FieldTypeOrder field_type_order;
8389 uint16_t field_index;
8390 };
8391
8392 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8393
8394 template <size_t kSize>
8395 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8396 REQUIRES_SHARED(Locks::mutator_lock_);
8397};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008398
Vladimir Markoc7993d52021-01-27 15:20:56 +00008399// We use the following order of field types for assigning offsets.
8400// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008401enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008402 kReference = 0u,
8403 kLong,
8404 kDouble,
8405 kInt,
8406 kFloat,
8407 kChar,
8408 kShort,
8409 kBoolean,
8410 kByte,
8411
8412 kLast64BitType = kDouble,
8413 kLast32BitType = kFloat,
8414 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008415};
8416
Vladimir Markoc7993d52021-01-27 15:20:56 +00008417ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008418ClassLinker::LinkFieldsHelper::FieldTypeOrder
8419ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008420 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008421 case 'J':
8422 return FieldTypeOrder::kLong;
8423 case 'D':
8424 return FieldTypeOrder::kDouble;
8425 case 'I':
8426 return FieldTypeOrder::kInt;
8427 case 'F':
8428 return FieldTypeOrder::kFloat;
8429 case 'C':
8430 return FieldTypeOrder::kChar;
8431 case 'S':
8432 return FieldTypeOrder::kShort;
8433 case 'Z':
8434 return FieldTypeOrder::kBoolean;
8435 case 'B':
8436 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008437 default:
8438 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8439 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008440 }
8441}
8442
8443// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008444class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008445 public:
8446 template <uint32_t kSize>
8447 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8448 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8449 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8450 uint32_t gap_start = field_offset.Uint32Value();
8451 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8452 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8453 }
8454 return field_offset;
8455 }
8456
8457 template <uint32_t kSize>
8458 bool HasGap() const {
8459 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8460 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8461 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8462 gap4_offset_ != kNoOffset;
8463 }
8464
8465 template <uint32_t kSize>
8466 MemberOffset ReleaseGap() {
8467 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8468 uint32_t result;
8469 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8470 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8471 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8472 result = gap1_offset_;
8473 gap1_offset_ = kNoOffset;
8474 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8475 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8476 result = gap2_offset_;
8477 gap2_offset_ = kNoOffset;
8478 if (kSize < 2u) {
8479 AddGaps<1u>(result + kSize, result + 2u);
8480 }
8481 } else {
8482 DCHECK_NE(gap4_offset_, kNoOffset);
8483 result = gap4_offset_;
8484 gap4_offset_ = kNoOffset;
8485 if (kSize < 4u) {
8486 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8487 }
8488 }
8489 return MemberOffset(result);
8490 }
8491
8492 private:
8493 template <uint32_t kGapsToCheck>
8494 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8495 if ((kGapsToCheck & 1u) != 0u) {
8496 DCHECK_LT(gap_start, gap_end);
8497 DCHECK_ALIGNED(gap_end, 2u);
8498 if ((gap_start & 1u) != 0u) {
8499 DCHECK_EQ(gap1_offset_, kNoOffset);
8500 gap1_offset_ = gap_start;
8501 gap_start += 1u;
8502 if (kGapsToCheck == 1u || gap_start == gap_end) {
8503 DCHECK_EQ(gap_start, gap_end);
8504 return;
8505 }
8506 }
8507 }
8508
8509 if ((kGapsToCheck & 2u) != 0u) {
8510 DCHECK_LT(gap_start, gap_end);
8511 DCHECK_ALIGNED(gap_start, 2u);
8512 DCHECK_ALIGNED(gap_end, 4u);
8513 if ((gap_start & 2u) != 0u) {
8514 DCHECK_EQ(gap2_offset_, kNoOffset);
8515 gap2_offset_ = gap_start;
8516 gap_start += 2u;
8517 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8518 DCHECK_EQ(gap_start, gap_end);
8519 return;
8520 }
8521 }
8522 }
8523
8524 if ((kGapsToCheck & 4u) != 0u) {
8525 DCHECK_LT(gap_start, gap_end);
8526 DCHECK_ALIGNED(gap_start, 4u);
8527 DCHECK_ALIGNED(gap_end, 8u);
8528 DCHECK_EQ(gap_start + 4u, gap_end);
8529 DCHECK_EQ(gap4_offset_, kNoOffset);
8530 gap4_offset_ = gap_start;
8531 return;
8532 }
8533
8534 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8535 << " after checking " << kGapsToCheck;
8536 }
8537
8538 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8539
8540 uint32_t gap4_offset_ = kNoOffset;
8541 uint32_t gap2_offset_ = kNoOffset;
8542 uint32_t gap1_offset_ = kNoOffset;
8543};
8544
8545template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008546ALWAYS_INLINE
8547MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8548 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008549 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8550 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8551 field->SetOffset(field_offset);
8552 return MemberOffset(field_offset.Uint32Value() + kSize);
8553}
8554
Vladimir Marko42bee502021-01-28 14:58:35 +00008555bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8556 Thread* self,
8557 Handle<mirror::Class> klass,
8558 bool is_static,
8559 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008560 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008561 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008562 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8563 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008564
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008565 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008566 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008567 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008568 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8569 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008570 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008571 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008572 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008573 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008574 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008575 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008576 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008577 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008578
David Sehr709b0702016-10-13 09:12:37 -07008579 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008580
Brian Carlstromdbc05252011-09-09 01:59:59 -07008581 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008582 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008583 //
8584 // The overall sort order order is:
8585 // 1) All object reference fields, sorted alphabetically.
8586 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8587 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8588 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8589 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8590 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8591 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8592 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8593 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8594 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008595 // (References are first to increase the chance of reference visiting
8596 // being able to take a fast path using a bitmap of references at the
8597 // start of the object, see `Class::reference_instance_offsets_`.)
8598 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008599 // Once the fields are sorted in this order we will attempt to fill any gaps
8600 // that might be present in the memory layout of the structure.
8601 // Note that we shall not fill gaps between the superclass fields.
8602
8603 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008604 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008605 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008606 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8607 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8608 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8609 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008610 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008611 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008612 } else {
8613 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008614 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008615 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008616 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008617 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008618 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008619 for (size_t i = 0; i != num_fields; ++i) {
8620 ArtField* field = &fields->At(i);
8621 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008622 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8623 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008624 // Insert references to the start, other fields to the end.
8625 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008626 if (field_type_order == FieldTypeOrder::kReference) {
8627 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008628 ++num_reference_fields;
8629 } else {
8630 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008631 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008632 }
8633 }
8634 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008635
Vladimir Marko42bee502021-01-28 14:58:35 +00008636 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008637 DCHECK(std::is_sorted(
8638 sorted_fields.begin(),
8639 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008640 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8641 ArtField* lhs_field = &fields->At(lhs.field_index);
8642 ArtField* rhs_field = &fields->At(rhs.field_index);
8643 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8644 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8645 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8646 lhs.field_index < rhs.field_index);
8647 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008648 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008649 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008650 DCHECK(std::is_sorted(
8651 sorted_fields.begin() + primitive_fields_start,
8652 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008653 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8654 ArtField* lhs_field = &fields->At(lhs.field_index);
8655 ArtField* rhs_field = &fields->At(rhs.field_index);
8656 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8657 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8658 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8659 lhs.field_index > rhs.field_index);
8660 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008661 }));
8662 // Sort the primitive fields by the field type order, then field index.
8663 std::sort(sorted_fields.begin() + primitive_fields_start,
8664 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008665 [](const auto& lhs, const auto& rhs) {
8666 if (lhs.field_type_order != rhs.field_type_order) {
8667 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008668 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008669 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008670 }
8671 });
8672 // Primitive fields are now sorted by field size (descending), then type, then field index.
8673 DCHECK(std::is_sorted(
8674 sorted_fields.begin() + primitive_fields_start,
8675 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008676 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8677 ArtField* lhs_field = &fields->At(lhs.field_index);
8678 ArtField* rhs_field = &fields->At(rhs.field_index);
8679 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008680 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008681 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008682 CHECK_NE(rhs_type, Primitive::kPrimNot);
8683 if (lhs_type != rhs_type) {
8684 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8685 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8686 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8687 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008688 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008689 }
8690 }));
8691
8692 // Process reference fields.
8693 FieldGaps field_gaps;
8694 size_t index = 0u;
8695 if (num_reference_fields != 0u) {
8696 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8697 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8698 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008699 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008700 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008701 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008702 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008703 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008704 if (index != num_fields &&
8705 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008706 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008707 while (index != num_fields &&
8708 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8709 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008710 field_offset = AssignFieldOffset<8u>(field, field_offset);
8711 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008712 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008713 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008714 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008715 if (index != num_fields &&
8716 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008717 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8718 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008719 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008720 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8721 ++index;
8722 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8723 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008724 while (index != num_fields &&
8725 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8726 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008727 field_offset = AssignFieldOffset<4u>(field, field_offset);
8728 ++index;
8729 }
8730 }
8731 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008732 if (index != num_fields &&
8733 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008734 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8735 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008736 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008737 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008738 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008739 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8740 ++index;
8741 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008742 while (index != num_fields &&
8743 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8744 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008745 field_offset = AssignFieldOffset<2u>(field, field_offset);
8746 ++index;
8747 }
8748 }
8749 // Process 8-bit fields.
8750 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008751 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008752 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8753 }
8754 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008755 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008756 field_offset = AssignFieldOffset<1u>(field, field_offset);
8757 }
8758
Ian Rogers7b078e82014-09-10 14:44:24 -07008759 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008760
Elliott Hughesadb460d2011-10-05 17:02:34 -07008761 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Vladimir Marko42bee502021-01-28 14:58:35 +00008762 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8763 if (!is_static &&
8764 UNLIKELY(!class_linker->init_done_) &&
8765 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008766 // We know there are no non-reference fields in the Reference classes, and we know
8767 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008768 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008769 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008770 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008771 --num_reference_fields;
8772 }
8773
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008774 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008775 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008776 if (is_static) {
8777 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008778 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008779 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008780 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008781 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008782 if (num_reference_fields == 0 || super_class == nullptr) {
8783 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008784 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008785 if (super_class == nullptr ||
8786 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8787 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008788 }
8789 }
8790 if (kIsDebugBuild) {
8791 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8792 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008793 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008794 while (cur_super != nullptr) {
8795 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8796 cur_super = cur_super->GetSuperClass();
8797 }
8798 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008799 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008800 } else {
8801 // Check that there is at least num_reference_fields other than Object.class.
8802 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008803 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008804 }
8805 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008806 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008807 std::string temp;
8808 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8809 size_t previous_size = klass->GetObjectSize();
8810 if (previous_size != 0) {
8811 // Make sure that we didn't originally have an incorrect size.
8812 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008813 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008814 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008815 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008816 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008817
8818 if (kIsDebugBuild) {
8819 // Make sure that the fields array is ordered by name but all reference
8820 // offsets are at the beginning as far as alignment allows.
8821 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008822 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008823 : klass->GetFirstReferenceInstanceFieldOffset();
8824 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8825 num_reference_fields *
8826 sizeof(mirror::HeapReference<mirror::Object>));
8827 MemberOffset current_ref_offset = start_ref_offset;
8828 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008829 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008830 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008831 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8832 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008833 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008834 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008835 // NOTE: The field names can be the same. This is not possible in the Java language
8836 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008837 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008838 }
8839 Primitive::Type type = field->GetTypeAsPrimitiveType();
8840 bool is_primitive = type != Primitive::kPrimNot;
8841 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8842 strcmp("referent", field->GetName()) == 0) {
8843 is_primitive = true; // We lied above, so we have to expect a lie here.
8844 }
8845 MemberOffset offset = field->GetOffsetDuringLinking();
8846 if (is_primitive) {
8847 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8848 // Shuffled before references.
8849 size_t type_size = Primitive::ComponentSize(type);
8850 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8851 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8852 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8853 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8854 }
8855 } else {
8856 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8857 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8858 sizeof(mirror::HeapReference<mirror::Object>));
8859 }
8860 }
8861 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8862 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008863 return true;
8864}
8865
Vladimir Marko42bee502021-01-28 14:58:35 +00008866bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8867 CHECK(klass != nullptr);
8868 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8869}
8870
8871bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8872 CHECK(klass != nullptr);
8873 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8874}
8875
Vladimir Marko76649e82014-11-10 18:32:59 +00008876// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008877void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008878 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008879 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008880 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008881 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008882 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008883 // Compute reference offsets unless our superclass overflowed.
8884 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8885 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008886 if (num_reference_fields != 0u) {
8887 // All of the fields that contain object references are guaranteed be grouped in memory
8888 // starting at an appropriately aligned address after super class object data.
8889 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8890 sizeof(mirror::HeapReference<mirror::Object>));
8891 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008892 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008893 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008894 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008895 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008896 reference_offsets |= (0xffffffffu << start_bit) &
8897 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008898 }
8899 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008900 }
8901 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008902 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008903}
8904
Vladimir Marko18090d12018-06-01 16:53:12 +01008905ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8906 ObjPtr<mirror::DexCache> dex_cache) {
8907 StackHandleScope<1> hs(Thread::Current());
8908 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8909 return DoResolveString(string_idx, h_dex_cache);
8910}
8911
8912ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8913 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008914 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008915 uint32_t utf16_length;
8916 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008917 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008918 if (string != nullptr) {
8919 dex_cache->SetResolvedString(string_idx, string);
8920 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008921 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008922}
8923
Vladimir Marko18090d12018-06-01 16:53:12 +01008924ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8925 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008926 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008927 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008928 uint32_t utf16_length;
8929 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008930 ObjPtr<mirror::String> string =
8931 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008932 if (string != nullptr) {
8933 dex_cache->SetResolvedString(string_idx, string);
8934 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008935 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008936}
8937
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008938ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008939 ObjPtr<mirror::Class> referrer) {
8940 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8941}
8942
8943ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008944 ObjPtr<mirror::DexCache> dex_cache,
8945 ObjPtr<mirror::ClassLoader> class_loader) {
8946 const DexFile& dex_file = *dex_cache->GetDexFile();
8947 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01008948 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
8949 if (type != nullptr) {
8950 DCHECK(type->IsResolved());
8951 dex_cache->SetResolvedType(type_idx, type);
8952 }
8953 return type;
8954}
8955
8956ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
8957 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008958 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8959 ObjPtr<mirror::Class> type = nullptr;
8960 if (descriptor[1] == '\0') {
8961 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8962 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008963 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008964 } else {
8965 Thread* const self = Thread::Current();
8966 DCHECK(self != nullptr);
8967 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8968 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008969 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008970 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01008971 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008972}
8973
Andreas Gampeb0625e02019-05-01 12:43:31 -07008974template <typename RefType>
8975ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008976 StackHandleScope<2> hs(Thread::Current());
8977 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8978 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8979 return DoResolveType(type_idx, dex_cache, class_loader);
8980}
8981
Andreas Gampe4835d212018-11-21 14:55:10 -08008982// Instantiate the above.
8983template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8984 ArtField* referrer);
8985template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8986 ArtMethod* referrer);
8987template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8988 ObjPtr<mirror::Class> referrer);
8989
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008990ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008991 Handle<mirror::DexCache> dex_cache,
8992 Handle<mirror::ClassLoader> class_loader) {
8993 Thread* self = Thread::Current();
8994 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8995 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8996 if (resolved != nullptr) {
8997 // TODO: we used to throw here if resolved's class loader was not the
8998 // boot class loader. This was to permit different classes with the
8999 // same name to be loaded simultaneously by different loaders
9000 dex_cache->SetResolvedType(type_idx, resolved);
9001 } else {
9002 CHECK(self->IsExceptionPending())
9003 << "Expected pending exception for failed resolution of: " << descriptor;
9004 // Convert a ClassNotFoundException to a NoClassDefFoundError.
9005 StackHandleScope<1> hs(self);
9006 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009007 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009008 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
9009 self->ClearException();
9010 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
9011 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009012 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009013 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00009014 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07009015 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00009016 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009017}
9018
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009019ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
9020 ObjPtr<mirror::DexCache> dex_cache,
9021 ObjPtr<mirror::ClassLoader> class_loader,
9022 uint32_t method_idx) {
9023 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
9024 // functions can optimize the search if the dex_cache is the same as the DexCache
9025 // of the class, with fall-back to name and signature search otherwise.
9026 ArtMethod* resolved = nullptr;
9027 if (klass->IsInterface()) {
9028 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9029 } else {
9030 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9031 }
9032 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009033 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009034 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
9035 // access, as we'll be looking if the method can be accessed through an
9036 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01009037 hiddenapi::ShouldDenyAccessToMember(resolved,
9038 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009039 hiddenapi::AccessMethod::kNone)) {
9040 // The resolved method that we have found cannot be accessed due to
9041 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
9042 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00009043 // part of the SDK.
9044 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009045 if (itf_method == nullptr) {
9046 // No interface method. Call ShouldDenyAccessToMember again but this time
9047 // with AccessMethod::kLinking to ensure that an appropriate warning is
9048 // logged.
9049 hiddenapi::ShouldDenyAccessToMember(resolved,
9050 hiddenapi::AccessContext(class_loader, dex_cache),
9051 hiddenapi::AccessMethod::kLinking);
9052 resolved = nullptr;
9053 } else {
9054 // We found an interface method that is accessible, continue with the resolved method.
9055 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009056 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009057 if (resolved != nullptr) {
9058 // In case of jmvti, the dex file gets verified before being registered, so first
9059 // check if it's registered before checking class tables.
9060 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009061 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
9062 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009063 << "DexFile referrer: " << dex_file.GetLocation()
9064 << " ClassLoader: " << DescribeLoaders(class_loader, "");
9065 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00009066 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009067 // Disable the following invariant check as the verifier breaks it. b/73760543
9068 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
9069 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
9070 // << "Method: " << resolved->PrettyMethod() << ", "
9071 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
9072 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009073 }
9074 return resolved;
9075}
9076
David Brazdil4525e0b2018-04-05 16:57:32 +01009077// Returns true if `method` is either null or hidden.
9078// Does not print any warnings if it is hidden.
9079static bool CheckNoSuchMethod(ArtMethod* method,
9080 ObjPtr<mirror::DexCache> dex_cache,
9081 ObjPtr<mirror::ClassLoader> class_loader)
9082 REQUIRES_SHARED(Locks::mutator_lock_) {
9083 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009084 hiddenapi::ShouldDenyAccessToMember(method,
9085 hiddenapi::AccessContext(class_loader, dex_cache),
9086 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009087}
9088
9089ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9090 ObjPtr<mirror::DexCache> dex_cache,
9091 ObjPtr<mirror::ClassLoader> class_loader,
9092 uint32_t method_idx) {
9093 if (klass->IsInterface()) {
9094 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9095 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9096 } else {
9097 // If there was an interface method with the same signature, we would have
9098 // found it in the "copied" methods. Only DCHECK that the interface method
9099 // really does not exist.
9100 if (kIsDebugBuild) {
9101 ArtMethod* method =
9102 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9103 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9104 }
9105 return nullptr;
9106 }
9107}
9108
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009109template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00009110ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07009111 Handle<mirror::DexCache> dex_cache,
9112 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009113 ArtMethod* referrer,
9114 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01009115 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08009116 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01009117 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07009118 // Check for hit in the dex cache.
David Srbecky5de5efe2021-02-15 21:23:00 +00009119 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009120 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009121 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
9122 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01009123 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
9124 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07009125 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009126 return resolved;
9127 }
Vladimir Marko89011192017-12-11 13:45:05 +00009128 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009129 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009130 ObjPtr<mirror::Class> klass = nullptr;
9131 if (valid_dex_cache_method) {
9132 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
9133 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009134 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009135 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009136 // We normaly should not end up here. However the verifier currently doesn't guarantee
9137 // the invariant of having the klass in the class table. b/73760543
9138 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01009139 if (klass == nullptr) {
9140 // This can only happen if the current thread is not allowed to load
9141 // classes.
9142 DCHECK(!Thread::Current()->CanLoadClasses());
9143 DCHECK(Thread::Current()->IsExceptionPending());
9144 return nullptr;
9145 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009146 }
Vladimir Markoba118822017-06-12 15:41:56 +01009147 } else {
9148 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009149 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01009150 if (klass == nullptr) {
9151 DCHECK(Thread::Current()->IsExceptionPending());
9152 return nullptr;
9153 }
9154 }
9155
9156 // Check if the invoke type matches the class type.
9157 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009158 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01009159 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07009160 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009161 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009162 }
Vladimir Markoba118822017-06-12 15:41:56 +01009163
9164 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009165 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009166 }
Vladimir Markoba118822017-06-12 15:41:56 +01009167
9168 // Note: We can check for IllegalAccessError only if we have a referrer.
9169 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
9170 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
9171 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9172 if (!referring_class->CheckResolvedMethodAccess(methods_class,
9173 resolved,
9174 dex_cache.Get(),
9175 method_idx,
9176 type)) {
9177 DCHECK(Thread::Current()->IsExceptionPending());
9178 return nullptr;
9179 }
9180 }
9181
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009182 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01009183 if (LIKELY(resolved != nullptr) &&
9184 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
9185 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07009186 return resolved;
9187 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009188 // If we had a method, or if we can find one with another lookup type,
9189 // it's an incompatible-class-change error.
9190 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01009191 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009192 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009193 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07009194 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009195 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009196 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009197 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
9198 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01009199 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07009200 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08009201 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009202 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07009203 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009204}
9205
Vladimir Marko89011192017-12-11 13:45:05 +00009206ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009207 Handle<mirror::DexCache> dex_cache,
9208 Handle<mirror::ClassLoader> class_loader) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009209 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009210 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009211 if (resolved != nullptr) {
9212 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009213 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9214 return resolved;
9215 }
9216 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009217 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009218 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009219 if (klass == nullptr) {
9220 Thread::Current()->AssertPendingException();
9221 return nullptr;
9222 }
9223 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009224 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9225 } else {
9226 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009227 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009228 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009229 hiddenapi::ShouldDenyAccessToMember(
9230 resolved,
9231 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9232 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009233 resolved = nullptr;
9234 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009235 return resolved;
9236}
9237
Vladimir Markof44d36c2017-03-14 14:18:46 +00009238ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9239 ObjPtr<mirror::DexCache> dex_cache,
9240 ObjPtr<mirror::ClassLoader> class_loader,
9241 bool is_static) {
9242 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009243 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009244 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9245 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009246 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009247 }
9248 if (klass == nullptr) {
9249 // The class has not been resolved yet, so the field is also unresolved.
9250 return nullptr;
9251 }
9252 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009253
David Brazdil1ab0fa82018-05-04 11:28:03 +01009254 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009255}
9256
Vladimir Markoe11dd502017-12-08 14:09:45 +00009257ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009258 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009259 Handle<mirror::ClassLoader> class_loader,
9260 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009261 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00009262 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
David Srbecky5de5efe2021-02-15 21:23:00 +00009263 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009264 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009265 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009266 return resolved;
9267 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009268 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009269 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009270 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009271 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009272 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009273 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009274 }
9275
David Brazdil1ab0fa82018-05-04 11:28:03 +01009276 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009277 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009278 const char* name = dex_file.GetFieldName(field_id);
9279 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009280 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009281 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009282 return resolved;
9283}
9284
Vladimir Markoe11dd502017-12-08 14:09:45 +00009285ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009286 Handle<mirror::DexCache> dex_cache,
9287 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009288 DCHECK(dex_cache != nullptr);
David Srbecky5de5efe2021-02-15 21:23:00 +00009289 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009290 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009291 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009292 return resolved;
9293 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009294 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009295 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009296 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009297 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009298 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009299 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009300 }
9301
David Brazdil1ab0fa82018-05-04 11:28:03 +01009302 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9303 if (resolved == nullptr) {
9304 const char* name = dex_file.GetFieldName(field_id);
9305 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009306 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009307 }
9308 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009309}
9310
David Brazdil1ab0fa82018-05-04 11:28:03 +01009311ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9312 ObjPtr<mirror::DexCache> dex_cache,
9313 ObjPtr<mirror::ClassLoader> class_loader,
9314 uint32_t field_idx,
9315 bool is_static) {
9316 ArtField* resolved = nullptr;
9317 Thread* self = is_static ? Thread::Current() : nullptr;
9318 const DexFile& dex_file = *dex_cache->GetDexFile();
9319
9320 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9321 : klass->FindInstanceField(dex_cache, field_idx);
9322
9323 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009324 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009325 const char* name = dex_file.GetFieldName(field_id);
9326 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9327 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9328 : klass->FindInstanceField(name, type);
9329 }
9330
9331 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009332 hiddenapi::ShouldDenyAccessToMember(resolved,
9333 hiddenapi::AccessContext(class_loader, dex_cache),
9334 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009335 resolved = nullptr;
9336 }
9337
9338 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009339 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009340 }
9341
9342 return resolved;
9343}
9344
9345ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9346 ObjPtr<mirror::DexCache> dex_cache,
9347 ObjPtr<mirror::ClassLoader> class_loader,
9348 uint32_t field_idx) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009349 Thread* self = Thread::Current();
Vladimir Markoe300c4e2021-06-08 16:00:05 +01009350 ArtField* resolved = mirror::Class::FindField(self, klass, dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009351
9352 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009353 hiddenapi::ShouldDenyAccessToMember(resolved,
9354 hiddenapi::AccessContext(class_loader, dex_cache),
9355 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009356 resolved = nullptr;
9357 }
9358
9359 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009360 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009361 }
9362
9363 return resolved;
9364}
9365
Vladimir Markoaf940202017-12-08 15:01:18 +00009366ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9367 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009368 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009369 Handle<mirror::DexCache> dex_cache,
9370 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009371 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009372 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009373
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009374 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009375 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009376 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009377 }
9378
Narayan Kamath25352fc2016-08-03 12:46:58 +01009379 StackHandleScope<4> hs(self);
9380
9381 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009382 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009383 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009384 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009385 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009386 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009387 DCHECK(self->IsExceptionPending());
9388 return nullptr;
9389 }
9390
9391 // Then resolve the argument types.
9392 //
9393 // TODO: Is there a better way to figure out the number of method arguments
9394 // other than by looking at the shorty ?
9395 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9396
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009397 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009398 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9399 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009400 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009401 DCHECK(self->IsExceptionPending());
9402 return nullptr;
9403 }
9404
9405 DexFileParameterIterator it(dex_file, proto_id);
9406 int32_t i = 0;
9407 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9408 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009409 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009410 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009411 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009412 DCHECK(self->IsExceptionPending());
9413 return nullptr;
9414 }
9415
9416 method_params->Set(i++, param_class.Get());
9417 }
9418
9419 DCHECK(!it.HasNext());
9420
9421 Handle<mirror::MethodType> type = hs.NewHandle(
9422 mirror::MethodType::Create(self, return_type, method_params));
9423 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9424
9425 return type.Get();
9426}
9427
Vladimir Markoaf940202017-12-08 15:01:18 +00009428ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009429 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009430 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009431 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009432 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9433 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009434 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009435}
9436
Vladimir Marko5aead702019-03-27 11:00:36 +00009437ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009438 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009439 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009440 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009441 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009442 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9443 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009444 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009445 bool is_static;
9446 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009447 switch (handle_type) {
9448 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009449 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009450 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009451 is_static = true;
9452 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009453 break;
9454 }
9455 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009456 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009457 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009458 is_static = true;
9459 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009460 break;
9461 }
9462 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009463 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009464 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009465 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009466 num_params = 2;
9467 break;
9468 }
9469 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009470 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009471 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009472 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009473 num_params = 1;
9474 break;
9475 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009476 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009477 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009478 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009479 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009480 case DexFile::MethodHandleType::kInvokeInterface:
9481 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009482 }
9483
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009484 ArtField* target_field =
9485 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9486 if (LIKELY(target_field != nullptr)) {
9487 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9488 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9489 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9490 ThrowIllegalAccessErrorField(referring_class, target_field);
9491 return nullptr;
9492 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009493 if (UNLIKELY(is_put && target_field->IsFinal())) {
9494 ThrowIllegalAccessErrorField(referring_class, target_field);
9495 return nullptr;
9496 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009497 } else {
9498 DCHECK(Thread::Current()->IsExceptionPending());
9499 return nullptr;
9500 }
9501
9502 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009503 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009504 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9505 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009506 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009507 DCHECK(self->IsExceptionPending());
9508 return nullptr;
9509 }
9510
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009511 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009512 Handle<mirror::Class> return_type;
9513 switch (handle_type) {
9514 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009515 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009516 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009517 break;
9518 }
9519 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009520 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009521 break;
9522 }
9523 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009524 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009525 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009526 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009527 break;
9528 }
9529 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009530 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009531 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009532 break;
9533 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009534 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009535 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009536 case DexFile::MethodHandleType::kInvokeConstructor:
9537 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009538 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009539 UNREACHABLE();
9540 }
9541
9542 for (int32_t i = 0; i < num_params; ++i) {
9543 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9544 DCHECK(self->IsExceptionPending());
9545 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009546 }
9547 }
9548
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009549 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009550 DCHECK(self->IsExceptionPending());
9551 return nullptr;
9552 }
9553
9554 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009555 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9556 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009557 DCHECK(self->IsExceptionPending());
9558 return nullptr;
9559 }
Orion Hodson631827d2017-04-10 14:53:47 +01009560
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009561 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9562 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9563}
9564
Vladimir Marko5aead702019-03-27 11:00:36 +00009565ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009566 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009567 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009568 ArtMethod* referrer) {
9569 DexFile::MethodHandleType handle_type =
9570 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9571 mirror::MethodHandle::Kind kind;
9572 uint32_t receiver_count = 0;
9573 ArtMethod* target_method = nullptr;
9574 switch (handle_type) {
9575 case DexFile::MethodHandleType::kStaticPut:
9576 case DexFile::MethodHandleType::kStaticGet:
9577 case DexFile::MethodHandleType::kInstancePut:
9578 case DexFile::MethodHandleType::kInstanceGet:
9579 UNREACHABLE();
9580 case DexFile::MethodHandleType::kInvokeStatic: {
9581 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9582 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009583 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9584 method_handle.field_or_method_idx_,
9585 referrer,
9586 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009587 break;
9588 }
9589 case DexFile::MethodHandleType::kInvokeInstance: {
9590 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9591 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009592 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9593 method_handle.field_or_method_idx_,
9594 referrer,
9595 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009596 break;
9597 }
9598 case DexFile::MethodHandleType::kInvokeConstructor: {
9599 // Constructors are currently implemented as a transform. They
9600 // are special cased later in this method.
9601 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9602 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009603 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9604 method_handle.field_or_method_idx_,
9605 referrer,
9606 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009607 break;
9608 }
9609 case DexFile::MethodHandleType::kInvokeDirect: {
9610 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9611 receiver_count = 1;
9612 StackHandleScope<2> hs(self);
9613 // A constant method handle with type kInvokeDirect can refer to
9614 // a method that is private or to a method in a super class. To
9615 // disambiguate the two options, we resolve the method ignoring
9616 // the invocation type to determine if the method is private. We
9617 // then resolve again specifying the intended invocation type to
9618 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009619 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009620 hs.NewHandle(referrer->GetDexCache()),
9621 hs.NewHandle(referrer->GetClassLoader()));
9622 if (UNLIKELY(target_method == nullptr)) {
9623 break;
9624 }
9625
9626 if (target_method->IsPrivate()) {
9627 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009628 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9629 method_handle.field_or_method_idx_,
9630 referrer,
9631 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009632 } else {
9633 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009634 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9635 method_handle.field_or_method_idx_,
9636 referrer,
9637 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009638 if (UNLIKELY(target_method == nullptr)) {
9639 break;
9640 }
9641 // Find the method specified in the parent in referring class
9642 // so invoke-super invokes the method in the parent of the
9643 // referrer.
9644 target_method =
9645 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9646 kRuntimePointerSize);
9647 }
9648 break;
9649 }
9650 case DexFile::MethodHandleType::kInvokeInterface: {
9651 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9652 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009653 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9654 method_handle.field_or_method_idx_,
9655 referrer,
9656 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009657 break;
9658 }
Orion Hodson631827d2017-04-10 14:53:47 +01009659 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009660
9661 if (UNLIKELY(target_method == nullptr)) {
9662 DCHECK(Thread::Current()->IsExceptionPending());
9663 return nullptr;
9664 }
9665
9666 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9667 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9668 uint32_t access_flags = target_method->GetAccessFlags();
9669 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9670 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9671 return nullptr;
9672 }
9673
9674 // Calculate the number of parameters from the method shorty. We add the
9675 // receiver count (0 or 1) and deduct one for the return value.
9676 uint32_t shorty_length;
9677 target_method->GetShorty(&shorty_length);
9678 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9679
Orion Hodsonecd58562018-09-24 11:27:33 +01009680 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009681 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009682 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9683 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9684 if (method_params.Get() == nullptr) {
9685 DCHECK(self->IsExceptionPending());
9686 return nullptr;
9687 }
9688
Orion Hodsonecd58562018-09-24 11:27:33 +01009689 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009690 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009691 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009692 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009693 // Insert receiver. Use the class identified in the method handle rather than the declaring
9694 // class of the resolved method which may be super class or default interface method
9695 // (b/115964401).
9696 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9697 // receiver_class should have been resolved when resolving the target method.
9698 DCHECK(receiver_class != nullptr);
9699 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009700 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009701
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009702 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009703 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009704 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009705 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009706 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009707 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009708 if (nullptr == klass) {
9709 DCHECK(self->IsExceptionPending());
9710 return nullptr;
9711 }
9712 method_params->Set(index++, klass);
9713 it.Next();
9714 }
9715
Orion Hodsonecd58562018-09-24 11:27:33 +01009716 Handle<mirror::Class> return_type =
9717 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009718 if (UNLIKELY(return_type.IsNull())) {
9719 DCHECK(self->IsExceptionPending());
9720 return nullptr;
9721 }
9722
9723 Handle<mirror::MethodType>
9724 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9725 if (UNLIKELY(method_type.IsNull())) {
9726 DCHECK(self->IsExceptionPending());
9727 return nullptr;
9728 }
9729
9730 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9731 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9732 Handle<mirror::MethodHandlesLookup> lookup =
9733 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9734 return lookup->FindConstructor(self, constructor_class, method_type);
9735 }
9736
9737 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9738 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9739}
9740
Vladimir Markoaf940202017-12-08 15:01:18 +00009741ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9742 uint32_t method_handle_idx,
9743 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009744 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009745 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009746 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009747 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9748 case DexFile::MethodHandleType::kStaticPut:
9749 case DexFile::MethodHandleType::kStaticGet:
9750 case DexFile::MethodHandleType::kInstancePut:
9751 case DexFile::MethodHandleType::kInstanceGet:
9752 return ResolveMethodHandleForField(self, method_handle, referrer);
9753 case DexFile::MethodHandleType::kInvokeStatic:
9754 case DexFile::MethodHandleType::kInvokeInstance:
9755 case DexFile::MethodHandleType::kInvokeConstructor:
9756 case DexFile::MethodHandleType::kInvokeDirect:
9757 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009758 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009759 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009760}
9761
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009762bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9763 return (entry_point == GetQuickResolutionStub()) ||
9764 (quick_resolution_trampoline_ == entry_point);
9765}
9766
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009767bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9768 return (entry_point == GetQuickToInterpreterBridge()) ||
9769 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9770}
9771
9772bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9773 return (entry_point == GetQuickGenericJniStub()) ||
9774 (quick_generic_jni_trampoline_ == entry_point);
9775}
9776
David Sehra49e0532017-08-25 08:05:29 -07009777bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009778 return entry_point == GetJniDlsymLookupStub() ||
9779 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009780}
9781
Vladimir Markofa458ac2020-02-12 14:08:07 +00009782bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9783 return entry_point == GetJniDlsymLookupCriticalStub() ||
9784 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9785}
9786
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009787const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9788 return GetQuickGenericJniStub();
9789}
9790
Mathieu Chartiere401d142015-04-22 13:56:20 -07009791void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009792 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009793 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9794 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009795 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009796 }
9797}
9798
Alex Lightdb01a092017-04-03 15:39:55 -07009799void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9800 DCHECK(method->IsObsolete());
9801 // We cannot mess with the entrypoints of native methods because they are used to determine how
9802 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9803 if (!method->IsNative()) {
9804 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9805 }
9806}
9807
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009808void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009809 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009810 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009811 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9812 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009813 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9814 os << "Dumping registered class loaders\n";
9815 size_t class_loader_index = 0;
9816 for (const ClassLoaderData& class_loader : class_loaders_) {
9817 ObjPtr<mirror::ClassLoader> loader =
9818 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9819 if (loader != nullptr) {
9820 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9821 bool saw_one_dex_file = false;
9822 for (const DexCacheData& dex_cache : dex_caches_) {
9823 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9824 if (saw_one_dex_file) {
9825 os << ":";
9826 }
9827 saw_one_dex_file = true;
9828 os << dex_cache.dex_file->GetLocation();
9829 }
9830 }
9831 os << "]";
9832 bool found_parent = false;
9833 if (loader->GetParent() != nullptr) {
9834 size_t parent_index = 0;
9835 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9836 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9837 soa.Self()->DecodeJObject(class_loader2.weak_root));
9838 if (loader2 == loader->GetParent()) {
9839 os << ", parent #" << parent_index;
9840 found_parent = true;
9841 break;
9842 }
9843 parent_index++;
9844 }
9845 if (!found_parent) {
9846 os << ", unregistered parent of type "
9847 << loader->GetParent()->GetClass()->PrettyDescriptor();
9848 }
9849 } else {
9850 os << ", no parent";
9851 }
9852 os << "\n";
9853 }
9854 }
9855 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009856 Runtime* runtime = Runtime::Current();
9857 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9858 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009859}
9860
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009861class CountClassesVisitor : public ClassLoaderVisitor {
9862 public:
9863 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9864
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009865 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009866 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009867 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009868 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009869 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9870 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009871 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009872 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009873
9874 size_t num_zygote_classes;
9875 size_t num_non_zygote_classes;
9876};
9877
9878size_t ClassLinker::NumZygoteClasses() const {
9879 CountClassesVisitor visitor;
9880 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009881 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009882}
9883
9884size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009885 CountClassesVisitor visitor;
9886 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009887 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009888}
9889
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009890size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009891 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009892 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009893 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009894}
9895
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009896pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009897 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009898}
9899
9900pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009901 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009902}
9903
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009904void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009905 DCHECK(!init_done_);
9906
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009907 DCHECK(klass != nullptr);
9908 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009909
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009910 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009911 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009912 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9913 int32_t index = static_cast<int32_t>(class_root);
9914 DCHECK(class_roots->Get(index) == nullptr);
9915 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009916}
9917
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009918ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9919 Thread* self,
9920 const std::vector<const DexFile*>& dex_files,
9921 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009922 Handle<mirror::ClassLoader> parent_loader,
9923 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009924
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009925 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009926
Mathieu Chartierc7853442015-03-27 14:35:38 -07009927 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009928 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009929
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009930 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009931 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009932 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009933 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009934 mirror::ObjectArray<mirror::Object>::Alloc(self,
9935 dex_elements_class.Get(),
9936 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009937 Handle<mirror::Class> h_dex_element_class =
9938 hs.NewHandle(dex_elements_class->GetComponentType());
9939
Mathieu Chartierc7853442015-03-27 14:35:38 -07009940 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009941 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009942 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009943
Andreas Gampe08883de2016-11-08 13:20:52 -08009944 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009945 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009946
Andreas Gampe08883de2016-11-08 13:20:52 -08009947 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009948 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009949
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009950 // Fill the elements array.
9951 int32_t index = 0;
9952 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009953 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009954
Calin Juravle7865ac72017-06-28 11:03:12 -07009955 // CreateWellKnownClassLoader is only used by gtests and compiler.
9956 // 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 -07009957 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9958 self,
9959 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009960 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009961 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009962
Mathieu Chartier3738e982017-05-12 16:07:28 -07009963 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9964 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009965 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009966 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009967 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009968 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009969
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009970 Handle<mirror::String> h_file_name = hs2.NewHandle(
9971 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009972 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009973 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9974
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009975 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009976 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009977 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009978
9979 h_dex_elements->Set(index, h_element.Get());
9980 index++;
9981 }
9982 DCHECK_EQ(index, h_dex_elements->GetLength());
9983
9984 // Create DexPathList.
9985 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009986 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009987 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009988 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009989 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009990 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9991 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9992 // elements.
9993 {
9994 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9995 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9996 DCHECK(native_lib_dirs != nullptr);
9997 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9998 DCHECK(list_class != nullptr);
9999 {
10000 StackHandleScope<1> h_list_scope(self);
10001 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
10002 bool list_init = EnsureInitialized(self, h_list_class, true, true);
10003 DCHECK(list_init);
10004 list_class = h_list_class.Get();
10005 }
10006 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
10007 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
10008 // is fine for testing. While it violates a Java-code invariant (the elementData field is
10009 // normally never null), as long as one does not try to add elements, this will still
10010 // work.
10011 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
10012 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010013
Calin Juravle7865ac72017-06-28 11:03:12 -070010014 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010015 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
10016 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -070010017 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010018 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -070010019 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -080010020 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010021 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -070010022 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010023
10024 // Make a pretend boot-classpath.
10025 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -070010026 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +010010027 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +010010028 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010029 if (parent_loader.Get() == nullptr) {
10030 ScopedObjectAccessUnchecked soa(self);
10031 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
10032 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
10033 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
10034 } else {
10035 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
10036 }
Calin Juravle7865ac72017-06-28 11:03:12 -070010037
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010038 ArtField* shared_libraries_field =
10039 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
10040 DCHECK(shared_libraries_field != nullptr);
10041 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
10042
10043 return h_class_loader.Get();
10044}
10045
10046jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
10047 const std::vector<const DexFile*>& dex_files,
10048 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010049 jobject parent_loader,
10050 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010051 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
10052 WellKnownClasses::dalvik_system_PathClassLoader) ||
10053 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +000010054 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
10055 self->GetJniEnv()->IsSameObject(loader_class,
10056 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010057
10058 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
10059 // We could move the jobject to the callers, but all call-sites do this...
10060 ScopedObjectAccessUnchecked soa(self);
10061
10062 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010063 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010064
10065 Handle<mirror::Class> h_loader_class =
10066 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010067 Handle<mirror::ClassLoader> h_parent =
10068 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
10069 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
10070 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010071
10072 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
10073 self,
10074 dex_files,
10075 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010076 h_parent,
10077 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010078
10079 // Make it a global ref and return.
10080 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010081 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010082 return soa.Env()->NewGlobalRef(local_ref.get());
10083}
10084
Calin Juravle7865ac72017-06-28 11:03:12 -070010085jobject ClassLinker::CreatePathClassLoader(Thread* self,
10086 const std::vector<const DexFile*>& dex_files) {
10087 return CreateWellKnownClassLoader(self,
10088 dex_files,
10089 WellKnownClasses::dalvik_system_PathClassLoader,
10090 nullptr);
10091}
10092
Andreas Gampe8ac75952015-06-02 21:01:45 -070010093void ClassLinker::DropFindArrayClassCache() {
10094 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10095 find_array_class_cache_next_victim_ = 0;
10096}
10097
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010098void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010099 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010100 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010101 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010102 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10103 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010104 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010105 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010106 }
10107 }
10108}
10109
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010110void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10111 for (const ClassLoaderData& data : class_loaders_) {
10112 LinearAlloc* alloc = data.allocator;
10113 if (alloc != nullptr && !visitor->Visit(alloc)) {
10114 break;
10115 }
10116 }
10117}
10118
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010119void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10120 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010121 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010122 Thread* const self = Thread::Current();
10123 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010124 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010125 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010126 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010127 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10128 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010129 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010130 }
10131}
10132
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010133void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010134 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010135 std::vector<ClassLoaderData> to_delete;
10136 // Do the delete outside the lock to avoid lock violation in jit code cache.
10137 {
10138 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10139 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10140 const ClassLoaderData& data = *it;
10141 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010142 ObjPtr<mirror::ClassLoader> class_loader =
10143 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010144 if (class_loader != nullptr) {
10145 ++it;
10146 } else {
10147 VLOG(class_linker) << "Freeing class loader";
10148 to_delete.push_back(data);
10149 it = class_loaders_.erase(it);
10150 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010151 }
10152 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010153 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010154 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010155 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010156 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010157}
10158
Mathieu Chartier65975772016-08-05 10:46:36 -070010159class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10160 public:
10161 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10162 : method_(method),
10163 pointer_size_(pointer_size) {}
10164
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010165 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010166 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10167 holder_ = klass;
10168 }
10169 // Return false to stop searching if holder_ is not null.
10170 return holder_ == nullptr;
10171 }
10172
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010173 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010174 const ArtMethod* const method_;
10175 const PointerSize pointer_size_;
10176};
10177
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010178ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010179 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10180 CHECK(method->IsCopied());
10181 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10182 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010183 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010184}
10185
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010186ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10187 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010188 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010189 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010190 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010191}
10192
Vladimir Markod1f73512020-04-02 10:50:35 +010010193bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
10194 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10195 LOG(FATAL) << "UNREACHABLE";
10196 UNREACHABLE();
10197}
10198
Calin Juravle33787682019-07-26 14:27:18 -070010199bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10200 REQUIRES_SHARED(Locks::mutator_lock_) {
10201 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10202 LOG(FATAL) << "UNREACHABLE";
10203 UNREACHABLE();
10204}
10205
10206bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10207 REQUIRES_SHARED(Locks::mutator_lock_) {
10208 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10209 LOG(FATAL) << "UNREACHABLE";
10210 UNREACHABLE();
10211}
10212
10213bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10214 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10215 LOG(FATAL) << "UNREACHABLE";
10216 UNREACHABLE();
10217}
10218
Calin Juravle2c2724c2021-01-14 19:54:23 -080010219void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10220 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10221 LOG(FATAL) << "UNREACHABLE";
10222 UNREACHABLE();
10223}
10224
Roland Levillain0e840272018-08-23 19:55:30 +010010225// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010226template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010227 uint32_t method_idx,
10228 Handle<mirror::DexCache> dex_cache,
10229 Handle<mirror::ClassLoader> class_loader,
10230 ArtMethod* referrer,
10231 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010232template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010233 uint32_t method_idx,
10234 Handle<mirror::DexCache> dex_cache,
10235 Handle<mirror::ClassLoader> class_loader,
10236 ArtMethod* referrer,
10237 InvokeType type);
10238
Roland Levillain0e840272018-08-23 19:55:30 +010010239// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010240template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010241 Thread* self,
10242 ObjPtr<mirror::Class> java_lang_Class,
10243 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010244template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010245 Thread* self,
10246 ObjPtr<mirror::Class> java_lang_Class,
10247 uint32_t class_size);
10248
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010249} // namespace art